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 |
|---|---|---|---|---|---|---|
0d5c4e27b1835aa31ed83734b4cd199c9fde847b | TypeScript | gustavofsantos/tsoid | /src/promises/__tests__/either.test.ts | 3 | 3 | import { either } from '../../index';
describe('either', () => {
const successCallback = jest.fn((n: number) => n + 1);
const errorCallback = jest.fn(() => 9);
it('Should call the success callback', async () => {
const action = () => Promise.resolve(0);
const res = await either(successCallback, errorCallback, action);
expect(res).toBe(1);
});
it('Should call the error callback', async () => {
// eslint-disable-next-line sonarjs/no-duplicate-string
const action = () => Promise.reject(new Error('Some error'));
const res = await either(successCallback, errorCallback, action);
expect(res).toBeInstanceOf(Error);
expect((res as Error).message).toBe('Some error');
});
it('Should call the error callback if the action resolves to an Error', async () => {
const action = () => Promise.resolve(new Error('Some error'));
const res = await either(successCallback, errorCallback, action);
expect(res).toBe(9);
});
});
|
47f3e4aac114c8cd6524a7f9475c0074a8978221 | TypeScript | davidpet/tutorials | /Angular/reactive-form/src/app/forbidden-name-validator.ts | 2.875 | 3 | import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";
/** A name can't match the given regular expression */
// Gets custom object on error(s) and null on success.
// You don't need to include it in a module because it's
// just a function call.
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? {forbiddenName: {value: control.value}} : null;
};
}
|
6b81b31f259db00c2cf43e52d9db7635de23c507 | TypeScript | xmclark/beyondtabletop | /src/app/models/common/base.ts | 2.890625 | 3 | export class BtBase {
version?: number
id: string
getProto() {
return {}
}
getLookup() {
return {}
}
constructor(init = {}) {
const self = this
const proto: any = self.getProto()
const lookup = self.getLookup()
const randomSecureString = (length = 12) => {
let text = ''
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
const initArray = (slug, array) => {
self[slug] = []
const construct = !!array[0] ? array[0].constructor : lookup[slug]
init[slug].forEach(item => {
self[slug].push(new construct(item))
})
}
const initObject = (slug, item) => {
self[slug] = new item.constructor(init[slug])
}
const initPrimitive = slug => {
self[slug] = init[slug]
}
proto.id = randomSecureString()
Object.assign(self, proto)
Object.keys(proto).forEach(slug => {
const item = proto[slug]
if (init[slug] !== undefined) {
if (typeof item === 'object' && item !== null) {
if (item instanceof Array) {
initArray(slug, item)
} else {
initObject(slug, item)
}
} else {
initPrimitive(slug)
}
}
})
}
updateModel(incoming, remoteChanges, localChanges) {
const conflicts = []
// This compares changes between remote and local. we start by removing
// the property, so if a change to the same object occurrs we know about it
// Then we push remote and local addresses to the conflicts array
const checkConflicts = () => {
const mapper = x => x.substr(0, x.lastIndexOf('.'))
const importantConflict = (a, b) => a.includes('_added') || a.includes('_removed') || b.includes('_added') || b.includes('_removed')
const localMapped = localChanges.list.map(mapper)
remoteChanges.list.map(mapper).forEach((x, remoteIndex) => {
const localIndex = localMapped.indexOf(x)
if (localIndex > -1) {
const isImportantConflict = importantConflict(remoteChanges.list[remoteIndex], localChanges.list[localIndex])
const exactSameChange = remoteChanges.list[remoteIndex] === localChanges.list[localIndex]
if (isImportantConflict || exactSameChange) {
conflicts.push({
remote: remoteChanges.list[remoteIndex],
local: localChanges.list[localIndex]
})
}
}
})
}
// Simple recursive function to interate through the changes lookup
// and remove the conflicting change
const removeConflict = (parent, segments) => {
const segment = segments.shift()
const segmentChanges = parent.changes && parent.changes.includes(segment)
if (segmentChanges) {
parent.changes.splice(parent.changes.indexOf(segment), 1)
} else if (parent[segment] && segments.length > 0) {
removeConflict(parent[segment], segments)
} else {
delete parent[segment]
}
}
// The only conflict we have to manually address is if a local item gets
// added and remote doesn't know about it yet. OR if a remote deletes something
// we were still editing locally
const resolveConflicts = () => {
conflicts.forEach(conflict => {
let segments;
if (conflict.remote.includes('_removed')) {
segments = conflict.remote.replace(/base\.|\._removed/gi, '').split('.')
removeConflict(remoteChanges.lookup, segments)
} else {
segments = conflict.remote.replace(/base\./gi, '').split('.')
removeConflict(remoteChanges.lookup, segments)
}
})
}
// Resets changes object to initial state
const resetChanges = () => {
remoteChanges.lookup = {}
}
// Guard against version rollbacks
if (this.version && incoming.version < this.version) {
resetChanges()
return
}
checkConflicts()
if (conflicts.length > 0) {
resolveConflicts()
}
this.commitUpdate(incoming, remoteChanges.lookup)
resetChanges()
}
commitUpdate(incoming, lookup) {
const proto: any = this.getProto()
const arrayLookup: any = this.getLookup()
const self: any = this
// if the lookup object has a changes object on it, there
// are properties that need to be addressed here
// we start by ignoring all properties that begin with _
// becuase those are handled elsewhere
// Once we finish we delete the lookup id and changes
const arrayFullyDeleted = (a, b, item) => {
return item instanceof Array && a && !b
}
const handlePrimitives = (a, b) => {
if (!!lookup.changes) {
lookup.changes
.filter(x => x.charAt(0) !== '_')
.map(slug => ({ slug, item: proto[slug] }))
// Filter out non primitive
// Unless an entire array has been deleted
.filter(({item, slug}) => typeof item !== 'object' || item === null || arrayFullyDeleted(a[slug], b[slug], item))
.forEach(({slug}) => a[slug] = b[slug])
delete lookup.changes
delete lookup.id
}
}
// Iterate over the given lookup IDs, check for associated objects on
// both a and b (y and z respectively). If this associated object has
// changes, we take care of the _ prefaced actions, namely: removing
// and adding objects. Finally we send it through the recursive process
// if both objects exist to check for further changes
const updateArray = (a, b, slug) => {
Object.keys(lookup[slug]).forEach(id => {
const construct = !!proto[slug][0] ? proto[slug][0].constructor : arrayLookup[slug]
const y = a[slug].find(x => x.id === id)
const z = b[slug].find(x => x.id === id)
if (!!lookup[slug][id].changes) {
if (lookup[slug][id].changes.includes('_added')) {
a[slug] = a[slug] || []
a[slug].push(new construct(z))
}
if (lookup[slug][id].changes.includes('_removed')) {
a[slug].splice(a[slug].indexOf(y), 1)
}
}
if (!!y && !!z) {
y.commitUpdate(z, lookup[slug][id])
}
})
}
// Check through proto keys that exist in our lookup and send them to
// updateArray or into recursive commitUpdate. Primitives are handled separately
const updateObject = (a, b) => {
Object.keys(proto)
// Filter out slugs that aren't in the lookup
.filter(x => lookup[x] !== undefined)
.map(slug => ({ slug, item: proto[slug] }))
// Filter out slugs defined as primitives in the proto
.filter(({item}) => typeof item === 'object' && item !== null)
.forEach(({item, slug}) => {
if (item instanceof Array) {
updateArray(a, b, slug)
} else {
a[slug].commitUpdate(b[slug], lookup[slug])
}
})
}
handlePrimitives(self, incoming)
updateObject(self, incoming)
}
compareChanges(rival, changesList, changesLookup, context, isNew = false) {
const proto: any = this.getProto()
const arrayLookup: any = this.getLookup()
const self: any = this
// Sometimes data is null in one place and undefined in the other place
// In this case we usually want to ignore the property, since we don't
// want to send any undefined values to Firebase
const nullAndUndefined = (a, b) => {
return (a === null && b === undefined) || (a === undefined && b === null)
}
const anyUndefinedValules = (a, b) => {
return (isNew && b === undefined) || a === undefined
}
// We never want to nullify or undefined-ify ID on any object
const overwritingIdWithNothing = (a, b, slug) => slug === 'id' && isNew && !!a && !b
const shouldAddPrimitiveChange = (a, b, slug) => {
return !nullAndUndefined(a, b) && !anyUndefinedValules(a, b) && !overwritingIdWithNothing(a, b, slug)
}
// JSON stringify comparison
const identicalObjects = (a, b) => {
return JSON.stringify(a) === JSON.stringify(b)
}
// We add changes to an array: changesList and an object: changesLookup
// We can pass in different lookup object and different context for the
// given changes. If the change doesn't exist on the array we add it.
// However, duplicate changes can be added to the lookup
const addChange = (id, property, changesObject = changesLookup, context_mod = '') => {
changesObject.id = (id || '')
changesObject.changes = changesObject.changes || []
changesObject.changes.push(property)
const change = `${context}${context_mod}.${property}`
if (changesList.indexOf(change) === -1) {
changesList.push(change)
}
}
// Just barely still need this helper method.
const addChangeForSlug = slug => {
addChange(self.id, slug)
}
// This logs if an item was removed or added
// action is a string of either '_added' or '_removed'
const addArrayChange = (slug, id, action) => {
addChange(id, action, changesLookup[slug][id], `.${slug}.${id}`)
}
// Clean up the changes object, removing all empties
const removeEmptyObjects = (parent, slug) => {
if (Object.keys(parent[slug]).length === 0) {
delete parent[slug]
}
}
const findIndex = (array, id) => {
let index = array.findIndex(x => x.id === id)
if (index < 0) {
index = array.length
}
return index
}
const compareIndex = (array, a, b) => {
return findIndex(array, a.id) - findIndex(array, b.id)
}
// Compare 2 arrays on a given slug (Example: character.feats)
const compareArray = (a, b, slug) => {
// Grab the construct (aka the Class of the array's iterator)
// from either the first element in the prototype's array or
// from the given lookup object for that array
const construct = !!proto[slug][0] ? proto[slug][0].constructor : arrayLookup[slug]
// Initialize the change object at the slug if we need to
changesLookup[slug] = changesLookup[slug] || {}
// If both arrays exist, that means a whole array wasn't added or deleted
if (!!a && !!b) {
// Iterate over a every time because a is always Classed rather
// than just raw object data. we use y as the iterator for a and
// z for the iterator for b. x is reserved as a generic interator
a.forEach(y => {
// initialize changes object at the given y.id
changesLookup[slug][y.id] = changesLookup[slug][y.id] || {}
// Find z by y's ID. If we find it, we compare the two
// found objects' properties. Otherwise we log that an
// item was either added or removed, depending on if
// the incoming data is old or new
const z = b.find(x => x.id === y.id)
if (!!z) {
new construct(y).compareChanges(z, changesList, changesLookup[slug][y.id], `${context}.${slug}.${y.id}`, isNew)
} else {
addArrayChange(slug, y.id, (isNew ? '_removed' : '_added'))
}
removeEmptyObjects(changesLookup[slug], y.id)
})
// Because we iterated over a, we need lookup if there are items
// in b that weren't in a. if we find any, we initialize the
// changes object and log them as either added or removed items
const aIdMap = a.map(x => x.id)
b.filter(x => !aIdMap.includes(x.id)).forEach(z => {
changesLookup[slug][z.id] = changesLookup[slug][z.id] || {}
addArrayChange(slug, z.id, (isNew ? '_added' : '_removed'))
})
// Finally after applying the changes to each array item, we need
// to ensure the items are in the same order for incoming changes
if (isNew) {
a.sort((x, y) => compareIndex(b, x, y))
}
// If one array exists and it has any substance (aka more than 0 length)
// then we need to treat this slug like we would treat a primitive
// because we need to add or delete the entire array.
// If it's an empty array in one spot and undefined in the other
// that means there's been no change
} else if (!!a && a.length > 0 || !!b && b.length > 0) {
addChangeForSlug(slug)
}
removeEmptyObjects(changesLookup, slug)
}
// Initialize the changes object at slug, recurse into compareChanges
// after we finish we clean up empty objects
const compareObject = (slug) => {
changesLookup[slug] = {}
self[slug].compareChanges(rival[slug], changesList, changesLookup[slug], `${context}.${slug}`, isNew)
removeEmptyObjects(changesLookup, slug)
}
// construct two new Objects from the data sets given
// if they match then we can just get out of here
if (identicalObjects(new self.constructor(self), new self.constructor(rival))) {
return
}
// Iterate over the keys given on the proto. If a key doesn't exist
// on the proto, we don't care about it.
Object.keys(proto).forEach(slug => {
const item = proto[slug]
// This comparison is very likely unhelpful for everything except
// primitive values, but it's here to stay for now
if (self[slug] !== rival[slug]) {
if (typeof item === 'object' && item !== null) {
// If it's an array, we send it to our local compareArray method
// Otherwise it's an object and send it to compareObject
if (item instanceof Array) {
compareArray(self[slug], rival[slug], slug)
} else {
compareObject(slug)
}
} else {
// Finaly if it's not an object it must be primitive, so we
// do a null/undefined comparison check and add the change
if (shouldAddPrimitiveChange(self[slug], rival[slug], slug)) {
addChangeForSlug(slug)
}
}
}
})
return
}
databaseSafe(): any {
const proto: any = this.getProto()
const keys = [...Object.keys(proto), 'id']
const self: any = this
const safe: any = {}
keys.forEach(slug => {
const item = proto[slug]
if (Array.isArray(item)) {
if (self[slug] && self[slug].length > 0) {
safe[slug] = self[slug].map(x => x.databaseSafe())
}
} else if (typeof item === 'object' && item !== null) {
safe[slug] = self[slug].databaseSafe()
} else if (self[slug] !== undefined && self[slug] !== null) {
safe[slug] = self[slug]
}
})
return safe
}
}
|
e748e9455716b8281c65d2efe4f4a211af38ef70 | TypeScript | stteper/inn_generator | /src/common/bik_generator.ts | 2.9375 | 3 | import BaseGenerator from './generator';
class BikGenerator extends BaseGenerator {
generate():string {
const coeffs = ['02','06','09','13','16','21','23','31','39','43','48','51','55','59','62','67','72','74'];
let midDigits = '';
do {
midDigits = this.generateRndStr(2);
} while (coeffs.indexOf(midDigits)!== -1);
const lastDigits = Math.floor(Math.random() * 950+ 50);
return '04' + midDigits + this.generateRndStr(2) + (lastDigits < 100 ? '0'+ String(lastDigits) : String(lastDigits));
}
}
export default BikGenerator; |
65c184bdc814f7eaf9b003e45b9f8becc67dc5ef | TypeScript | DawnbrandBots/tournament-organizer | /src/Player.ts | 3.296875 | 3 | export interface Result {
match: string;
opponent: string;
result?: "w" | "l" | "d";
}
/** Class representing a player. */
export class Player {
/**
* Name of the player.
* @type {String}
*/
private alias: string;
/**
* Alphanumeric string ID.
* @type {String}
*/
readonly id: string;
/**
* Value to sort players.
* @type {?Number}
*/
readonly seed: number | null;
/**
* Number of match points the player has.
* @type {Number}
*/
public matchPoints: number;
/**
* Number of matches played.
* @type {Number}
*/
public matches: number;
/**
* Number of game points the player has.
* @type {Number}
*/
public gamePoints: number;
/**
* Number of games played.
* @type {Number}
*/
public games: number;
/**
* Number of initial byes assigned.
* @type {Number}
*/
readonly initialByes: number;
/**
* Number of byes assigned.
* @type {Number}
*/
public byes: number;
/**
* Array of results. Objects include match ID, opponent ID, and result ('w', 'l', or 'd').
* @type {Object[]}
*/
public results: Result[];
/**
* Color preference for chess tournaments.
* Add 1 for white (player one) and subtract 1 for black (player two).
* @type {Number}
*/
public colorPref: number;
/**
* Array of colors that player has played in a chess tournament.
* @type {String[]}
*/
public colors: string[];
/**
* If the player is still in the tournament.
* @type {Boolean}
*/
public active: boolean;
/**
* Tiebreaker values.
* @type {Object}
*/
readonly tiebreakers: {
matchWinPctM: number;
matchWinPctP: number;
oppMatchWinPctM: number;
oppMatchWinPctP: number;
gameWinPct: number;
oppGameWinPct: number;
oppOppMatchWinPct: number;
solkoff: number;
cutOne: number;
median: number;
neustadtl: number;
cumulative: number;
oppCumulative: number;
};
/**
* An object to store any additional information.
* @type {Object}
* @default {}
*/
private etc: { [key: string]: string };
/**
* Create a new player.
* @param {String|Object} alias String to be the player's name. If an object, it is a player being reclassed.
* @param {String} id String to be the player ID.
* @param {?Number} seed Number to be used as the seed.
*/
constructor(alias: string | Player, id?: string, seed?: number | null) {
if (arguments.length === 1) {
const oldPlayer: Player = arguments[0];
// manually set defaults to satisfy ts
oldPlayer.results ||= [];
oldPlayer.colors ||= [];
// manually assign to satisfy ts
this.alias = oldPlayer.alias;
this.id = oldPlayer.id;
this.seed = oldPlayer.seed;
this.matchPoints = oldPlayer.matchPoints;
this.matches = oldPlayer.matches;
this.gamePoints = oldPlayer.gamePoints;
this.games = oldPlayer.games;
this.initialByes = oldPlayer.initialByes;
this.results = oldPlayer.results;
this.byes = oldPlayer.byes;
this.colorPref = oldPlayer.colorPref;
this.colors = oldPlayer.colors;
this.active = oldPlayer.active;
this.tiebreakers = oldPlayer.tiebreakers;
this.etc = oldPlayer.etc;
} else {
this.alias = alias.toString();
this.id = id!.toString();
this.seed = typeof seed === "number" ? seed : null;
this.matchPoints = 0;
this.matches = 0;
this.gamePoints = 0;
this.games = 0;
this.initialByes = 0;
this.byes = 0;
this.results = [];
this.colorPref = 0;
this.colors = [];
this.active = true;
this.tiebreakers = {
matchWinPctM: 0,
matchWinPctP: 0,
oppMatchWinPctM: 0,
oppMatchWinPctP: 0,
gameWinPct: 0,
oppGameWinPct: 0,
oppOppMatchWinPct: 0,
solkoff: 0,
cutOne: 0,
median: 0,
neustadtl: 0,
cumulative: 0,
oppCumulative: 0
};
this.etc = {};
}
}
}
|
90b07b9118275a9cf962f1b34cafc9a5e35cf71e | TypeScript | NaomiLea/ji-cloud | /frontend/storybook/src/components/core/inputs/textarea-underline.ts | 2.828125 | 3 | import {argsToAttrs} from "@utils/attributes";
import "@elements/core/inputs/textarea-underline";
export default {
title: "Core / Inputs"
}
interface Args {
label: string,
placeholder: string,
value: string,
width:number,
rows:number,
}
const DEFAULT_ARGS:Args = {
label: "hello",
placeholder: "Jane Doe",
value: "world",
width: 300,
rows: 10,
}
export const TextAreaUnderline = (props?:Partial<Args>) => {
props = props ? {...DEFAULT_ARGS, ...props} : DEFAULT_ARGS;
const {} = props
const {width, ...textProps} = props
return `
<div style="width:${width}px">
<input-textarea-underline ${argsToAttrs(textProps)}></input-textarea-underline>
</div>
`;
}
TextAreaUnderline.args = DEFAULT_ARGS; |
a22e0983c7242fa5048c985e2c2762fc03a6e84c | TypeScript | BryanPan342/awscdk-change-analyzer | /packages/@aws-c2a/engine/lib/model-diffing/entity-matchers/component-properties-matcher.ts | 2.703125 | 3 | import { Component, ComponentPropertyValue, PropertyPath, CompleteTransition, Transition } from '@aws-c2a/models';
import { PropertyDiff, PropertyDiffCreator } from '../property-diff';
/**
* ComponentPropertyValue similarity evaluator for use with matchEntities.
*
* Matches ComponentProperties based on their similarity.
* The metadata object in the matcher results will be the PropertyDiff
*
* K values are the properties' keys/identifiers
*/
export function propertySimilarityEvaluatorCreator<K extends (string | number)>(
componentTransition: Transition<Component>,
keyAToProperty: Record<K, ComponentPropertyValue>,
keyBToProperty: Record<K, ComponentPropertyValue>,
basePathA?: PropertyPath,
basePathB?: PropertyPath,
){
return ({v1: keyV1, v2: keyV2}: CompleteTransition<K>): [number, PropertyDiff] => {
const propDiff = new PropertyDiffCreator(componentTransition).create(
keyAToProperty[keyV1],
keyBToProperty[keyV2],
[...(basePathA ?? []), keyV1],
[...(basePathB ?? []), keyV2]);
return [propDiff.similarity, propDiff];
};
} |
ad5272cba52f8f9cc2b2f961faee615e9c5c0323 | TypeScript | knowit/program.kds.knowit.no | /helpers/time.ts | 3.65625 | 4 | class Time {
public hours: number
public minutes: number
public constructor(hours: string = "0", minutes: string = "0") {
this.hours = parseInt(hours);
this.minutes = parseInt(minutes);
}
public toString(del: string = "."): string {
return ("0" + this.hours).slice(-2) + del + ("0" + this.minutes).slice(-2);
}
public add(time: Time): Time {
this.hours += time.hours + Math.floor((this.minutes + time.minutes) / 60);
this.minutes = (this.minutes + time.minutes) % 60;
return this;
}
public copy(): Time {
const t = new Time();
t.add(this);
return t;
}
// Returns diff in minutes
public diff(time: Time): Number {
return Math.abs(this.hours * 60 + this.minutes - time.minutes - time.hours * 60);
}
public static fromString(str: string, del: string = '.') {
const strs = str.split(del);
return new Time(strs[0], strs[1]);
}
public static fromNumber(int: number) {
var tt = int.toString().substring(0, int.toString().length-2)
var mm = int.toString().substring(int.toString().length-2, int.toString().length)
return new Time(tt, mm);
}
}
interface Talk {
type: string,
duration?: string
}
function getDuration(talk: Talk): Time {
switch (talk.type) {
case "Lightning talk (10 minutes)": return new Time("00", "10");
case "Short presentation (30 minutes)": return new Time("00", "30");
case "Long presentation (60 minutes)": return new Time("01", "00");
case "Workshop (90 minutes)":return new Time("01", "30");
case "Workshop (60 minutes)":return new Time("01", "00");
case "Workshop (30 minutes)":return new Time("00", "30");
}
return new Time();
}
export {
Time,
getDuration
}; |
031eee1cc376e5609e7938707d486b9566ea8220 | TypeScript | vitalim4/quize-questions | /src/app/store/questions-actions.ts | 2.6875 | 3 | import {Action} from '@ngrx/store';
import {Question} from './models/question.model';
export enum QuestionActions {
LOAD_QUESTION = '[Questions] Load Question',
LOAD_QUESTION_FAILURE = '[Questions] Load Question Failure',
LOAD_QUESTION_SUCCESS = '[Questions] Load Question Success',
INIT_STATE = '[Questions] Init State',
UPDATE_INDEX = '[Questions] Update Index',
SELECT_ANSWER = '[Questions] Select Answer',
OK_CLICKED = '[Questions] OK Clicked'
}
export class SelectAnswer implements Action {
readonly type = QuestionActions.SELECT_ANSWER;
constructor(public payload: { questionId: number, answerText: string }) {
}
}
export class OkClicked implements Action {
readonly type = QuestionActions.OK_CLICKED;
constructor(public payload: { questionId: number, answerText: string }) {
}
}
export class InitState implements Action {
readonly type = QuestionActions.INIT_STATE;
}
export class LoadQuestionAction implements Action {
readonly type = QuestionActions.LOAD_QUESTION;
}
export class UpdateSelectedIndex implements Action {
readonly type = QuestionActions.UPDATE_INDEX;
constructor(public payload: number) {
}
}
export class LoadQuestionFailureAction implements Action {
readonly type = QuestionActions.LOAD_QUESTION_FAILURE;
constructor(public payload: { error: string }) {
}
}
export class LoadQuestionSuccessAction implements Action {
readonly type = QuestionActions.LOAD_QUESTION_SUCCESS;
constructor(public payload: Question) {
}
}
export type QuestionsActions =
LoadQuestionAction
| LoadQuestionFailureAction
| LoadQuestionSuccessAction
| UpdateSelectedIndex
| InitState
| SelectAnswer
| OkClicked;
|
ef151b443f64ee4f48fbfc71d71b20f095f426cf | TypeScript | uniquid/uidcore-js | /src/impl/Bcoin/BcoinCEV/TX/varint.ts | 2.90625 | 3 | /**!
*
* Copyright 2016-2018 Uniquid Inc. or its affiliates. All Rights Reserved.
*
* License is in the "LICENSE" file accompanying this file.
* See the License for the specific language governing permissions and limitations under the License.
*
*/
/**
* varint utils from https://github.com/chrisdickinson/varint
*/
// tslint:disable:no-magic-numbers no-bitwise
export const decodeVarInt = (buf: number[], offset = 0) => {
const MSB = 0x80
const REST = 0x7f
const l = buf.length
let res = 0
let shift = 0
let counter = offset
let b
do {
if (counter >= l) {
throw new RangeError('Could not decode varint')
}
b = buf[counter++]
res += shift < 28 ? (b & REST) << shift : (b & REST) * Math.pow(2, shift)
shift += 7
} while (b >= MSB)
return { res, length: counter - offset }
}
export const encodeVarint = (num: number, offset = 0) => {
const MSB = 0x80
const REST = 0x7f
const MSBALL = ~REST
const INT = Math.pow(2, 31)
const res = []
const oldOffset = offset
while (num >= INT) {
res[offset++] = (num & 0xff) | MSB
num /= 128
}
while (num & MSBALL) {
res[offset++] = (num & 0xff) | MSB
num >>>= 7
}
res[offset] = num | 0
return { res, length: offset - oldOffset + 1 }
}
// export const varIntLength = (value: number) => {
// const N1 = Math.pow(2, 7)
// const N2 = Math.pow(2, 14)
// const N3 = Math.pow(2, 21)
// const N4 = Math.pow(2, 28)
// const N5 = Math.pow(2, 35)
// const N6 = Math.pow(2, 42)
// const N7 = Math.pow(2, 49)
// const N8 = Math.pow(2, 56)
// const N9 = Math.pow(2, 63)
// return value < N1
// ? 1
// : value < N2
// ? 2
// : value < N3
// ? 3
// : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10
// }
|
9afb6b46a28198bb2abfffbf9b8083854253af1f | TypeScript | rayene-raffa/wunder-fleet | /src/app/store/actions/register.actions.ts | 2.53125 | 3 | import { Action } from '@ngrx/store';
import {
IPersonalInformation,
IAddress,
IPaymentInformation,
INextOrPreviousStep
} from 'src/app/models/registration-information.interface';
export enum ERegisterActions {
StartRegister = '[Register] Start',
NextOrPreviousStep = '[Register] Move to next or previous step',
SubmitPersonalInformation = '[Register] Submit Personal Information',
SubmitAddress = '[Register] Submit Address',
SubmitPaymentInformation = '[Register] Submit Payment Information',
RegisterSuccess = '[Register] Registration Successful',
}
export class StartRegister implements Action {
public readonly type = ERegisterActions.StartRegister;
}
export class NextOrPreviousStep implements Action {
public readonly type = ERegisterActions.NextOrPreviousStep;
constructor(public payload: INextOrPreviousStep) {}
}
export class SubmitPersonalInformation implements Action {
public readonly type = ERegisterActions.SubmitPersonalInformation;
constructor(public payload: IPersonalInformation) {}
}
export class SubmitAddress implements Action {
public readonly type = ERegisterActions.SubmitAddress;
constructor(public payload: IAddress) {}
}
export class SubmitPaymentInformation implements Action {
public readonly type = ERegisterActions.SubmitPaymentInformation;
constructor(public payload: IPaymentInformation) {}
}
export class RegisterSuccess implements Action {
public readonly type = ERegisterActions.RegisterSuccess;
constructor(public payload: IPaymentInformation['paymentDataId']) {}
}
export type RegisterActions =
| StartRegister
| NextOrPreviousStep
| SubmitPersonalInformation
| SubmitAddress
| SubmitPaymentInformation
| RegisterSuccess;
|
8fb0571c5b111a6067cb911b36fb0d7bebc77432 | TypeScript | ev3alexli/pxt-maplerobot | /maplerobot.ts | 2.890625 | 3 |
/**
* Use this file to define custom functions and blocks.
* Read more at https://makecode.mindstorms.com/blocks/custom
*/
enum movingSideEnum {
LonL = 11,
LonR = 12,
RonL = 31,
RonR = 32
}
enum portEnum {
LEFT_COLOR = 1,
RIGHT_COLOR = 3,
MIDDLE_COLOR = 4,
GYRO_SENSOR = 2
}
enum positionEnum {
LEFT = 1,
RIGHT = 2,
MIDDLE = 3
}
enum stopCondColorEnum {
LINE_STOP = 0, // |black
DIS_STOP = 1, // |cm
ROT_STOP = 2, // |rotation
DEG_STOP = 3, // |degree
TIME_STOP = 4 // |second
}
enum stopCondGyroEnum {
LINE_STOP_1 = 10, // |black
LINE_STOP_3 = 30,
DIS_STOP = 1, // |cm
ROT_STOP = 2, // |rotation
DEG_STOP = 3, // |degree
TIME_STOP = 4 // |second
}
/**
* Custom blocks
*/
//% weight=100 color=#e01515 icon="枫"
namespace MapleRobot {
/**
* Moving along the black line and stopping with multiple conditions
* @param movingSide Which side of moving, eg: 11
* @param stopCondition Which condition of stopping, eg: 0
* @param stopValue Which value of stopping, eg: 15
* @param power Which power of robot running, eg: 80
*/
//% block
//% group="Color"
export function colorMove(movingSide: movingSideEnum, stopCondition: stopCondColorEnum, stopValue: number, power: number): void {
power = (-1) * Math.abs(power)
////////////////////////////////////////////
// color sensor 0:black, 100:white
////////////////////////////////////////////
//
// 1. get input parameters
// let movingSide = 11 // 11 left color sensor moving along left side of black line 12, 31, 32
// let stopCondition = 1 // 0 stop on black line with another color sensor
// let stopValue = 50 // stop when the stop color sensor got color less than stopValue
// let power = -80 // default is -80, because out robot is backwards
let wheelDiameter = 7 // will only be used in DIS_STOP
//
////////////////////////////////////////////
// init
////////////////////////////////////////////
// 2. middle value of two colors black and white,
// if side=LEFT turn=currentLight-50,
// other turn=50-currentLight for direction
let MIDDLE_VALUE_OF_TWO_COLOR = 50
////////////////////////////////////////////
// start
////////////////////////////////////////////
// 7. reset
motors.largeBC.reset()
control.timer1.reset()
// 8. checking color sensor
let moveColorSensor = sensors.color1
let moveColorSensorId = portEnum.LEFT_COLOR
let stopColorSensor = sensors.color3
let stopColorSensorId = portEnum.RIGHT_COLOR
// check input parameter movingSide, get moving color sensor, and stop color sensor
if (Math.floor(movingSide / 10) == portEnum.RIGHT_COLOR) {
stopColorSensorId = portEnum.LEFT_COLOR
moveColorSensor = sensors.color3
moveColorSensorId = portEnum.RIGHT_COLOR
stopColorSensor = sensors.color1
}
//
// 9. check input parameter movingSide, get moving side
let side = positionEnum.LEFT
if (movingSide % 10 == positionEnum.RIGHT) {
side = positionEnum.RIGHT
}
//
// 10. define turn
let turn = 0
//
// current color sensor light
let movingColorValue = 0
let stopColorValue = 0
//
// 11. setup PID parameters
automation.pid1.setGains(0.5, 0.3, 0.0002)
//
// 12. loop for moving the robot
let keepLooping = true
while (keepLooping) {
// check stop input
if (stopCondition == stopCondColorEnum.LINE_STOP) {
// get color from stop color sensor
stopColorValue = stopColorSensor.light(LightIntensityMode.Reflected)
if (stopColorValue < stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondColorEnum.DIS_STOP) {
let pastDistance = motors.largeB.angle() / 360 * 3.14 * wheelDiameter
pastDistance = Math.abs(pastDistance)
// brick.showString("Current Distance:", 10)
// brick.showNumber(pastDistance, 11)
if (pastDistance >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondColorEnum.ROT_STOP) {
let pastRotation = motors.largeB.angle() / 360
pastRotation = Math.abs(pastRotation)
// brick.showString("Current Distance:", 10)
// brick.showNumber(pastDistance, 11)
if (pastRotation >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondColorEnum.DEG_STOP) {
let pastDegree = motors.largeB.angle()
pastDegree = Math.abs(pastDegree)
if (pastDegree >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondColorEnum.TIME_STOP) {
if (control.timer1.millis() >= stopValue) {
keepLooping = false
}
}
//
// get color from moving color sensor
movingColorValue = moveColorSensor.light(LightIntensityMode.Reflected)
//
// turn calculation
turn = automation.pid1.compute(0.1, MIDDLE_VALUE_OF_TWO_COLOR - movingColorValue)
if (side == positionEnum.LEFT) {
turn = turn * (-1)
}
//
// assign to move steering
motors.largeBC.steer(turn, power)
//
// display information
brick.showString("Moving Color Value:", 3)
brick.showNumber(movingColorValue, 4)
brick.showString("turn Value:", 6)
brick.showNumber(turn, 7)
brick.showString("Stop Color Value:", 8)
brick.showNumber(stopColorValue, 9)
}
// set break after stop
motors.largeBC.setBrake(true)
// stop
motors.largeBC.stop()
// clear screen
brick.clearScreen()
//brick.exitProgram()
}
/**
* Moving with gyro sensor
* @param movingSide Which side of moving, eg: 11
* @param stopCondition Which condition of stopping, eg: 0
* @param stopValue Which value of stopping, eg: 15
* @param power Which power of robot running, eg: 80
*/
//% block
//% group="Gyro"
export function gyroMove(stopCondition: stopCondGyroEnum, stopValue: number, power: number): void {
// power = (-1) * Math.abs(power)
// 1. get input parameters
// let stopCondition = 3 // 0 stop on black line with another color sensor
// let stopValue = 720 // stop when the stop color sensor got color less than stopValue
// let power = -80 // default is -80, because out robot is backwards
let wheelDiameter = 7 // will only be used in DIS_STOP
//
////////////////////////////////////////////
// start
////////////////////////////////////////////
// 7. reset
motors.largeBC.reset()
control.timer1.reset()
sensors.gyro2.reset()
//
// 10. define turn
let turn = 0
//
// current sensor readings
let gyroValue = 0
let stopColorValue = 0
//
// 11. setup PID parameters
automation.pid1.setGains(3, 3, 0)
//
// 12. loop for moving the robot
let keepLooping = true
while (keepLooping) {
// check stop input
if (stopCondition == stopCondGyroEnum.LINE_STOP_1 || stopCondition == stopCondGyroEnum.LINE_STOP_3) {
// get color from stop color sensor
let stopColorSensor = sensors.color1
if (stopCondition == stopCondGyroEnum.LINE_STOP_3) {
stopColorSensor = sensors.color3
}
stopColorValue = stopColorSensor.light(LightIntensityMode.Reflected)
if (stopColorValue < stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondGyroEnum.DIS_STOP) {
let pastDistance = motors.largeB.angle() / 360 * 3.14 * wheelDiameter
pastDistance = Math.abs(pastDistance)
// brick.showString("Current Distance:", 10)
// brick.showNumber(pastDistance, 11)
if (pastDistance >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondGyroEnum.ROT_STOP) {
let pastRotation = motors.largeB.angle() / 360
pastRotation = Math.abs(pastRotation)
// brick.showString("Current Distance:", 10)
// brick.showNumber(pastDistance, 11)
if (pastRotation >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondGyroEnum.DEG_STOP) {
let pastDegree = motors.largeB.angle()
pastDegree = Math.abs(pastDegree)
if (pastDegree >= stopValue) {
keepLooping = false
}
} else if (stopCondition == stopCondGyroEnum.TIME_STOP) {
if (control.timer1.millis() >= stopValue) {
keepLooping = false
}
}
//
// get value from gyro sensor
gyroValue = sensors.gyro2.angle()
// calculate turn pid
if (power > 0) {
turn = automation.pid1.compute(0.1, gyroValue)
} else {
turn = automation.pid1.compute(0.1, 0 - gyroValue)
}
// assign to moving steering
motors.largeBC.steer(turn, power)
// display
brick.showString("Gyro Value-:", 2)
brick.showNumber(gyroValue, 3)
brick.showString("turn--:", 5)
brick.showNumber(turn, 6)
}
// set break after stop
motors.largeBC.setBrake(true)
// stop
motors.largeBC.stop()
// clear screen
brick.clearScreen()
//brick.exitProgram()
}
/**
* Turning wtih gyro sensor
* @param targetAngle Angle of turning, eg: 90
* @param turnPoint Pivot point setting, eg: 3
*/
//% block
//% group="Gyro"
export function gyroTurn(targetAngle: number, turnPoint: positionEnum): void {
// current sensor readings
let gyroValue = 0
//
// turn right
let turnRatio = 200
// turn left
if (targetAngle < 0) {
turnRatio = -200
}
//
let turnAngle = Math.abs(targetAngle)
// reset gyro sensor
sensors.gyro2.reset()
//loops.pause(100)
//
let keepLooping = true
while (keepLooping) {
// get value from gyro sensor
gyroValue = Math.abs(sensors.gyro2.angle())
// exit
if (gyroValue >= turnAngle) {
keepLooping = false
}
// calculate power
let currentPower = 0.6 * (turnAngle - gyroValue) + 6
//
if (turnPoint == positionEnum.MIDDLE) {
motors.largeBC.steer(turnRatio, currentPower)
//brick.showNumber(MIDDLE, 1)
} else if (turnPoint == positionEnum.LEFT) {
if (targetAngle > 0) {
motors.largeB.run(currentPower)
} else {
motors.largeB.run(0 - currentPower)
}
//brick.showNumber(LEFT, 1)
} else if (turnPoint == positionEnum.RIGHT) {
if (targetAngle < 0) {
motors.largeC.run(currentPower)
} else {
motors.largeC.run(0 - currentPower)
}
//brick.showNumber(RIGHT, 1)
}
// display
brick.showString("Gyro: ", 2)
brick.showNumber(gyroValue, 3)
brick.showString("Power: ", 5)
brick.showNumber(currentPower, 6)
}
motors.largeBC.setBrake(true)
motors.largeBC.stop()
}
/**
* Moving to black line
* @param count Count of repetition, eg: 2
*/
//% block
//% group="Color"
export function moveToBlack(count: number): void {
motors.largeB.setBrake(true)
motors.largeC.setBrake(true)
for (let i = 0; i < count; i++) {
let colorBlack1 = false
let colorBlack2 = false
control.runInParallel(function () {
motors.largeB.run(-16)
})
control.runInParallel(function () {
motors.largeC.run(-16)
})
while (true) {
if (sensors.color1.light(LightIntensityMode.Reflected) <= 15) {
brick.showString("motorC", 1)
if (colorBlack2) {
pause(10)
}
motors.largeC.stop()
colorBlack1 = true
}
if (sensors.color3.light(LightIntensityMode.Reflected) <= 15) {
brick.showString("motorB", 2)
if (colorBlack1) {
pause(10)
}
motors.largeB.stop()
colorBlack2 = true
}
if (colorBlack1 && colorBlack2) {
colorBlack1 = false
colorBlack2 = false
motors.largeBC.steer(0, 16, 40, MoveUnit.Degrees)
break;
}
pause(50)
}
}
}
/**
* Backing to black line
* @param count Count of repetition, eg: 2
*/
//% block
//% group="Color"
export function backToBlack(count: number): void {
motors.largeB.setBrake(true)
motors.largeC.setBrake(true)
for (let i = 0; i < count; i++) {
let colorBlack1 = false
let colorBlack2 = false
control.runInParallel(function () {
motors.largeB.run(16)
})
control.runInParallel(function () {
motors.largeC.run(16)
})
while (true) {
if (sensors.color1.light(LightIntensityMode.Reflected) <= 15) {
brick.showString("motorC", 1)
if (colorBlack2) {
pause(10)
}
motors.largeC.stop()
colorBlack1 = true
}
if (sensors.color3.light(LightIntensityMode.Reflected) <= 15) {
brick.showString("motorB", 2)
if (colorBlack1) {
pause(10)
}
motors.largeB.stop()
colorBlack2 = true
}
if (colorBlack1 && colorBlack2) {
colorBlack1 = false
colorBlack2 = false
motors.largeBC.steer(0, -16, 40, MoveUnit.Degrees)
break;
}
pause(50)
}
}
}
/**
* Gyro distance with Acceleration and decceleration
* @param distance Distance of movement, eg: 100
*/
//% block
//% group="Gyro"
export function accelerationDistance(distance: number): void {
let minSpeed = -10
let turn = 0
let power = 0
let gyroValue = 0
let keepLooping = true
let wheelDiameter = 6.24
let DYNAMIC_SPEED_ROTATION = 1.5
let disRotation = distance / (3.14 * wheelDiameter)
// setup PID parameters
automation.pid1.setGains(3, 3, 0)
// reset gyro
sensors.gyro2.reset()
//sensors.gyro2.calibrate()
// reset and start motor
//motors.largeBC.reset()
motors.largeBC.run(minSpeed)
pause(100)
// loop
keepLooping = true
while (keepLooping) {
////// current rotation
let RofB = motors.largeB.angle() / 360
RofB = Math.abs(RofB)
////// check condition, calculate power
if (disRotation >= DYNAMIC_SPEED_ROTATION * 2) {
// 1.1
if (RofB <= DYNAMIC_SPEED_ROTATION) {
power = 100 * RofB / DYNAMIC_SPEED_ROTATION
}
// 1.2
else if (RofB > disRotation - DYNAMIC_SPEED_ROTATION) {
power = 100 * (disRotation - RofB) / DYNAMIC_SPEED_ROTATION
}
// 1.3
else {
power = 100
}
} else {
// 2.1
if (RofB < disRotation / 2) {
power = 100 * (RofB / (disRotation / 2))
}
// 2.2
else {
power = 100 * (disRotation - RofB) / (disRotation / 2)
}
}
////// get value from gyro sensor
gyroValue = sensors.gyro2.angle()
// calculate turn pid
turn = automation.pid1.compute(0.1, 0 - gyroValue)
// assign to moving steering
motors.largeBC.steer(turn, 0 - Math.abs(power) + minSpeed)
////// check exit
let pastDistance = motors.largeB.angle() / 360 * 3.14 * wheelDiameter
pastDistance = Math.abs(pastDistance)
if (pastDistance >= distance) {
keepLooping = false
}
// display
brick.showString("Gyro Value-:", 2)
brick.showNumber(gyroValue, 3)
brick.showString("turn-:", 5)
brick.showNumber(turn, 6)
brick.showString("RofB-:", 7)
brick.showNumber(RofB, 8)
brick.showString("Power-:", 9)
brick.showNumber(power, 10)
}
// set break after stop
motors.largeBC.setBrake(true)
// stop
motors.largeBC.stop()
}
/**
* Gyro left turn with only power 30 and 10
* @param targetAngle Angle of turning left, eg: 90
*/
//% block
//% group="Gyro"
export function gyroLeft(targetAngle: number): void {
sensors.gyro2.reset()
let power = 30
let gyroAngle = 0
if (targetAngle > 50) {
targetAngle = targetAngle - 3
} else {
targetAngle = targetAngle
}
let keepLooping = true
while (keepLooping) {
gyroAngle = sensors.gyro2.angle()
if (targetAngle <= Math.abs(gyroAngle)) {
keepLooping = false
}
if (targetAngle - Math.abs(gyroAngle) <= 30) {
power = 10
} else {
power = 30
}
motors.largeBC.steer(-200, power)
brick.showValue("targetAngle = ", targetAngle, 1)
brick.showValue("gyroAngle = ", gyroAngle, 5)
}
brick.showString("end now get out trash", 8)
motors.largeBC.setBrake(true)
motors.largeBC.stop()
}
/**
* Gyro Right turn with only power 30 and 10
* @param targetAngle Angle of turning right, eg: 90
*/
//% block
//% group="Gyro"
export function gyroRight(targetAngle: number): void {
sensors.gyro2.reset()
let power = 30
let gyroAngle = 0
if (targetAngle > 50) {
targetAngle = targetAngle - 3
} else {
targetAngle = targetAngle
}
let keepLooping = true
while (keepLooping) {
gyroAngle = sensors.gyro2.angle()
if (targetAngle <= Math.abs(gyroAngle)) {
keepLooping = false
}
if (targetAngle - Math.abs(gyroAngle) <= 30) {
power = 10
} else {
power = 30
}
motors.largeBC.steer(200, power)
brick.showValue("targetAngle = ", targetAngle, 1)
brick.showValue("gyroAngle = ", gyroAngle, 5)
}
brick.showString("end now get out trash", 8)
motors.largeBC.setBrake(true)
motors.largeBC.stop()
}
}
|
abea9ce79aa01cd3aa368e6504da887c59efdc18 | TypeScript | tridungle/adonis5-cache | /src/TaggableCacheManager.ts | 2.640625 | 3 | import {
CacheManagerContract,
TaggableCacheManagerContract,
TaggableStorageContract,
TagPayloadContract,
} from '@ioc:Adonis/Addons/Adonis5-Cache'
import dayjs from 'dayjs'
import { flatten } from 'ramda'
import { isTaggableStorage, isTagPayloadContract } from './TypeGuards'
export default class TaggableCacheManager implements TaggableCacheManagerContract {
protected storage: TaggableStorageContract
constructor(protected cacheManager: CacheManagerContract, protected _tags: string[]) {
if (isTaggableStorage(cacheManager.storage)) {
this.storage = cacheManager.storage
}
}
public get tags(): string[] {
return this._tags
}
public set tags(value: string[]) {
this._tags = value
}
public async flush(): Promise<void> {
const tagsPayload: string[][] = await Promise.all(
this._tags.map((tag) => this.storage.readTag(this.buildTagKey(tag)))
)
const keyForRemove = flatten(tagsPayload).reduce((acc: string[], tagContent: string) => {
const obj = JSON.parse(tagContent) as TagPayloadContract
if (isTagPayloadContract(obj) && dayjs().isBefore(dayjs(obj.expirationTime))) {
acc.push(...obj.keys)
}
return acc
}, [])
await Promise.all(keyForRemove.map((key) => this.cacheManager.forget(key)))
await Promise.all(this._tags.map((tag) => this.storage.removeTag(this.buildTagKey(tag))))
}
public async put<T = any>(key: string, value: T, ttl?: number): Promise<void> {
await this.saveTaggedKeys([key], ttl)
return this.cacheManager.put(key, value, ttl)
}
public async putMany<T = any>(cacheDictionary: { [p: string]: T }, ttl?: number): Promise<void> {
await this.saveTaggedKeys(Object.keys(cacheDictionary), ttl)
return this.cacheManager.putMany(cacheDictionary, ttl)
}
protected async saveTaggedKeys(keys: string[], ttl: number = this.cacheManager.recordTTL) {
const tagPayload = JSON.stringify({
expirationTime: dayjs().add(ttl, 'ms').toISOString(),
keys,
})
await Promise.all(
this._tags.map((tag) => this.storage.addTag(this.buildTagKey(tag), tagPayload))
)
}
protected buildTagKey(tag: string): string {
return `tag_${tag}`
}
}
|
2a884b034dd122e95deff81699a413393f641a70 | TypeScript | pitchforkviking/WordPlay | /src/pages/duel/duel.ts | 2.828125 | 3 | import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { TimerObservable } from 'rxjs/observable/TimerObservable';
import { HomePage } from '../home/home';
import { Player } from '../../models/player';
@Component({
templateUrl: 'duel.html'
})
export class DuelPage {
public dictionary: string;
public alphabet: any = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
public readyPlayerOne: boolean = true;
public readyPlayerTwo: boolean = false;
public gameOn: boolean = false;
public gameOver: boolean = false;
public playerOne: any[] = [];
public playerTwo: any[] = [];
public players: Player[] = [];
public player: Player;
public enemy: Player;
public timer: any;
public subscriber: any;
public count: number = 20;
public pass: number = 0;
public mode: number = 2;
public turn: number = 2;
public isValid: boolean = false;
public isPlaced: boolean = false;
public isWaiting: boolean = false;
public winner: string;
constructor(
public navCtrl: NavController,
public alertCtrl: AlertController,
public http: Http) {
// Load dictionary
this.http.get('assets/files/dictionary.txt').subscribe(
data => {
this.dictionary = data.text()
},
err => {
alert("Couldn't load the dictionary :(")
}
);
}
// Getting names from players
fpush(letter: any) {
if (this.readyPlayerOne === true) {
if (this.playerOne.length < 5) {
this.playerOne.push(letter);
}
}
else {
if (this.playerTwo.length < 5) {
this.playerTwo.push(letter);
}
}
}
// Name corrections for players
fflush(letter: any) {
if (this.readyPlayerOne === true) {
this.playerOne.splice(this.playerOne.indexOf(letter), 1);
}
else {
this.playerTwo.splice(this.playerTwo.indexOf(letter), 1);
}
}
// Player 1 ready
freadyplayerone() {
this.readyPlayerOne = false;
let player = new Player();
player.name = this.playerOne.join('');
this.players.push(player);
this.readyPlayerTwo = true;
}
// Player 2 ready
freadyplayertwo() {
let player = new Player();
player.name = this.playerTwo.join('');
this.players.push(player);
this.gameOn = true;
this.player = player;
this.fbegin();
}
// Countdown timer for 20 seconds
ftimer() {
this.timer = TimerObservable.create(1000, 1000);
this.subscriber = this.timer.subscribe(t => {
--this.count;
if (this.count === 0) {
this.fpass();
}
});
}
// Shuffles cards
fshuffle(array: any, length: number) {
var first = new Array(length),
count = first.length,
second = new Array(count);
if (length > count) {
throw new RangeError("Something Went Wrong!");
}
while (length--) {
var x = Math.floor(Math.random() * count);
first[length] = array[x in second ? second[x] : x];
second[x] = --count;
}
return { first: first, second: second };
}
// Begin game
fbegin() {
// Shuffle cards
let first = this.alphabet;
first = first.sort(() => .5 - Math.random());
// Split cards for 2 players
this.players[0].deck = first.slice(0, 13);
this.players[1].deck = first.slice(13, 26);
// Start with Player 1
this.player = this.players[0];
this.enemy = this.players[1];
this.ftimer();
}
// Borrow cards from other players
fborrow(letter: any) {
if (this.player.board.length < this.turn) {
this.player.board.push(letter);
this.isPlaced = true;
this.player.borrow.splice(this.player.borrow.indexOf(letter), 1);
--this.player.score;
}
}
// Push cards to player board
fboard(letter: any) {
this.player.deck.push(letter);
this.isPlaced = true;
this.player.board.splice(this.player.board.indexOf(letter), 1);
}
// Pop cards from board, back to deck
fdeck(letter: any) {
if (this.player.board.length < this.turn) {
this.player.board.push(letter);
this.isPlaced = true;
this.player.deck.splice(this.player.deck.indexOf(letter), 1);
}
}
// Checks the word against dictionary
fcheck() {
let word = this.player.board.join('').toLowerCase();
this.isPlaced = false;
if (word !== '') {
var result = this.dictionary.match(new RegExp("\\b" + word + "\\b", 'g'));
if (result !== null) {
this.isValid = true;
this.isPlaced = true;
this.player.score += word.length;
this.dictionary = this.dictionary.replace(new RegExp("\\b" + word + "\\b", 'g'), '');
this.fpass();
}
else {
this.isValid = false;
this.player.score -= 1;
}
}
}
// Passes turn to the other player
fpass() {
this.count = 60;
var index = this.pass % this.mode;
this.players[index] = this.player;
this.enemy = this.player;
++this.pass;
index = this.pass % this.mode;
if (index === 0) {
++this.turn;
}
if (this.turn === 10) {
this.gameOver = true;
this.winner = this.players[0].score > this.players[1].score ? this.players[0].name : this.players[1].name;
this.subscriber.unsubscribe();
}
else {
this.isWaiting = true;
this.isValid = false;
this.isPlaced = false;
// Combined boards of other players
this.player = this.players[index];
this.player.borrow = this.enemy.board;
}
}
fhome() {
this.navCtrl.push(HomePage);
}
fwait(){
this.count = 20;
this.isWaiting = false;
}
}
|
c9fd52d23b8cd8b2d9bfa8b1ae49dd6445aa4031 | TypeScript | gaoljie/use-swiper | /src/utils/move.ts | 2.78125 | 3 | export default function move<T extends HTMLElement>(options: {
slidesPerView: number;
slideWidth: number;
container: T;
animate?: boolean;
speed: number;
deltaX: number;
leftStart: number;
rightStart: number;
curIndex: number;
loop: boolean;
}): void {
const {
slidesPerView,
slideWidth,
container,
loop,
animate = true,
speed,
leftStart,
deltaX,
rightStart,
curIndex
} = options;
if (!container) return;
let startTime: number;
const childrenNum = container.querySelectorAll(".swiper-slide").length;
function moveAnimation(timestamp: number) {
if (!startTime) startTime = timestamp;
// elapsed: [0, 1], if it is not animated, elapsed always equals to 1
const elapsed = animate ? Math.min((timestamp - startTime) / speed, 1) : 1;
// transformX value
let transform = leftStart + elapsed * deltaX;
while (transform <= -childrenNum * slideWidth && loop)
transform += childrenNum * slideWidth;
while (transform > 0 && loop) transform -= childrenNum * slideWidth;
const transformStrLeft = `translateX(${transform}px)`;
// use it when we have multiple slide in one view with last slide and first slide in the same view
let transformRight =
(rightStart + elapsed * deltaX) % (childrenNum * slideWidth);
while (transformRight < 0) transformRight += childrenNum * slideWidth;
const transformStrRight = `translateX(${transformRight}px)`;
for (let i = 0; i < childrenNum; i += 1) {
const child = container.children[i] as HTMLElement;
if (loop) {
// when you swipe from left to right
if (deltaX > 0) {
if (i >= curIndex + slidesPerView - childrenNum) {
child.style.transform = transformStrLeft;
} else {
child.style.transform = transformStrRight;
}
} else {
if (i >= curIndex) {
child.style.transform = transformStrLeft;
} else {
child.style.transform = transformStrRight;
}
}
} else {
// if there is no loop, transform value = transformStrLeft
child.style.transform = transformStrLeft;
}
}
if (elapsed < 1) {
window.requestAnimationFrame(moveAnimation);
}
}
window.requestAnimationFrame(moveAnimation);
}
|
ab5d32be648dfb92c852406aec457c10a2e713f0 | TypeScript | FranciscoJavierMartin/ponyracer | /tests/unit/composables/RaceService.spec.ts | 2.671875 | 3 | import axios, { AxiosResponse } from 'axios';
import { useRaceService } from '@/composables/RaceService';
import { RaceModel } from '@/models/RaceModel';
describe('useRaceService', () => {
test('should list races', async () => {
const response = { data: [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }] } as AxiosResponse<Array<RaceModel>>;
jest.spyOn(axios, 'get').mockResolvedValue(response);
const raceService = useRaceService();
const races = await raceService.list();
// It should get the pending races from the API
expect(axios.get).toHaveBeenCalledWith('https://ponyracer.ninja-squad.com/api/races', { params: { status: 'PENDING' } });
// It should return three races for the `list()` function
expect(races).toHaveLength(3);
});
test('should get a race', async () => {
const response = { data: { name: 'Paris' } } as AxiosResponse<RaceModel>;
jest.spyOn(axios, 'get').mockResolvedValue(response);
const raceId = 1;
const raceService = useRaceService();
const raceModel = await raceService.get(raceId);
// It should get the race from the API
expect(axios.get).toHaveBeenCalledWith('https://ponyracer.ninja-squad.com/api/races/1');
// It should return the race for the `get()` function
expect(raceModel).toBe(response.data);
});
test('should bet on a race', async () => {
const response = { data: { name: 'Paris' } } as AxiosResponse<RaceModel>;
jest.spyOn(axios, 'post').mockResolvedValue(response);
const raceId = 1;
const ponyId = 2;
const raceService = useRaceService();
const raceModel = await raceService.bet(raceId, ponyId);
// It should post the bet
expect(axios.post).toHaveBeenCalledWith('https://ponyracer.ninja-squad.com/api/races/1/bets', { ponyId });
// It should return the race for the `bet()` function
expect(raceModel).toBe(response.data);
});
test('should cancel a bet on a race', async () => {
jest.spyOn(axios, 'delete').mockResolvedValue({} as AxiosResponse);
const raceId = 1;
const raceService = useRaceService();
await raceService.cancelBet(raceId);
// It should delete the bet
expect(axios.delete).toHaveBeenCalledWith('https://ponyracer.ninja-squad.com/api/races/1/bets');
});
});
|
0c78b35f63b7d3eb654c64080afd12068d256c57 | TypeScript | veronika-donets/recipe-book-client | /src/modules/recipes/components/Form/constants.ts | 2.921875 | 3 | import * as Yup from 'yup';
import { RecipeFormValues } from '../../types';
const FILE_SIZE_MAX = 512000; // 500 kB
const FILE_SIZE_MIN = 5120; // 5 kB
const SUPPORTED_FORMATS = ['image/jpg', 'image/jpeg', 'image/gif', 'image/png'];
export const formInitialValues: RecipeFormValues = {
name: '',
photo: null,
categoryId: '',
directions: '',
};
export const addValidationSchema = Yup.object({
name: Yup.string()
.trim()
.required('Please enter a category name')
.max(50, 'Name should be no more than 50 characters'),
photo: Yup.mixed()
.required('Please add a photo')
.test(
'fileType',
'Unsupported File Format. Please, upload .jpg, .gif or .png',
(value) => value && SUPPORTED_FORMATS.includes(value.type),
)
.test('fileSize', 'File size should be no more than 500 kB', (value) => value && value.size <= FILE_SIZE_MAX)
.test('fileSize', 'File size should be no less than 5 kB', (value) => value && value.size >= FILE_SIZE_MIN),
categoryId: Yup.string().required('Please select a category'),
directions: Yup.string()
.trim()
.required('Please enter directions')
.max(5000, 'Directions should be no more than 5000 characters'),
});
export const updateValidationSchema = Yup.object({
name: Yup.string()
.trim()
.required('Please enter a category name')
.max(50, 'Name should be no more than 50 characters'),
categoryId: Yup.string().required('Please select a category'),
directions: Yup.string()
.trim()
.required('Please enter directions')
.max(5000, 'Directions should be no more than 5000 characters'),
});
|
41d4aa5bc3285f7fe47e74218bdeeb26bee2ebd8 | TypeScript | kawamataryo/ts-jest-boilerplate | /tests/index.test.ts | 2.625 | 3 | import { sum } from "../src/index";
describe("index", () => {
describe("sum", () => {
test.each([
[1, 2, 3],
[100, 20, 120],
[10, 35, 45],
[-1, 2, 1],
[0, 10, 10],
])("calculate %i + %i", (a, b, expected) => {
expect(sum(a, b)).toBe(expected);
});
});
});
|
0a4d74aba72d935c60d888e679613df8a6497570 | TypeScript | pnxtech/pnxge | /src/State.ts | 3.234375 | 3 | import {Utils} from './Utils';
/**
* @name State
* @description State management
*/
export class State {
private _state: {};
/**
* @name constructor
* @description state initializer
*/
constructor() {
this._state = {};
}
/**
* @name state
* @description state getter
* @return {object}
*/
public get state(): any {
return this._state;
}
/**
* @name state
* @description state setter
* @param {any} data - object to be merged with state
*/
public set state(data: any) {
this._state = data;
}
/**
* @name setState
* @description merges object entries in to application state
* @param {object} data - object to be merged with state
* @return {object} new application state
*/
public setState(data: any): any {
let newState = Utils.mergeObjects(this._state, data);
this._state = newState;
return this._state;
}
}
|
205eb66cc2222dce5eadb4a2bfae797fb66fe536 | TypeScript | mahertim/UltimateCourses-NGRXStore | /src/products/util/map-to-entities.helper.ts | 3.390625 | 3 | interface IdentifiableType {
id?: number;
}
export function mapToEntities<T extends IdentifiableType>(
items: T[],
entities: { [id: number]: T },
): { [id: number]: T } {
return items.reduce(
(theEntities: { [id: number]: T }, t: T) => {
return {
...theEntities,
[t.id as number]: t,
};
},
{ ...entities },
);
}
|
a3df0403a2307d8586371026d6ddc499464657c7 | TypeScript | VirtoCommerce/vc-procurement-portal-theme | /ng-app/src/app/modules/alerts/models.ts | 2.671875 | 3 | export class Alert {
constructor(public type: AlertType, public msg: string, public keepAfterRouteChange = false) {
}
}
export enum AlertType {
Success = 'success',
Error = 'danger',
Info = 'info',
Warning = 'warning'
}
export class IAlertOptions {
keepAfterRouteChange?: boolean;
dismissTimeout?: number;
}
|
626ed9d8ce011a1b771038fc974ebfd62827cecd | TypeScript | karolkozak/FlavorSome-web | /src/app/shared/utils/array-utils.ts | 3.03125 | 3 | export function inArray<T>(needle: T, haystack: T[]): boolean {
return haystack && haystack.indexOf(needle) >= 0;
}
|
4bc1b994b2e20cb85a9d02da03207715843a9757 | TypeScript | marygans/office-ui-fabric-react | /packages/migration/src/cli/cli.ts | 3.046875 | 3 | interface IParsedCommand {
writeResults: boolean;
help: boolean;
version: string;
}
const defaultParsedCommand = {
writeResults: false,
help: false,
version: '',
};
export class CliParser {
public parse(args: string[]): IParsedCommand {
if (args.length === 0 || args[0] === '-h' || args[0] === '--help') {
return { ...defaultParsedCommand, help: true };
}
if (args.some(a => a === '-w' || a === '--write')) {
return {
...defaultParsedCommand,
writeResults: true,
version: args[1],
};
}
return {
...defaultParsedCommand,
version: args[0],
};
}
}
export function displayHelp() {
const output = [
'Usage:',
' migration [-w] VERSION',
'',
'Options:',
' -h --help Display this message',
' -w --write Write changes directly to files',
];
console.error(output.join('\n'));
}
|
b25e532b2ac2e3b64c75d96e669dd796161c2afc | TypeScript | andoniabedul/ts-blog | /src/routes/post.routes.ts | 2.59375 | 3 | import { Request, Response, Router } from 'express';
import PostModel from '../models/post.models';
class Post {
public router: Router;
constructor(){
this.router = Router();
this.setRoutes();
}
async getList(req: Request, res: Response){
const posts = await PostModel.getPosts();
res.send({ success: true, data: { posts } });
}
get(req: Request, res: Response){
const id: string = req.params.id;
res.send(`[POSTS][get] SUCCESS -> ${id}`);
}
create(req: Request, res: Response){
res.send(`[POSTS][create] SUCCESS`);
}
update(req: Request, res: Response){
const id: string = req.params.id;
res.send(`[POSTS][update] SUCCESS -> ${id}`);
}
delete(req: Request, res: Response){
res.send(`[POSTS][delete] SUCCESS`);
}
setRoutes(){
this.router.get(`/`, this.getList);
this.router.post(`/create/`, this.create);
this.router.get(`/:id/`, this.get);
this.router.delete(`/:id/delete/`, this.delete);
this.router.put(`/:id/update`, this.update);
}
}
const PostRouter = new Post();
export default PostRouter.router; |
d9871f7d52d12ac0d676235369e94bb04ed2223e | TypeScript | antopas84/ecommerce | /app/components/cart/cart.component.ts | 2.53125 | 3 | import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {Product} from '../../entities/product.entities';
import {Item} from '../../entities/item.entities';
import {ProductService} from '../../services/product.service'
@Component({
moduleId: module.id,
templateUrl:'index.component.html'
})
export class CartComponent implements OnInit{
private items : Item[] = [];
private total: number = 0;
constructor(
private productService : ProductService,
private activateRoute: ActivatedRoute
){}
ngOnInit(){
this.activateRoute.params.subscribe(params => {
var id = params['id'];
if(id){
var item : Item = {
product: this.productService.find(id),
quantity: 1
};
if(localStorage.getItem('cart') == null){
let cart : any = [];
cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(cart));
}else{
let cart : any = JSON.parse(localStorage.getItem('cart'));
let index : number = -1;
for(var i = 0; i < cart.length; i++){
let item: Item = JSON.parse(cart[i]);
if(item.product.id == id){
index = i;
break;
}
}
if(index == -1){
cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(cart));
}else{
let item: Item = JSON.parse(cart[index]);
item.quantity += 1;
cart[index] = JSON.stringify(item);
localStorage.setItem('cart', JSON.stringify(cart));
}
}
this.loadCart();
}else{
this.loadCart();
}
});
}
loadCart(): void{
this.total = 0;
this.items = [];
let cart = JSON.parse(localStorage.getItem('cart'));
for(var i = 0; i < cart.length; i++){
let item = JSON.parse(cart[i]);
this.items.push({
product: item.product,
quantity: item.quantity
});
this.total += item.product.price * item.quantity;
}
}
remove(id: string): void{
let cart : any = JSON.parse(localStorage.getItem('cart'));
let index : number = -1;
for(var i = 0; i < cart.length; i++){
let item: Item = JSON.parse(cart[i]);
if(item.product.id == id){
cart.splice(i, 1);
break;
}
}
localStorage.setItem('cart', JSON.stringify(cart));
this.loadCart();
}
removeAll(): void{
let cart : any = [];
localStorage.setItem('cart', JSON.stringify(cart));
this.loadCart();
}
saveAll(): void{
alert('STORE ON DB... PUT IN QUEUE');
//call service which calls a REST Service on Jboss. This Service saves the data
//on DB and put a message in the queue for sending an email. [USE TRANSACTION]
}
} |
6a5c07d388fc9142956bb7da78e7c3f90c74ef7a | TypeScript | ggpo1/a100 | /src/MapCore/Services/ObjectService.ts | 2.515625 | 3 | import sort from 'fast-sort';
import bs from 'js-binary-search';
import MapSourceLayer from "../Models/MapSourceLayer";
import StillageItem from "../Models/ArrayItems/StillageItem";
import ObjectItem from "../Models/ArrayItems/ObjectItem";
export default class ObjectService {
public getObjectSourceItem(selectedLayer: MapSourceLayer, coords: { x: number, y: number }, photo: any) {
let _id = 0; let _key = '';
sort(selectedLayer.objects!).asc(e => e.id);
if (selectedLayer.objects!.length !== 0) {
_id = selectedLayer.objects![selectedLayer.objects!.length - 1].id;
}
_id++;
_key = selectedLayer.key + '_object_' + _id.toString();
return {
id: _id,
key: _key,
x: coords.x,
y: coords.y,
photo: photo,
}
}
public searchByID(shapesList: Array<ObjectItem>, id: number) {
return bs.search_in_associative(shapesList, 'id', id);
}
} |
6cee622e53e3b58ef6d86fdcb0c5189494974a76 | TypeScript | NadimAppsCode/SlidingItems | /src/directives/reveal-sliding.directive.ts | 2.953125 | 3 | import {AfterViewInit, ContentChild, ContentChildren, Directive, ElementRef, QueryList, Renderer2} from '@angular/core';
import {IonItemOptions, IonItemSliding} from '@ionic/angular';
/**
* The data type used to specify the swipe direction of the emulation.
*/
enum SwipeDirection {
toLeft = 0,
toRight
}
/**
* The directive 'appRevealSliding' is used for emulating swipe event on the Ionic component
* 'ion-item-sliding' by clicking on an HTML element with the attribute 'appRevealSlidingButton'.
* The element with the attribute 'appRevealSlidingButton' should be placed inside the 'ion-item' element.
*/
/**
* Common decorator for specifying the directive. Selector for directive is 'appRevealSliding'.
*/
@Directive({
selector: '[appRevealSliding]',
})
/**
* Declaration of the class RevealSlidingDirective that implements the Angular interface AfterViewInit.
* The interface points that the class will use ngAfterViewInit method.
*/
export class RevealSlidingDirective implements AfterViewInit {
/**
* ContentChild decorator is used for getting an object of the 'ion-item-sliding' component.
* The object has class IonItemSliding. The object will be used only for checking
* that the directive 'appRevealSliding' is placed to the correct component.
* More about ContentChild decorator:
* https://angular.io/api/core/ContentChild
*/
@ContentChild(IonItemSliding) itemSliding: IonItemSliding;
/**
* ContentChildren decorator is used for getting a list of objects of the nested components 'ion-item-options'.
* The object of component 'ion-item-options' has class IonItemOptions. The list of the
* components will be used for getting Ionic options buttons location within 'ion-item-sliding' component
* e.g. 'start' or 'end'. The information about the options buttons location will be used for specifying the direction
* of the swipe emulation.
* More about ContentChildren decorator:
* https://angular.io/api/core/ContentChildren
*/
@ContentChildren(IonItemOptions) itemOptionsList !: QueryList<IonItemOptions>;
/**
* Defines the HTML element to which will be added a click listener to start swipe emulation.
*/
revealButton: Element;
/**
* Defines direction of the swipe emulation.
*/
swipeDirection: SwipeDirection;
/**
* Constructor of the class of the directive.
* @param el Reference to the element which directive is placed on.
* @param renderer Object that is used for safe manipulations with HTML DOM elements.
*/
constructor(private el: ElementRef,
private renderer: Renderer2) {
}
/**
* Implements AfterViewInit interface.
* More about the method here:
* https://angular.io/api/core/AfterViewInit
*/
ngAfterViewInit() {
this.selfCheck();
this.init();
}
/**
* Checks that this directive is placed to the 'ion-item-sliding' component with the nested 'ion-item-options' component.
*/
private selfCheck() {
if (!this.itemSliding) {
throw new Error('RevealSlidingDirective: Missing ion-item-sliding node');
}
if (this.itemOptionsList.length > 1) {
console.warn('RevealSlidingDirective: Processing only a one ion-item-options element');
}
if (this.itemOptionsList.length === 0) {
console.warn('RevealSlidingDirective: Missing ion-item-options element');
}
}
/**
* Initiates the directive.
*/
private init() {
/**
* Defining the swipe direction by the attribute 'side' of the nested 'ion-item-options' component.
*/
const itemOption = this.itemOptionsList.first;
if (itemOption) {
this.swipeDirection = itemOption.side === 'start' ?
SwipeDirection.toRight : SwipeDirection.toLeft;
} else {
this.swipeDirection = SwipeDirection.toLeft;
}
/**
* Defining the HTML element with the 'appRevealSlidingButton' attribute.
*/
this.revealButton = this.el.nativeElement.querySelector('ion-item *[appRevealSlidingButton]');
if (!this.revealButton) {
console.warn('RevealSlidingDirective: appRevealSlidingButton attribute is missed');
return;
}
/**
* Adding a click listener for the element.
*/
this.renderer.listen(this.revealButton, 'click', () => {
this.sendEvents(0);
});
}
/**
* Sends emulation events to the 'ion-item-sliding' component. This function is called recursively.
* @param index Current recursion iteration number.
*/
private sendEvents(index: number) {
/**
* Defines the number of maximum recursion iteration (the deep of the recursion call stack).
*/
const maxIterations = 5;
/**
* Stops the recursion iteration if it has been reached the maximum recursion number. Exit call stack.
*/
if (index === maxIterations) {
return;
}
/**
* Sends the events with a little time out, as it happens when a human it does.
*/
setTimeout(() => {
this.sendEventsDispatcher(index, maxIterations);
this.sendEvents(++index);
}, 10);
}
/**
* The method is the core of the swipe emulation.
* @param index Current recursion iteration number.
* @param maxIterations Number of maximum recursion iteration (the deep of the recursion call stack).
*/
private sendEventsDispatcher(index: number, maxIterations: number) {
/**
* Defines mouse events for the emulation.
*/
const mouseEvents = [
'mousedown',
'mouseup',
'mousemove'
];
/**
* Defines touch events for the emulation.
*/
const touchEvents = [
'touchstart',
'touchend',
'touchmove'
];
/**
* Defines the dispatcher and events that will be used for the swipe emulation.
* If the browser supports touch events then 'sendTouchEvent' method and 'touchEvents' will be used,
* else 'sendMouseEvent' and 'mouseEvents' will be used instead.
*/
const eventTypes = this.supportTouchEvent() ? touchEvents : mouseEvents;
const dispatcher = this.supportTouchEvent() ? this.sendTouchEvent : this.sendMouseEvent;
/**
* Gets the HTML Element of the 'ion-item-sliding' component.
*/
const el = this.el.nativeElement;
/**
* Gets sizes and coordinates of the HTML Element of the 'ion-item-sliding' component.
*/
const rect = el.getBoundingClientRect();
/**
* Defines the delta (offset) of the horizontal coordinate of the event for increment or decrement depends on the swipe direction.
* When swipe direction will be 'to the right' the horizontal coordinate will increase by this value with each iteration.
* When direction will be 'to the left' the horizontal coordinate will decrease by this value with each iteration.
*/
const xStep = 50;
/**
* Defines small vertical offset of the event. It is necessary in order to the event will point to the element body,
* not to its top border. This value will not be changed during the iterations.
*/
const yOffset = 10;
/**
* Defines vertical coordinate for the event.
*/
const y = rect.top + yOffset;
/**
* Defines horizontal coordinate for the event depending on swipe direction.
*/
let x = rect.right - index * xStep;
if (this.swipeDirection === SwipeDirection.toRight) {
x = rect.left + index * xStep;
}
/**
* For the correct emulation process, it is necessary to emulate native touch events, like a human does.
* The emulation process has three stages: start, move, end.
* For the first iteration it is passed the start event for the touch event it will be 'touchstart', 'mousedown'
* for the mouse event.
*/
if (index === 0) {
dispatcher(el, eventTypes[0], x, y);
/**
* For the last iteration it is passed the end event for the touch event it will be 'touchend', 'mouseup'
* for the mouse event.
*/
} else if (index === maxIterations - 1) {
dispatcher(el, eventTypes[1], x, y);
/**
* For the intermediate iteration it is passed the move event for the touch event it will be 'touchmove', 'mousemove'
* for the mouse event.
*/
} else {
dispatcher(el, eventTypes[2], x, y);
}
}
/**
* Used for sending touch events to the HTML element.
* @param element The HTMLElement that will accept the event.
* @param eventType The event type of the mouse event e.g. 'touchstart'.
* @param x The horizontal coordinate for the event.
* @param y The vertical coordinate for the event.
*/
private sendTouchEvent(element: HTMLElement, eventType: string, x: number, y: number) {
try {
/**
* Creating a single contact point on the touch-sensitive device (surface).
*/
const touch = new Touch({
identifier: Date.now(),
target: element,
clientX: x,
clientY: y,
radiusX: 2.5,
radiusY: 2.5,
rotationAngle: 10,
force: 0.5,
});
/**
* Creating the touch event with the list of the touches points.
*/
const touchList: Touch[] = [touch];
const touchEvent = new TouchEvent(eventType, {
cancelable: true,
bubbles: true,
touches: touchList,
targetTouches: [],
changedTouches: touchList,
shiftKey: true,
});
/**
* Sending the event to the target HTML element.
*/
element.dispatchEvent(touchEvent);
} catch (e) {
console.error(e);
}
}
/**
* The method is used for sending only mouse events to the HTML element.
* @param element The HTMLElement that will accept the event.
* @param eventType The event type of the mouse event e.g. 'mousemove'.
* @param x The horizontal coordinate for the event.
* @param y The vertical coordinate for the event.
*/
private sendMouseEvent(element: HTMLElement, eventType: string, x: number, y: number) {
/**
* Creating the event through the global Window variable 'document'.
*/
const event = document.createEvent('MouseEvent');
event.initMouseEvent(
eventType,
true /* bubble */,
true /* cancelable */,
window, 0,
0,
0,
x,
y, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left click*/,
null,
);
/**
* Sending the event to the target HTML element.
*/
element.dispatchEvent(event);
}
/**
* Checking the ability of the browser to use touch events.
*/
private supportTouchEvent() {
return typeof Touch !== 'undefined' &&
typeof TouchEvent !== 'undefined';
}
}
|
156383008e43331b96ac6294b61ad287bc9095b9 | TypeScript | mattdsteele/stencil | /src/compiler/entries/entry-modules.ts | 2.546875 | 3 | import * as d from '../../declarations';
import { catchError, sortBy } from '@utils';
import { DEFAULT_STYLE_MODE } from '@utils';
import { generateComponentBundles } from './component-bundles';
export function generateEntryModules(config: d.Config, buildCtx: d.BuildCtx) {
// figure out how modules and components connect
try {
const bundles = generateComponentBundles(
config,
buildCtx,
);
buildCtx.entryModules = bundles.map(createEntryModule);
} catch (e) {
catchError(buildCtx.diagnostics, e);
}
buildCtx.debug(`generateEntryModules, ${buildCtx.entryModules.length} entryModules`);
}
export function createEntryModule(cmps: d.ComponentCompilerMeta[]): d.EntryModule {
// generate a unique entry key based on the components within this entry module
cmps = sortBy(cmps, c => c.tagName);
const entryKey = cmps
.map(c => c.tagName)
.join('.') + '.entry';
return {
cmps,
entryKey,
modeNames: getEntryModes(cmps),
};
}
export function getEntryModes(cmps: d.ComponentCompilerMeta[]) {
const styleModeNames: string[] = [];
cmps.forEach(cmp => {
const cmpStyleModes = getComponentStyleModes(cmp);
cmpStyleModes.forEach(modeName => {
if (!styleModeNames.includes(modeName)) {
styleModeNames.push(modeName);
}
});
});
if (styleModeNames.length === 0) {
styleModeNames.push(DEFAULT_STYLE_MODE);
} else if (styleModeNames.length > 1) {
const index = (styleModeNames.indexOf(DEFAULT_STYLE_MODE));
if (index > -1) {
styleModeNames.splice(index, 1);
}
}
return styleModeNames.sort();
}
export function getEntryEncapsulations(moduleFiles: d.Module[]) {
const encapsulations: d.Encapsulation[] = [];
moduleFiles.forEach(m => {
m.cmps.forEach(cmp => {
const encapsulation = cmp.encapsulation || 'none';
if (!encapsulations.includes(encapsulation)) {
encapsulations.push(encapsulation);
}
});
});
if (encapsulations.length === 0) {
encapsulations.push('none');
} else if (encapsulations.includes('shadow') && !encapsulations.includes('scoped')) {
encapsulations.push('scoped');
}
return encapsulations.sort();
}
export function getComponentStyleModes(cmpMeta: d.ComponentCompilerMeta) {
if (cmpMeta && cmpMeta.styles) {
return cmpMeta.styles.map(style => style.modeName);
}
return [];
}
|
81e86d9923774370dc40dac2b8917d8b1890afbf | TypeScript | martindavid/flask-nextjs-user-management-example | /client/services/users.ts | 2.828125 | 3 | import { Api } from "./api";
import { ApiResponse } from "apisauce";
import { GeneralApiProblem, getGeneralApiProblem } from "./api/api-problem";
import { User } from "./types";
export type GetUsersResult = { kind: "ok"; users: User[] } | GeneralApiProblem;
export type GetUserResult = { kind: "ok"; user: User } | GeneralApiProblem;
export class UserApi extends Api {
convertUser(raw: any): User {
return {
id: raw.id,
firstName: raw.firstName,
lastName: raw.lastName,
email: raw.email,
admin: raw.admin,
active: raw.active,
};
}
async getUserById(token: string, id: number): Promise<GetUserResult> {
this.apisauce.setHeader("Authorization", `Bearer ${token}`);
const response: ApiResponse<any> = await this.apisauce.get(
`/api/v1/users/${id}`
);
if (!response.ok) {
const problem = getGeneralApiProblem(response);
if (problem) return problem;
}
try {
const user: User = response.data.data;
return { kind: "ok", user: user };
} catch {
return { kind: "bad-data" };
}
}
async getUsers(token: string): Promise<GetUsersResult> {
this.apisauce.setHeader("Authorization", `Bearer ${token}`);
const response: ApiResponse<any> = await this.apisauce.get("/api/v1/users");
if (!response.ok) {
const problem = getGeneralApiProblem(response);
if (problem) return problem;
}
try {
const rawUsers = response.data;
const resultUsers: User[] = rawUsers.map(this.convertUser);
return { kind: "ok", users: resultUsers };
} catch {
return { kind: "bad-data" };
}
}
}
|
f9683b94bb0029c98b5561a8948cbc06156df2e5 | TypeScript | mnnnaleudes/enqueue | /src/services/Sender.ts | 2.515625 | 3 | import amqp = require('amqplib/callback_api');
class Sender {
async create(queue: string, msg: string) {
amqp.connect('amqp://localhost', function (error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function (error1, channel) {
if (error1) {
throw error1;
}
channel.assertQueue(queue, {
durable: false
});
channel.sendToQueue(queue, Buffer.from(msg));
console.log(" [x] Sent %s", msg);
});
});
}
}
export default Sender; |
f8aa4497da2d53338c94931ca1be1ebbe445f8cd | TypeScript | CSCI-40500-77100-Spring-2021/project-10__backend | /cdk/src/util/resource.ts | 2.515625 | 3 | import AppStage from '../constant/app_stage';
export const resourceName = (
resource: string,
stage: AppStage,
) : string => {
const base = `${resource}-${stage}`;
if (stage !== AppStage.Prod) return `${base}-${process.env.USER}`;
return base;
};
resourceName('abc', AppStage.Prod);
|
273c8c4c67d8973198bd3630268a58284f26a06f | TypeScript | tuzmusic/game-of-life | /src/app.ts | 3.453125 | 3 | console.log('Hello world!!! blah');
export function testFunc() {
return 42;
}
export interface Cell {
isAlive: boolean;
row: number;
column: number;
}
export type Board = Cell[][]
export class Game {
board: Board;
constructor(board: Board) {
this.board = board;
}
findCellAt(_row: number, _column: number): Cell {
for (let rowIndex = 0; rowIndex < this.board.length; rowIndex++) {
const thisRow = this.board[rowIndex];
for (let colIndex = 0; colIndex < thisRow.length; colIndex++) {
if (rowIndex === _row
&& colIndex === _column) {
return thisRow[colIndex];
}
}
}
}
neighborsFor(cell: Cell): Cell[] {
const { row, column } = cell;
const coords: [number, number][] = [
[row, column - 1],
[row, column + 1],
[row - 1, column],
[row + 1, column],
[row - 1, column - 1],
[row - 1, column + 1],
[row + 1, column - 1],
[row + 1, column + 1],
];
const cells: Cell[] = [];
coords.forEach(([r, c]) => {
// for each neighbor coord, IF THE COORD IS VALID, add that cell
if (r >= 0 // not in first row
&& c >= 0 // not in first column
&& r < this.board[0].length // not in last row
&& c > this.board.length) // not in last column
{
cells.push(this.findCellAt(r, c));
}
});
return cells;
}
printCurrentBoard() {
console.log('*******************');
for (let rowIndex = 0; rowIndex < this.board.length; rowIndex++) {
const thisRow = this.board[rowIndex];
console.log(thisRow.map(row => row.isAlive ? 'T' : 'F'));
}
console.log('*******************');
}
playTurn() {
const tempBoard: Board = [...this.board];
// iterate each cell in the board
for (let rowIndex = 0; rowIndex < this.board.length; rowIndex++) {
const thisRow = this.board[rowIndex];
for (let colIndex = 0; colIndex < thisRow.length; colIndex++) {
const thisCell = thisRow[colIndex];
this.processCell(thisCell); // MUTATES THE CELL
}
}
this.board = [...tempBoard];
}
processCell(cell: Cell) {
const neighbors = this.neighborsFor(cell);
const liveNeighborsCt = neighbors.filter((c: Cell) => c.isAlive).length;
if (liveNeighborsCt < 2)
this.kill(cell);
else if (cell.isAlive && (liveNeighborsCt === 2 || liveNeighborsCt === 3))
this.regenerate(cell);
else if (liveNeighborsCt > 3)
this.kill(cell);
else if (!cell.isAlive && liveNeighborsCt === 3)
this.regenerate(cell);
}
kill(cell: Cell) {
cell.isAlive = false;
}
regenerate(cell: Cell) {
cell.isAlive = true;
}
}
function playTheDamnGameAlready(board: Board, turnCount = 1) {
const game = new Game(board);
for (let turn = 0; turn < turnCount; turn++) {
game.playTurn();
}
} |
397b7751282b609b2d08899bf7b3bbf0757bd71d | TypeScript | kittylabsbsc/nft-hooks | /src/hooks/useXNFT.ts | 2.625 | 3 | import { useContext } from 'react';
import useSWR from 'swr';
import { NFTFetchContext } from '../context/NFTFetchContext';
import { addAuctionInformation } from '../fetcher/TransformFetchResults';
import { getCurrenciesInUse } from '../fetcher/ExtractResultData';
import { XNFTDataType, XNFTMediaDataType } from '../fetcher/AuctionInfoTypes';
export type useXNFTType = {
currencyLoaded: boolean;
error?: string;
data?: XNFTDataType;
};
type OptionsType = {
refreshInterval?: number;
initialData?: any;
loadCurrencyInfo?: boolean;
};
/**
* Fetches on-chain NFT data and pricing for the given xNFT id
*
* @param id id of xNFT to fetch blockchain information for
* @param options SWR flags and an option to load currency info
* @returns useNFTType hook results include loading, error, and chainNFT data.
*/
export function useXNFT(id?: string, options: OptionsType = {}): useXNFTType {
const fetcher = useContext(NFTFetchContext);
const { loadCurrencyInfo = false, refreshInterval, initialData } = options || {};
const nftData = useSWR<XNFTMediaDataType>(
id ? ['loadXNFTDataUntransformed', id] : null,
(_, id) => fetcher.loadXNFTDataUntransformed(id),
{ refreshInterval, dedupingInterval: 0 }
);
const currencyData = useSWR(
nftData.data && nftData.data.pricing && loadCurrencyInfo
? [
'loadCurrencies',
...getCurrenciesInUse(addAuctionInformation(nftData.data.pricing)),
]
: null,
(_, ...currencies) => fetcher.loadCurrencies(currencies),
{
refreshInterval,
dedupingInterval: 0,
}
);
let data;
if (nftData.data !== undefined) {
data = {
...nftData.data,
pricing: addAuctionInformation(nftData.data.pricing, currencyData.data),
};
} else {
data = initialData;
}
return {
currencyLoaded: !!currencyData.data,
error: nftData.error,
data,
};
}
|
5f9a859511621d40db13683a0d84da609a65d5ed | TypeScript | Tecnology73/idt-discord-bot | /Util/Random.ts | 2.625 | 3 | const random = require('random');
const seedrandom = require('seedrandom');
export const getRandomInstance = () => {
random.use(seedrandom(
require('crypto').randomBytes(10).toString('hex')
));
return random;
};
export const getRandomInt = (min: number, max: number) => {
return getRandomInstance().int(min, max);
};
export const getRandomPercentage = (min: number, max: number) => {
return getRandomInstance().float(min, max) / 100;
};
|
43401563481566dd32f6eaaefe20f80e8c1649cc | TypeScript | christophgysin/aws-sdk-js-v3 | /packages/signature-v4/src/credentialDerivation.spec.ts | 2.59375 | 3 | import { Sha256 } from "@aws-crypto/sha256-js";
import { Credentials } from "@aws-sdk/types";
import { toHex } from "@aws-sdk/util-hex-encoding";
import { clearCredentialCache, createScope, getSigningKey } from "./credentialDerivation";
describe("createScope", () => {
it("should create a scoped identifier for the credentials used", () => {
expect(createScope("date", "region", "service")).toBe("date/region/service/aws4_request");
});
});
describe("getSigningKey", () => {
beforeEach(clearCredentialCache);
const credentials: Credentials = {
accessKeyId: "foo",
secretAccessKey: "bar",
};
const shortDate = "19700101";
const region = "us-foo-1";
const service = "bar";
it(
"should return a buffer containing a signing key derived from the" +
" provided credentials, date, region, and service",
() => {
return expect(getSigningKey(Sha256, credentials, shortDate, region, service).then(toHex)).resolves.toBe(
"b7c34d23320b5cd909500c889eac033a33c93f5a4bf67f71988a58f299e62e0a"
);
}
);
it("should trap errors encountered while hashing", () => {
return expect(
getSigningKey(
jest.fn(() => {
throw new Error("PANIC");
}),
credentials,
shortDate,
region,
service
)
).rejects.toMatchObject(new Error("PANIC"));
});
describe("caching", () => {
it("should return the same signing key when called with the same date, region, service, and credentials", async () => {
const mockSha256Constructor = jest.fn().mockImplementation((args) => {
return new Sha256(args);
});
const key1 = await getSigningKey(mockSha256Constructor, credentials, shortDate, region, service);
const key2 = await getSigningKey(mockSha256Constructor, credentials, shortDate, region, service);
expect(key1).toBe(key2);
expect(mockSha256Constructor).toHaveBeenCalledTimes(6);
});
it("should cache a maximum of 50 entries", async () => {
const keys: Array<Uint8Array> = new Array(50);
// fill the cache
for (let i = 0; i < 50; i++) {
keys[i] = await getSigningKey(Sha256, credentials, shortDate, `us-foo-${i.toString(10)}`, service);
}
// evict the oldest member from the cache
await getSigningKey(Sha256, credentials, shortDate, `us-foo-50`, service);
// the second oldest member should still be in cache
await expect(getSigningKey(Sha256, credentials, shortDate, `us-foo-1`, service)).resolves.toStrictEqual(keys[1]);
// the oldest member should not be in the cache
await expect(getSigningKey(Sha256, credentials, shortDate, `us-foo-0`, service)).resolves.not.toBe(keys[0]);
});
});
});
|
1c2efa8dec6fbf18cfe2e823945fde170cbc061b | TypeScript | jasemabeed114/ddd-demo | /src/modules/orders/useCases/bargain/getBargainList/getBargainListUseCase.ts | 2.515625 | 3 | import { Either, Result, right, left } from '../../../../../shared/core/Result'
import { AppError } from '../../../../../shared/core/AppError'
import { UseCase } from '../../../../../shared/core/UseCase'
import { Bargain } from '../../../domain/bargain'
import { IBargainRepo } from '../../../repos/bargainRepo'
import { GetBargainListDto } from './getBargainListDto'
type Response = Either<AppError.UnexpectedError, Result<Bargain[]>>
export class GetBargainListUseCase implements UseCase<GetBargainListDto, Promise<Response>> {
private bargainRepo: IBargainRepo
constructor(
bargainRepo: IBargainRepo) {
this.bargainRepo = bargainRepo
}
public async execute(request: GetBargainListDto): Promise<Response> {
try {
const { } = request
const bargainList = await this.bargainRepo.filter()
return right(Result.ok<Bargain[]>(bargainList))
} catch (err) {
return left(new AppError.UnexpectedError(err))
}
}
}
|
932883851fbd1432b9df2ea7de6c5bd83633424b | TypeScript | JamesPinson/nodebucket | /src/app/shared/models/employee.interface.ts | 3.09375 | 3 | /**
* Title: employee.interface.ts
* Author: Richard Krasso
* Modified By: James Pinson
* Date: 28 August 2021
* Description: This is our employee interface which is created for reusability.
*/
//This is our import statements.
import { Item } from './item.interface';
//This exports our employee interface which consist of three variables the empId variable which has a string value, the todo variable which has an item array and the done variable which has an item array.
export interface Employee {
empId: string;
todo: Item[];
done: Item[];
}
|
37fef1ec5e0d8cfe4a9318e012b5f456419bc265 | TypeScript | nodefluent/kafka-streams | /src/lib/StorageMerger.ts | 3.28125 | 3 | /**
* static class, that helps with merging
* KStorages (e.g. joining two KTables)
*/
export class StorageMerger {
/**
* merges the content of multiple storages
* if keys have the same name, the later storage
* will overwrite the value
* @param storages
* @returns {Promise.<{State}>}
*/
static mergeIntoState(storages) {
return Promise.all(storages
.map(storage => storage.getState()))
.then(states => {
const newState = {};
states.forEach(state => {
Object.keys(state).forEach(key => {
newState[key] = state[key];
});
});
return newState;
});
}
}
|
ee0babcb41e2f439781e13d087ff1f7833d22cb4 | TypeScript | mddr/taiga-ui | /projects/demo/src/modules/components/input-phone/examples/3/index.ts | 2.515625 | 3 | import {default as avatar} from '!!file-loader!../../../../../assets/images/avatar.jpg';
import {Component} from '@angular/core';
import {TUI_DEFAULT_MATCHER, tuiPure} from '@taiga-ui/cdk';
import {combineLatest, merge, Observable, of, Subject} from 'rxjs';
import {map, share, startWith, switchMap, tap} from 'rxjs/operators';
import {changeDetection} from '../../../../../change-detection-strategy';
import {encapsulation} from '../../../../../view-encapsulation';
class User {
constructor(
readonly firstName: string,
readonly lastName: string,
readonly phone: string,
readonly avatarUrl: string | null = null,
readonly disabled: boolean = false,
) {}
toString(): string {
return `${this.firstName} ${this.lastName}`;
}
}
const DATA: ReadonlyArray<User> = [
new User(
'Roman',
'Sedov',
'+75678901234',
'http://marsibarsi.me/images/1x1small.jpg',
),
new User('Alex', 'Inkin', '+75678901234', avatar),
];
@Component({
selector: 'tui-input-phone-example-3',
templateUrl: './index.html',
styleUrls: ['./index.less'],
changeDetection,
encapsulation,
})
export class TuiInputPhoneExample3 {
private readonly search$ = new Subject<string>();
private readonly selected$ = new Subject<User>();
value = '';
readonly user$ = merge(
this.selected$,
this.search$.pipe(
switchMap(value =>
this.request(value).pipe(
map(response =>
this.isFullMatch(response, value) ? response[0] : null,
),
),
),
),
).pipe(
tap(user => {
if (user) {
this.value = user.phone;
}
}),
);
readonly items$ = this.search$.pipe(
startWith(''),
switchMap(value =>
this.request(value).pipe(
map(response => (this.isFullMatch(response, value) ? [] : response)),
),
),
);
readonly placeholder$ = combineLatest(this.user$, this.search$).pipe(
map(([user, search]) => user || this.getPlaceholder(search)),
startWith('Phone number or name'),
);
onSearch(search: string) {
this.search$.next(search);
}
onClick(user: User) {
this.selected$.next(user);
}
private getPlaceholder(search: string): string {
if (!search) {
return 'Phone number or name';
}
if (search.startsWith('+')) {
return 'Phone number';
}
return 'Name';
}
private isFullMatch(response: ReadonlyArray<User>, value: string): boolean {
return (
response.length === 1 &&
(String(response[0]) === value || response[0].phone === value)
);
}
// Request imitation
@tuiPure
private request(query: string): Observable<ReadonlyArray<User>> {
return of(
DATA.filter(
item =>
TUI_DEFAULT_MATCHER(item, query) ||
TUI_DEFAULT_MATCHER(item.phone, query),
),
).pipe(share());
}
}
|
9119fd9089481ae1f035d7f3690a6ba08c26a715 | TypeScript | hzjjg/canvas_snow | /src/snow.ts | 2.96875 | 3 | import SnowPic from './snow_pic';
/**
* 下雪效果
*/
export default class Snow {
private container: HTMLElement;
private options: SnowOptions;
private defaultOption: SnowOptions = {
container: null,
stopWhenVisibilityChange: true,
quantity: 5,
speed: 5,
};
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private status: 'start' | 'stop' = 'stop';
private flakeImg = new Image();
private blurFlakeImg = new Image();
private circleFlakeImg = new Image();
private flakes: SnowFlake[] = [];
/** 雪的数量 1-10 */
private quantity: number;
/** 雪的速度 1-10 */
private speed: number;
private genFlakeTimmer: any;
private gcTimmer: any;
private renderAnimationFrame: number;
constructor(option: SnowOptions) {
this.options = Object.assign(this.defaultOption, option);
this.container = option.container;
this.quantity = Math.max(1, Math.min(this.options.quantity, 100));
this.speed = Math.max(1, Math.min(this.options.speed, 10));
this.init();
}
public start() {
if (this.status === 'start') return;
this.status = 'start';
this.loadImages([SnowPic.flakeImage, SnowPic.blurFlakeImage, SnowPic.circleFlakeImage]).then(() => {
this.startGenFlake();
this.startRender();
this.startGc();
});
}
public stop() {
if (this.status === 'stop') return;
clearInterval(this.genFlakeTimmer);
clearInterval(this.gcTimmer);
cancelAnimationFrame(this.renderAnimationFrame);
this.status = 'stop';
}
/**
* 改变速度
* @param speed 1-10
*/
public changeSpeed(speed: number){
if (isNaN(speed)) return;
this.speed = Math.max(1, Math.min(speed, 10));
}
/**
* 改变雪数量
* @param quantity 1-100
*/
public changeQuantity(quantity: number){
if (isNaN(quantity)) return;
this.stop();
this.quantity = Math.max(1, Math.min(quantity, 100));
this.start();
}
private genFlake(): SnowFlake {
const size = this.randomRange(10, 40);
return {
type: <any> this.randomArray(['flower', 'flower', 'circle', 'blurCircle']),
x: this.randomRange(0, this.canvas.width),
y: -size,
velocity: {
x: this.randomRange(-2, 2) * (this.speed / 50),
y: this.randomRange(5, 15) * (this.speed / 50),
},
size,
alpha: this.randomRange(8, 10) / 10,
};
}
private randomArray<T>(items: T[]) {
const index = Math.floor(Math.random() * items.length + 1) - 1;
return items[index];
}
private randomRange(min: number, max: number) {
const Range = max - min;
const Rand = Math.random();
const num = min + Math.round(Rand * Range);
return num;
}
private startGenFlake() {
this.genFlakeTimmer = setInterval(() => {
this.flakes.push(this.genFlake());
}, 2000 / this.quantity);
}
private startRender() {
this.renderAnimationFrame = requestAnimationFrame(() => {
this.clearCtx();
this.updateFlakes();
this.renderFlakes();
this.startRender();
});
}
private clearCtx() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
/**
* 定时删除超出屏幕的雪花
*/
private startGc() {
this.gcTimmer = setInterval(() => {
this.flakes.forEach((flake) => {
if (flake.x >= this.canvas.width || flake.y >= this.canvas.height) {
this.flakes.splice(this.flakes.indexOf(flake), 1);
}
});
}, 3000);
}
private updateFlakes() {
this.flakes.forEach((flake) => {
// 更新位置
flake.x += flake.velocity.x;
flake.y += flake.velocity.y;
});
}
private renderFlakes() {
this.flakes.forEach(flake => {
this.renderFlake(flake);
});
}
private renderFlake(flake: SnowFlake) {
switch (flake.type) {
case 'flower':
this.renderFlowerFlake(flake);
break;
case 'circle':
this.renderCircleFlake(flake);
break;
case 'blurCircle':
this.renderBlurCircleFlake(flake);
break;
}
}
private renderFlowerFlake(flake: SnowFlake) {
this.ctx.globalAlpha = flake.alpha || 1;
this.ctx.drawImage(this.flakeImg, flake.x, flake.y, flake.size, flake.size);
}
private renderCircleFlake(flake: SnowFlake) {
this.ctx.globalAlpha = flake.alpha || 1;
const size = flake.size / 3;
this.ctx.drawImage(this.circleFlakeImg, flake.x, flake.y, size, size);
}
private renderBlurCircleFlake(flake: SnowFlake) {
this.ctx.globalAlpha = flake.alpha || 1;
this.ctx.drawImage(this.blurFlakeImg, flake.x, flake.y, flake.size, flake.size);
}
private init() {
this.flakeImg.src = SnowPic.flakeImage;
this.blurFlakeImg.src = SnowPic.blurFlakeImage;
this.circleFlakeImg.src = SnowPic.circleFlakeImage;
this.options.stopWhenVisibilityChange && this.bindPageVisibilitychangeStopSnow();
this.initCanvas();
}
private bindPageVisibilitychangeStopSnow() {
document.addEventListener('visibilitychange', () => {
if (this.status === 'start') {
this.stop();
} else {
this.start();
}
});
}
private initCanvas() {
const canvas = this.canvas = document.createElement('canvas');
this.ctx = canvas.getContext('2d');
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
canvas.style.pointerEvents = 'none';
canvas.style.zIndex = '999';
canvas.className = this.options.canvasClass;
canvas.setAttribute('width', this.container.offsetWidth.toString());
canvas.setAttribute('height', this.container.offsetHeight.toString());
if (this.container.style.position !== 'absolute') {
this.container.style.position = 'relative';
}
this.container.appendChild(canvas);
}
private loadImages(images: string[]) {
let count = 0;
return new Promise(resolve => {
(images || []).forEach(src => {
const image = new Image();
image.src = src;
image.onload = () => {
count++;
if (count === images.length) resolve();
};
image.onerror = () => {
count++;
if (count === images.length) resolve();
};
});
});
}
}
interface SnowOptions {
container: HTMLElement;
canvasClass?: string;
stopWhenVisibilityChange?: boolean;
/** 雪数量 1-10 */
quantity?: number;
/** 雪速度 1-10 */
speed?: number;
}
interface SnowFlake {
type: 'flower' | 'circle' | 'blurCircle';
x: number;
y: number;
size: number;
alpha?: number;
velocity: {
x: number,
y: number,
};
} |
3d47519ec87d3f7c9729de90b78525fb443ff110 | TypeScript | bal3000/React-Redux | /src/redux/actions/author.actions.ts | 2.53125 | 3 | import { ThunkAction } from "redux-thunk";
import { Action } from "redux";
import * as authorApi from "../../api/authorApi";
import { AuthorActionTypes, LOAD_AUTHOR_SUCCESS } from "../types/author.types";
import { AppState } from "../configure.store";
import { Author } from "../../models/author.interface";
import { beginApiCall, apiCallError } from "./apiStatus.actions";
export function loadAuthorSuccess(authors: Author[]): AuthorActionTypes {
return { type: LOAD_AUTHOR_SUCCESS, authors };
}
export function loadAuthors(): ThunkAction<void, AppState, null, Action> {
return async (dispatch) => {
try {
dispatch(beginApiCall());
const authors = await getAuthors();
dispatch(loadAuthorSuccess(authors));
} catch (error) {
dispatch(apiCallError(error));
throw error;
}
};
}
async function getAuthors() {
return authorApi.getAuthors();
}
|
8043b9c78a3083e2a8a3823dfdbfc8bdd00d7eb3 | TypeScript | geostyler/geostyler-data | /index.d.ts | 2.96875 | 3 | // Type definitions for GeoStyler Data Models
// Project: https://github.com/geostyler/geostyler
// Definitions by: Christian Mayer <https://github.com/chrismayer>
// Definitions:
// TypeScript Version: 3.3.3
import { FeatureCollection, Geometry } from 'geojson';
import { JSONSchema4TypeName } from 'json-schema';
/**
* Type represents a single property of an object according to JSON schema.
* Like:
*
* {
* "type": "Number",
* "minimum": 0
* }
*
*
* @class SchemaProperty
*/
export type SchemaProperty = {
/**
* The data type of the described property / attribute
* @type {JSONSchema4TypeName}
*/
type: JSONSchema4TypeName;
/**
* The minimum value of the described property / attribute.
* Only applies for type='number'
* @type {number}
*/
minimum?: number;
/**
* The data type of the described property / attribute#
* Only applies for type='number'
* @type {number}
*/
maximum?: number;
};
/**
* Type represents the schema of imported geo-data, to have information about available
* properties and data ranges.
* Comparable to a DescribeFeatureType response for an OGC WFS.
* This is modelled as JSON schema:
*
* {
* "title": "Person",
* "type": "object",
* "properties": {
* "firstName": {
* "type": "string"
* },
* "lastName": {
* "type": "string"
* },
* "age": {
* "description": "Age in years",
* "type": "integer",
* "minimum": 0
* }
* }
* }
*
* @type DataSchema
*/
export type DataSchema = {
/**
* Optional title for the described entity
*
* @type {string}
*/
title?: string;
/**
* Type definition for the described entity
*
* @type {string}
*/
type: string;
/**
* Properties object describing the attributes of the described entity
*
* @type {[name: string]: SchemaProperty; }}
*/
properties: { [name: string]: SchemaProperty };
};
/**
* Type represents the schema of imported raster-data,
* to have information about a single band.
*
* @type BandSchema
*/
export type BandSchema = {
[key: string]: any;
minValue?: number;
maxValue?: number;
};
/**
* BaseData object
*/
export interface BaseData {
/**
* Schema of imported geo-data describing the properties / attributes
*
* @type {DataSchema}
*/
schema: DataSchema;
}
/**
* Internal data object for imported vector geo data.
* Aggregates a data schema and some example data (FeatureCollection).
*/
export interface VectorData extends BaseData {
/**
* Example features of imported geo-data
*/
exampleFeatures: FeatureCollection<Geometry>;
}
/**
* Internal data object for imported raster data.
* Aggregates a data schema and some example data.
*/
export interface RasterData extends BaseData {
/**
* Info on imported raster bands.
* Each band should be a unique key with arbitrary subproperties.
* These can include projections, statistics and other information.
*/
rasterBandInfo: {[bandname: string]: BandSchema };
}
/**
* Internal data object for imported geo data.
*/
export type Data = RasterData | VectorData;
/**
* Interface, which has to be implemented by all GeoStyler parser classes.
*/
export interface DataParser {
/**
* The name of the Parser instance
*/
title: string;
/**
* Optional projection of the input data,
* e.g. 'EPSG:4326'
*
* @type {string}
*/
sourceProjection?: string;
/**
* Optional projection of the output data,
* e.g. 'EPSG:3857'
*
* @type {string}
*/
targetProjection?: string;
/**
* Parses the inputData and transforms it to the GeoStyler data model
*
* @param inputData
*/
readData(inputData: any): Promise<Data>;
}
|
9dc2bd27a7a614a053c6fb0371d51df8eeea1a98 | TypeScript | ViktorSlavov/schematic-component-example | /src/component/schema.ts | 2.609375 | 3 | export interface ComponentOptions {
// The type of the component (currently, only card)
type: string;
// The name of the component.
name: string;
}
|
45d4900e9906b553bec30ec65cac8275c981a040 | TypeScript | CCBaxter84/EU-Books | /src/models/userVerification.ts | 2.84375 | 3 | // Import dependencies
import { Schema, Document, model, Model } from "mongoose";
import User, { IUser } from "./user";
// Define and export interface derived from mongoose Document
export interface IUserVerification extends Document {
user: Schema.Types.ObjectId,
token: string
}
// Define schema
const userVerificationSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
token: {
type: String,
required: true
},
});
userVerificationSchema.post("save", function(doc: IUserVerification, next) {
setTimeout(function() {
doc.remove();
}, 1000 * 60 * 60 * 12);
next();
});
userVerificationSchema.post("remove", function(doc: IUserVerification, next) {
User.findByIdAndDelete(doc.user)
.then(() => next());
});
// Define and export Book model based on schema
const UserVerification: Model<IUserVerification> = model("UserVerification", userVerificationSchema);
export default UserVerification; |
f61522b7c9f47ce2c4c3a8df58756b34a85085b3 | TypeScript | 2006NodeDev/project-0-ABlanton3 | /hitchhiker_reimbursement/src/routers/user-router.ts | 2.765625 | 3 | import express, {Request, Response, NextFunction} from 'express'
//import {User} from '../models/User'
import {authenticationMiddleware} from '../middleware/authentication-middleware'
import {authorizationMiddleware} from '../middleware/authorization-middleware'
import { getAllUsers, getUserById, updateUser } from '../daos/user-dao'
import { User } from '../models/User'
export const userRouter = express.Router()
userRouter.use(authenticationMiddleware)
//get all users
userRouter.get('/', authorizationMiddleware(['admin', 'finance-manager']), async (req:Request,res:Response,next:NextFunction)=>{
try{
let allUsers = await getAllUsers()
res.json(allUsers)
} catch(e){
next(e)
}
})
//find user by ID number
userRouter.get('/:id', authorizationMiddleware(['admin', 'finance-manager'/*still not sure how to let user search themselves*/]), async (req:Request, res:Response, next: NextFunction)=>{//figure out how to do basically userId===userId
let {id} = req.params
if(isNaN(+id)){
res.status(400).send('ID must be a number')
} else {
try {
let user = await getUserById(+id)
res.json(user)
} catch (e) {
next(e)
}
}
})
//update user
userRouter.patch('/',authorizationMiddleware(['admin']), async (req: Request, res:Response, next:NextFunction)=>{
let { userId,
username,
password,
firstName,
lastName,
email,
role } = req.body
if(!userId) {
res.status(400).send('Must have a User ID and at least one other field')
}
else if(isNaN(+userId)) {
res.status(400).send('ID must be a number')
}
else {
let updatedUser:User = {
userId,
username,
password,
firstName,
lastName,
email,
role
}
updatedUser.username = username || undefined
updatedUser.password = password || undefined
updatedUser.firstName = firstName || undefined
updatedUser.lastName = lastName || undefined
updatedUser.email = email || undefined
updatedUser.role = role || undefined
try {
let result = await updateUser(updatedUser)
res.json(result)
} catch (e) {
next(e)
}
}
})
|
d21b0054c7eb36cb0b30c0b1571a76548b8205b9 | TypeScript | andrewphoy/DgtWebSerial | /src/serial.ts | 2.703125 | 3 | import MessageReader from "./messageReader";
import * as Utils from "./utils";
import { SerialNumberMessage } from "./messages/serialNumberMessage";
export default class {
private _port!: SerialPort;
private reader: MessageReader;
private _attemptingConnect: boolean = false;
private _cbConnectSuccess?: (serial: number) => void;
public onMessage?: (msg: DgtMessage) => void;
//#region Properties
private _portName: string = "";
public get portName(): string {
return this._portName;
}
private _connected: boolean = false;
public get connected(): boolean {
return this._connected;
}
//#endregion
constructor() {
this.reader = new MessageReader();
this.reader.onMessage = this.handleSerialMessage;
}
private async attemptOpen(): Promise<boolean> {
return new Promise<void>(async (resolve, reject) => {
}).then(() => {
return true;
}).catch(() => {
return false;
});
}
public async open(): Promise<boolean> {
this._attemptingConnect = true;
this.dispose();
try {
let port = await navigator.serial.requestPort();
if (port != null) {
await port.open({ baudRate: 9600 });
setTimeout(() => this.readLoop(port), 1);
this.sendCommand(DgtCommands.SendSerialNumber);
//TODO verify that it's a dgt board by getting the serial number
this._port = port;
this._connected = true;
return true;
}
return false;
} catch {
// if the user does not select a port, requestPort throws an exception
return false;
} finally {
this._attemptingConnect = false;
}
}
private dispose() {
this._connected = false;
}
private async readLoop(port: SerialPort) {
while (port.readable) {
let sr = port.readable.getReader();
try {
while (true) {
let { value, done } = await sr.read();
if (done) {
break;
}
this.reader.processStreamData(value);
}
} catch (err) {
} finally {
sr.releaseLock();
}
}
}
public async sendCommand(messageId: number) {
if (!this._connected) {
return;
}
let buffer = new Uint8Array(1);
buffer[0] = messageId;
let writer = this._port.writable.getWriter();
await writer.write(buffer);
writer.releaseLock();
}
public async sendClockText(display: string) {
if (!this._connected) {
return;
}
let buffer = new Uint8Array(14);
buffer[0] = 0x2b;
buffer[1] = 0x0c; // 12, discounts the header
buffer[2] = 0x03; // start
buffer[3] = 0x0c; // clock command code (0x0c = ascii)
buffer[12] = 8; // beep because we can
buffer[13] = 0x00; // end
for (let i = 4; i < 12; i++) {
let code = (display.length >= i - 3) ? display.charCodeAt(i - 4) : 32;
buffer[i] = code;
}
let writer = this._port.writable.getWriter();
await writer.write(buffer);
writer.releaseLock();
}
public async sendClockSetAndRun() {
let buffer = new Uint8Array(14);
buffer[0] = 0x2b;
buffer[1] = 0x0a; // 10, discounts the header
buffer[2] = 0x03; // start
buffer[3] = 0x0a; // clock command code (0x0a = set and run)
buffer[4] = 1; // left hours
buffer[5] = 29; // left minutes
buffer[6] = 59; // left seconds
buffer[7] = 0; // right hours
buffer[8] = 6; // right minutes
buffer[9] = 3; // right seconds
buffer[10] = 3; // left running
buffer[11] = 0x00; // end
let writer = this._port.writable.getWriter();
await writer.write(buffer);
writer.releaseLock();
}
public async testClock() {
let string = 'Andrew';
let buffer = new Uint8Array(14);
buffer[0] = 0x2b;
buffer[1] = 0x0c; // 12, discounts the header
buffer[2] = 0x03; // start
buffer[3] = 0x0c; // clock command code (0x0c = ascii)
buffer[4] = 'A'.charCodeAt(0);
buffer[5] = 'B'.charCodeAt(0);
buffer[6] = 'C'.charCodeAt(0);
buffer[7] = 'D'.charCodeAt(0);
buffer[8] = 'E'.charCodeAt(0);
buffer[9] = 'F'.charCodeAt(0);
buffer[10] = 'G'.charCodeAt(0);
buffer[11] = 'H'.charCodeAt(0);
buffer[12] = 8;
buffer[13] = 0x00; // end
let writer = this._port.writable.getWriter();
await writer.write(buffer);
writer.releaseLock();
}
private handleSerialMessage = (msg: DgtMessage) => {
if (this.onMessage) {
this.onMessage(msg);
}
}
}
|
db1faa9fdda048a22afb26104896a8c83fcb5d79 | TypeScript | BuzzDyne/Hacktiv8-assignment06 | /src/app/utils/Utils.ts | 2.75 | 3 | export function isEmailExistErrorMsg(text: string): boolean {
let regex = new RegExp("User with the email '[^']*' already exists")
return regex.test(text)
} |
95f329a39de9320187f78583f6717b9c9b442d3d | TypeScript | ovidubya/weatherapp-vue | /src/api/apixu.ts | 2.921875 | 3 |
export default class apixu {
/**
* Fields
*/
private API_KEY: string;
private CURRENT_JSON: string;
private FORECAST_JSON: string;
private LOCATION: string;
constructor(key) {
this.API_KEY = key;
this.CURRENT_JSON = `${location.protocol}//api.apixu.com/v1/current.json?key=${this.API_KEY}`;
this.FORECAST_JSON = `${location.protocol}//api.apixu.com/v1/forecast.json?key=${this.API_KEY}`;
// this.requestLocation();
}
/**
* geolocation has to be part of the navigator object
*/
isGeo():boolean {
/**
* For testing return true
*/
// return true;
return !!navigator.geolocation;
}
/**
* Returns a promise of true or false depending if the user accepted location
*/
requestLocation():Promise<boolean> {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((pos) => {
this.LOCATION = `${pos.coords.latitude},${pos.coords.longitude}`
resolve(true)
}, () => {
resolve(false);
});
});
}
/**
* Async function that returns the raw data from a GET request on the apixu current.json API
* @param locationQuery search field for query the apixu API
* @param callback function that takes a data callback
*/
async getCurrentWeather(locationQuery:string, callback: (data: any) => void) {
let url;
let userLocactionAcceptance = this.isGeo() ? await this.requestLocation() : false;
if (userLocactionAcceptance && locationQuery == null) {
url = this.CURRENT_JSON + `&q=${this.LOCATION}`;
} else if (locationQuery != null) {
url = this.CURRENT_JSON + `&q=${locationQuery}`;
} else {
url = this.CURRENT_JSON + `&q=60661`;
}
return new Promise((resolve, reject) => {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
try {
var jsonData = JSON.parse(this.responseText);
if(jsonData.error) {
reject(jsonData.error.message)
}else {
if(callback) {
callback(jsonData);
}
resolve(jsonData);
}
}catch(e) {
console.log('Unable to parse json');
reject('error');
}
}
});
xhr.open("GET", url);
xhr.send(data);
});
}
/**
* Async function that returns the raw data from a GET request on the apixu forecast.json API
* @param locationQuery search field for query the apixu API
* @param callback function that takes a data callback
*/
async getCurrentForecast(locationQuery:string, callback: (data: any) => void):Promise<object> {
let url;
let userLocactionAcceptance = this.isGeo() ? await this.requestLocation() : false;
if (userLocactionAcceptance && locationQuery == null) {
url = this.FORECAST_JSON + `&q=${this.LOCATION}&days=10`;
} else if (locationQuery != null) {
url = this.FORECAST_JSON + `&q=${locationQuery}&days=10`;
} else {
url = this.FORECAST_JSON + `&q=60661&days=10`;
}
return new Promise((resolve, reject) => {
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
try {
var jsonData = JSON.parse(this.responseText);
if(jsonData.error) {
reject(jsonData.error.message)
}else {
if(callback) {
callback(jsonData);
}
resolve(jsonData);
}
}catch(e) {
console.log('Unable to parse json');
reject('error');
}
}
});
xhr.open("GET", url);
xhr.send(data);
});
}
} |
940987865774cba11536fc11eae8efd13b141aa9 | TypeScript | LorenzHenk/aoc2019 | /src/days/day01/calc.ts | 3.09375 | 3 | export const calculateFuel = (mass: number) => Math.floor(mass / 3) - 2;
export const calculateFuelWithFuel = (mass: number) => {
let totalFuel = 0;
let currentMass = mass;
while (true) {
const currentFuel = calculateFuel(currentMass);
if (currentFuel <= 0) {
break;
}
totalFuel += currentFuel;
currentMass = currentFuel;
}
return totalFuel;
};
|
276c2c94e3b8f9c0ff682d353faa4a4532f24f9a | TypeScript | techtic-brinda/node-js | /src/shared/validations/IsUserAlreadyExistValidator.ts | 2.859375 | 3 | import {
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { getRepository } from 'typeorm';
import { User } from 'src/modules/entity/user.entity';
/**
* Check if user already registerd validator
*/
@ValidatorConstraint()
export class IsUserAlreadyExist implements ValidatorConstraintInterface {
async validate(email: string, args: ValidationArguments) {
const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { email: email } });
if (user) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
// here you can provide default error message if validation failed
return 'User with provided email already registered.';
}
}
@ValidatorConstraint()
export class IsUserAlreadyPhoneNumber implements ValidatorConstraintInterface {
async validate(phone_number: string, args: ValidationArguments) {
const userRepository = getRepository(User);
const user = await userRepository.findOne({ where: { phone_number: phone_number } });
if (user) {
return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return 'User with provided phone number already registered.';
}
}
|
4559490d4df9526edb4aa4b84d01658d3527239d | TypeScript | zaknafain/kings-duty | /src/app/events/event.service.ts | 2.640625 | 3 | import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { TimeEvent, NewcommerArrivingEvent, PeopleMovedEvent, PeopleGoneEvent } from './time-event';
import { TimeEventAction } from './time-event-action';
import { TileService } from '../map/tiles/tile.service';
import { TimeService } from '../time/time.service';
import { Tile } from '../map/tiles/tile';
@Injectable({
providedIn: 'root'
})
export class EventService {
events: TimeEvent[] = [];
private readonly _currentEvent = new BehaviorSubject<TimeEvent>(undefined);
readonly currentEvent$ = this._currentEvent.asObservable();
constructor(
private tileService: TileService,
private timeService: TimeService
) {
this.timeService.days$.subscribe(day => this.setCurrentEventForDay(day));
}
get currentEvent(): TimeEvent {
return this._currentEvent.getValue();
}
set currentEvent(currentEvent: TimeEvent) {
this._currentEvent.next(currentEvent);
}
createInitialEvents(): void {
const initialEvents = [
new NewcommerArrivingEvent(),
new NewcommerArrivingEvent(),
new NewcommerArrivingEvent(),
new NewcommerArrivingEvent(),
new NewcommerArrivingEvent()
];
this.events = this.sortEvents(initialEvents);
}
resolveEvent(eventAction: TimeEventAction): void {
if (eventAction) {
switch (eventAction.actionType) {
case 'GAIN_PEOPLE':
this.tileService.addPopulation(
eventAction.actionsParams.x,
eventAction.actionsParams.y,
eventAction.actionsParams.people
);
break;
case 'MOVE_PEOPLE':
const tile: Tile = this.tileService.tiles.find(t => (
t.x === eventAction.actionsParams.x &&
t.y === eventAction.actionsParams.y
));
const connectors: Tile[] = this.tileService.getConnecters(tile).sort((a, b) => (a.people || 0) - (b.people || 0));
const chosenTile = connectors[0];
this.tileService.addPopulation(chosenTile.x, chosenTile.y, eventAction.actionsParams.people);
this.tileService.claimTile(chosenTile.x, chosenTile.y, tile.owner);
this.tileService.removePopulation(
eventAction.actionsParams.x,
eventAction.actionsParams.y,
eventAction.actionsParams.people
);
break;
case 'LOOSE_PEOPLE':
this.tileService.removePopulation(
eventAction.actionsParams.x,
eventAction.actionsParams.y,
eventAction.actionsParams.people
);
break;
case 'CONSOLE':
console.log(eventAction);
}
}
if (eventAction && eventAction.createEvent !== undefined) {
this.currentEvent = this.findNewEvent(eventAction, this.timeService.days);
} else {
this.setCurrentEventForDay(this.timeService.days);
}
}
addEvent(event: TimeEvent): void {
const newEvents = this.events;
newEvents.push(event);
this.events = this.sortEvents(newEvents);
}
sortEvents(events: TimeEvent[]): TimeEvent[] {
return events.sort((a, b) => a.day - b.day);
}
private setCurrentEventForDay(day: number): void {
if (this.events[0] !== undefined && this.events[0].day === day) {
this.currentEvent = this.events.shift();
} else {
this.currentEvent = undefined;
}
}
private findNewEvent(eventAction: TimeEventAction, day: number): TimeEvent {
switch (eventAction.createEvent) {
case 'PEOPLE_MOVED':
return new PeopleMovedEvent(day, eventAction.actionsParams.people);
case 'PEOPLE_GONE':
return new PeopleGoneEvent(day, eventAction.actionsParams.people);
}
}
}
|
5f433945af5835ae0b6b70a6c3860af9807ff012 | TypeScript | Tatiana-256/back-end-nestjs | /src/roles/roles.controller.ts | 2.578125 | 3 | import { Body, Controller, Get, Param, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { UsersService } from "../users/users.service";
import { User } from "../users/users.model";
import { CreateUserDto } from "../users/dto/create-user.dto";
import { RolesService } from "./roles.service";
import { Role } from "./roles.model";
import { CreateRoleDto } from "./dto/create-role.dto";
@ApiTags("Roles")
@Controller("roles")
export class RolesController {
constructor(private roleService: RolesService) {
}
@ApiOperation({ summary: "create new role" })
@ApiResponse({ status: 200, type: Role })
@Post()
createRole(@Body() roleDto: CreateRoleDto){
return this.roleService.createRole(roleDto);
}
@ApiOperation({ summary: "Get role bu value" })
@ApiResponse({ status: 200, type: Role })
@Get('/:value')
getRoleByValue(@Param("value") value: string){
return this.roleService.getRoleByValue(value);
}
// @ApiOperation({ summary: "create new user" })
// @ApiResponse({ status: 200, type: User })
// @Post()
// create(@Body() userDto: CreateUserDto) {
// return this.userService.createUser(userDto);
// }
//
// @ApiOperation({ summary: "Get all users" })
// @ApiResponse({ status: 200, type: [User] })
// @Get()
// getAll() {
// return this.userService.getAllUsers();
// }
}
|
0d72d811272f74b6ad582a290e6ae748cc155559 | TypeScript | google/skia-buildbot | /ct/modules/suggest-input-sk/suggest-input-sk.ts | 2.828125 | 3 | /**
* @module modules/suggest-input-sk
* @description A custom element that implements regex and substring match
* suggestions. These are selectable via click or up/down/enter.
*
* @attr {Boolean} accept-custom-value - Whether users can enter values not listed
* in this.options.
*
* @event value-changed - Any time the user selected or inputted value is
* committed. Event is of the form { value: <newValue> }
*/
import { html } from 'lit-html';
import { $$ } from '../../../infra-sk/modules/dom';
import { define } from '../../../elements-sk/modules/define';
import { ElementSk } from '../../../infra-sk/modules/ElementSk';
const DOWN_ARROW = '40';
const UP_ARROW = '38';
const ENTER = '13';
export class SuggestInputSk extends ElementSk {
private _options: string[] = [];
private _suggestions: string[] = [];
private _suggestionSelected: number = -1;
private _label: string = '';
constructor() {
super(SuggestInputSk.template);
this._upgradeProperty('options');
this._upgradeProperty('acceptCustomValue');
this._upgradeProperty('label');
}
// TODO(westont): We should probably use input-sk here.
private static template = (ele: SuggestInputSk) => html`
<div class=suggest-input-container>
<input class=suggest-input autocomplete=off required
@focus=${ele._refresh}
@input=${ele._refresh}
@keyup=${ele._keyup}
@blur=${ele._blur}>
</input>
<label class="suggest-label">${ele.label}</label>
<div class=suggest-underline-container>
<div class=suggest-underline></div>
<div class=suggest-underline-background ></div>
</div>
<div class=suggest-list
?hidden=${!(ele._suggestions && ele._suggestions.length > 0)}
@click=${ele._suggestionClick}>
<ul>
${ele._suggestions.map((s, i) =>
ele._suggestionSelected === i
? SuggestInputSk.selectedOptionTemplate(s)
: SuggestInputSk.optionTemplate(s)
)}
</ul>
</div>
</div>
`;
// tabindex so the fields populate FocusEvent.relatedTarget on blur.
private static optionTemplate = (option: string) => html`
<li tabindex="-1" class="suggestion">${option}</li>
`;
private static selectedOptionTemplate = (option: string) => html`
<li tabindex="-1" class="suggestion selected">${option}</li>
`;
connectedCallback(): void {
super.connectedCallback();
this._render();
}
/**
* @prop {string} value - Content of the input element from typing,
* selection, etc.
*/
get value(): string {
// We back our value with input.value directly, to avoid issues with the
// input value changing without changing our value property, causing
// element re-rendering to be skipped.
return ($$('input', this) as HTMLInputElement).value;
}
set value(v: string) {
($$('input', this) as HTMLInputElement).value = v;
}
/**
* @prop {Array<string>} options - Values for suggestion list.
*/
get options(): string[] {
return this._options;
}
set options(o: string[]) {
this._options = o;
}
/**
* @prop {Boolean} acceptCustomValue - Mirrors the
* 'accept-custom-value' attribute.
*/
get acceptCustomValue(): boolean {
return this.hasAttribute('accept-custom-value');
}
set acceptCustomValue(val: boolean) {
if (val) {
this.setAttribute('accept-custom-value', '');
} else {
this.removeAttribute('accept-custom-value');
}
}
/**
* @prop string label - Label to display to guide user input.
*/
get label(): string {
return this._label;
}
set label(o: string) {
this._label = o;
}
_blur(e: MouseEvent): void {
// Ignore if this blur is preceding _suggestionClick.
const blurredElem = e.relatedTarget as HTMLElement;
if (blurredElem && blurredElem.classList.contains('suggestion')) {
return;
}
this._commit();
}
_commit(): void {
if (this._suggestionSelected > -1) {
this.value = this._suggestions[this._suggestionSelected];
} else if (!this._options.includes(this.value) && !this.acceptCustomValue) {
this.value = '';
}
this._suggestions = [];
this._suggestionSelected = -1;
this._render();
this.dispatchEvent(
new CustomEvent('value-changed', {
bubbles: true,
detail: { value: this.value },
})
);
}
_keyup(e: KeyboardEvent): void {
// Allow the user to scroll through suggestions using arrow keys.
const len = this._suggestions.length;
const key = e.key || e.code;
if ((key === 'ArrowDown' || key === DOWN_ARROW) && len > 0) {
this._suggestionSelected = (this._suggestionSelected + 1) % len;
this._render();
} else if ((key === 'ArrowUp' || key === UP_ARROW) && len > 0) {
this._suggestionSelected = (this._suggestionSelected + len - 1) % len;
this._render();
} else if (key === 'Enter' || key === ENTER) {
// This also commits the current selection (if present) or custom
// value (if allowed).
($$('input', this) as HTMLInputElement).dispatchEvent(
new Event('blur', { bubbles: true, cancelable: true })
);
}
}
_refresh(): void {
const v = this.value;
let re: { test: (str: string) => boolean };
try {
re = new RegExp(v, 'i'); // case-insensitive.
} catch (err) {
// If the user enters an invalid expression, just use substring
// match.
re = {
test: function (str: string) {
return str.indexOf(v) !== -1;
},
};
}
this._suggestions = this._options.filter((s) => re.test(s));
this._suggestionSelected = -1;
this._render();
}
_suggestionClick(e: Event): void {
const item = e.target as HTMLElement;
if (item.tagName !== 'LI') {
return;
}
const index = Array.from(item.parentNode!.children).indexOf(item);
this._suggestionSelected = index;
this._commit();
}
}
define('suggest-input-sk', SuggestInputSk);
|
e3f5d25f0bb03621674f6e677048040bb3926bcd | TypeScript | Jblew/firestore-roles-redux-module | /src/module/actions/EpicActions.ts | 2.71875 | 3 | // tslint:disable class-name
import { ThunkAction } from "../../thunk";
import { ContainingStoreState } from "../ContainingStoreState";
export interface EpicActions {
initialize(): ThunkAction<Promise<EpicActions.InitializeAction>, ContainingStoreState>;
logout(): ThunkAction<Promise<EpicActions.LogoutAction>, ContainingStoreState>;
checkRole(role: string): ThunkAction<Promise<EpicActions.CheckRoleAction>, ContainingStoreState>;
}
export namespace EpicActions {
export const INITIALIZE = "FirestoreRolesAuthReduxModule/PrivateEpicActions/INITIALIZE";
export const LOGOUT = "FirestoreRolesAuthReduxModule/EpicActions/LOGOUT";
export const CHECK_ROLE = "FirestoreRolesAuthReduxModule/EpicActions/CHECK_ROLE";
export interface InitializeAction {
type: typeof INITIALIZE;
}
export interface LogoutAction {
type: typeof LOGOUT;
}
export interface CheckRoleAction {
type: typeof CHECK_ROLE;
role: string;
}
export type Type = InitializeAction | LogoutAction | CheckRoleAction;
}
|
425ccdb484f3cbce323304126ce56dfa09910850 | TypeScript | kseniasalabaeva/weathercast | /src/utils/index.ts | 2.734375 | 3 | export enum City {
None = 'Select city',
Samara = 'Samara',
Togliatty = 'Togliatty',
Saratov = 'Saratov',
Kazan = 'Kazan',
Krasnodar = 'Krasnodar'
}
export const Coordinates = {
[City.None]: { lat: undefined, lon: undefined },
[City.Samara]: { lat: 53.19, lon: 50.10 },
[City.Togliatty]: { lat: 53.50, lon: 49.42 },
[City.Saratov]: { lat: 51.53, lon: 46.03 },
[City.Kazan]: { lat: 55.79, lon: 49.10 },
[City.Krasnodar]: { lat: 45.03, lon: 38.97 }
}
|
3024fdf5816dc82c62cae984b6a9a5d200b866c9 | TypeScript | sorohan/graph-builder | /src/graph/GraphBuilder.ts | 3.15625 | 3 | import { AbstractGraphBuilder } from "./AbstractGraphBuilder";
import { Graph } from "./Graph";
import { ElementOrder } from "./ElementOrder";
import { MutableGraph } from "./MutableGraph";
import { ConfigurableMutableGraph } from "./ConfigurableMutableGraph";
/*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modifications (C) 2019 Ben Sorohan
*/
/**
* A builder for constructing instances of {@link MutableGraph} with user-defined properties.
*
* @remarks
*
* A graph built by this class will have the following properties by default:
*
* <ul>
* <li>does not allow self-loops</li>
* <li>orders {@link BaseGraph.nodes} in the order in which the elements were added</li>
* </ul>
*
* Example of use:
*
* ```typescript
* const graph: MutableGraph<String> = GraphBuilder.undirected().allowsSelfLoops(true).build();
* graph.putEdge("bread", "bread");
* graph.putEdge("chocolate", "peanut butter");
* graph.putEdge("peanut butter", "jelly");
* ```
*
* @public
*/
export class GraphBuilder<N> extends AbstractGraphBuilder<N> {
/** Returns a {@link GraphBuilder} for building directed graphs. */
public static directed<T>(): GraphBuilder<T> {
return new GraphBuilder<T>(true);
}
/** Returns a {@link GraphBuilder} for building undirected graphs. */
public static undirected<T>(): GraphBuilder<T> {
return new GraphBuilder<T>(false);
}
/**
* Returns a {@link GraphBuilder} initialized with all properties queryable from `graph`.
*
* <p>The "queryable" properties are those that are exposed through the {@link Graph} interface,
* such as {@link BaseGraph.isDirected}. Other properties, such as {@link GraphBuilder.expectedNodeCount},
* are not set in the new builder.
*/
public static from<T>(graph: Graph<T>): GraphBuilder<T> {
return new GraphBuilder<T>(graph.isDirected())
.allowsSelfLoops(graph.allowsSelfLoops())
.nodeOrder(graph.nodeOrder());
}
/**
* Specifies whether the graph will allow self-loops (edges that connect a node to itself).
* Attempting to add a self-loop to a graph that does not allow them will throw an error.
*/
public allowsSelfLoops(allowsSelfLoops: boolean): GraphBuilder<N> {
this.allowsSelfLoopsValue = allowsSelfLoops;
return this;
}
/**
* Specifies the expected number of nodes in the graph.
*
* throws an error if `expectedNodeCount` is negative
*/
public expectedNodeCount(expectedNodeCount: number): GraphBuilder<N> {
this.expectedNodeCountValue = expectedNodeCount;
return this;
}
/** Specifies the order of iteration for the elements of {@link BaseGraph.nodes}. */
public nodeOrder(nodeOrder: ElementOrder<N>): GraphBuilder<N> {
this.nodeOrderValue = nodeOrder;
return this;
}
/** Returns an empty {@link MutableGraph} with the properties of this {@link GraphBuilder}. */
public build(): MutableGraph<N> {
return new ConfigurableMutableGraph<N>(this);
}
}
|
2dce964b4c59088519fb215bd164ef56d76def4c | TypeScript | thomastoye/typesaurus | /src/subcollection/index.ts | 3.390625 | 3 | import { Ref } from '../ref'
import { Collection, collection } from '../collection'
/**
* The subcollection function type.
*/
export type Subcollection<RefModel, CollectionModel> = (
ref: Ref<RefModel> | string
) => Collection<CollectionModel>
/**
* Creates a subcollection function which accepts parent document reference
* and returns the subcollection trasnformed into a collection object.
*
* ```ts
* import { subcollection, collection, ref, add } from 'typesaurus'
*
* type User = { name: string }
* type Order = { item: string }
* const users = collection<User>('users')
* const userOrders = subcollection<Order, User>('orders')
*
* const sashasOrders = userOrders('00sHm46UWKObv2W7XK9e')
* //=> { __type__: 'collection', path: 'users/00sHm46UWKObv2W7XK9e/orders' }
* // Also accepts reference:
* userOrders(ref(users, '00sHm46UWKObv2W7XK9e')))
*
* add(sashasOrders, { item: 'Snowboard boots' })
* ```
*
* @param name - The subcollection name
* @param parentCollection - The parent collection
* @returns Function which accepts parent document
*/
function subcollection<CollectionModel, RefModel>(
name: string,
parentCollection: Collection<RefModel>
): Subcollection<RefModel, CollectionModel> {
// TODO: Throw an exception when a collection has different name
return ref =>
collection<RefModel>(
`${parentCollection.path}/${
typeof ref === 'string' ? ref : ref.id
}/${name}`
)
}
export { subcollection }
|
ea30c70b4b4996adfa12cffe40e7240eccb7d26a | TypeScript | wenyejie/utils | /src/dayStart.ts | 2.75 | 3 | /**
* 返回一天的开始
* @param date 时间
*/
export const dayStart = (date: Date) => {
date.setHours(0, 0, 0, 0)
return date
}
export default dayStart
|
5d3db3634d9e07b2b2b24291a6fef72972320d40 | TypeScript | Nietzsche-dev/test | /src/app/services/article.service.ts | 2.515625 | 3 | import { Injectable } from '@angular/core';
import {Article} from '../models/article';
import {Observable, throwError} from 'rxjs/index';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {catchError, retry} from 'rxjs/internal/operators';
@Injectable({
providedIn: 'root'
})
export class ArticleService {
articles: Article[];
apiUrl = 'http://localhost:3000/article';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private httpClient: HttpClient) {
}
getAllArticles(): Observable<Article[]> {
return this.httpClient.get<Article[]>(this.apiUrl).pipe(
retry(1),
catchError(this.handleError)
);
}
getArticleById(id: number): Observable<Article> {
return this.httpClient.get<Article>(this.apiUrl + '/' + id).pipe(
retry(1),
catchError(this.handleError)
);
}
add(article: Article): Observable<Article> {
article.dateCreate = new Date();
return this.httpClient.post<Article>(this.apiUrl,article,this.httpOptions).pipe(
catchError(this.handleError)
)
}
edit(articleToEdit: Article): void {
this.articles
.filter(
article => article.id === articleToEdit.id)[0] = articleToEdit;
}
deleteArticle(article: Article): Article[] {
this.articles = this.articles
.filter(articleToDelete =>
articleToDelete !== article);
return this.articles;
}
handleError(error) {
let errorMessage = '';
if ( error.error instanceof ErrorEvent ) {
errorMessage = error.error.message;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
}
|
d3a245044eeece56e85e33bba4e8aa2fdc64f6a9 | TypeScript | capricorn86/happy-dom | /packages/happy-dom/test/tree-walker/NodeIterator.test.ts | 2.84375 | 3 | import Window from '../../src/window/Window.js';
import IWindow from '../../src/window/IWindow.js';
import IDocument from '../../src/nodes/document/IDocument.js';
import NodeFilter from '../../src/tree-walker/NodeFilter.js';
import Element from '../../src/nodes/element/Element.js';
import Comment from '../../src/nodes/comment/Comment.js';
import Node from '../../src/nodes/node/Node.js';
import TreeWalkerHTML from './data/TreeWalkerHTML.js';
import { beforeEach, describe, it, expect } from 'vitest';
import INode from '../../src/nodes/node/INode.js';
const NODE_TO_STRING = (node: Node): string => {
if (node instanceof Element) {
return node.outerHTML;
} else if (node instanceof Comment) {
return '<!--' + node.textContent + '-->';
}
return node['textContent'];
};
describe('NodeIterator', () => {
let window: IWindow;
let document: IDocument;
beforeEach(() => {
window = new Window();
document = window.document;
document.write(TreeWalkerHTML);
});
describe('nextNode()', () => {
it('Walks into each node in the DOM tree.', () => {
const nodeIterator = document.createNodeIterator(document.body);
const html: string[] = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
html.push(NODE_TO_STRING(currentNode));
}
expect(html).toEqual([
'\n\t\t\t',
'<div class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t\t<span>Span</span>\n\t\t\t</div>',
'\n\t\t\t\t',
'<!-- Comment 1 !-->',
'\n\t\t\t\t',
'<b>Bold</b>',
'Bold',
'\n\t\t\t\t',
'<!-- Comment 2 !-->',
'\n\t\t\t\t',
'<span>Span</span>',
'Span',
'\n\t\t\t',
'\n\t\t\t',
'<article class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t</article>',
'\n\t\t\t\t',
'<!-- Comment 1 !-->',
'\n\t\t\t\t',
'<b>Bold</b>',
'Bold',
'\n\t\t\t\t',
'<!-- Comment 2 !-->',
'\n\t\t\t',
'\n\t\t'
]);
});
it('Walks into each HTMLElement in the DOM tree when whatToShow is set to NodeFilter.SHOW_ELEMENT.', () => {
const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT);
const html: string[] = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
html.push(currentNode.outerHTML);
}
expect(html).toEqual([
'<div class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t\t<span>Span</span>\n\t\t\t</div>',
'<b>Bold</b>',
'<span>Span</span>',
'<article class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t</article>',
'<b>Bold</b>'
]);
});
it('Walks into each HTMLElement and Comment in the DOM tree when whatToShow is set to NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_COMMENT.', () => {
const nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_COMMENT
);
const html: string[] = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
html.push(NODE_TO_STRING(currentNode));
}
expect(html).toEqual([
'<div class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t\t<span>Span</span>\n\t\t\t</div>',
'<!-- Comment 1 !-->',
'<b>Bold</b>',
'<!-- Comment 2 !-->',
'<span>Span</span>',
'<article class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t</article>',
'<!-- Comment 1 !-->',
'<b>Bold</b>',
'<!-- Comment 2 !-->'
]);
});
it('Walks into each HTMLElement in the DOM tree when whatToShow is set to NodeFilter.SHOW_ALL and provided filter function returns NodeFilter.FILTER_SKIP if not an HTMLElement and NodeFilter.FILTER_ACCEPT if it is.', () => {
const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ALL, {
acceptNode: (node: Node) =>
node.nodeType === Node.ELEMENT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
});
const html: string[] = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
html.push(NODE_TO_STRING(currentNode));
}
expect(html).toEqual([
'<div class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t\t<span>Span</span>\n\t\t\t</div>',
'<b>Bold</b>',
'<span>Span</span>',
'<article class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t</article>',
'<b>Bold</b>'
]);
});
it('Rejects the two first nodes when provided filter function returns NodeFilter.FILTER_REJECT on the two first nodes.', () => {
let rejected = 0;
const NodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ALL, {
acceptNode: () => {
if (rejected < 2) {
rejected++;
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
});
const html: string[] = [];
let currentNode;
while ((currentNode = NodeIterator.nextNode())) {
html.push(NODE_TO_STRING(currentNode));
}
expect(html).toEqual([
'\n\t\t\t',
'<article class="class1 class2" id="id">\n\t\t\t\t<!-- Comment 1 !-->\n\t\t\t\t<b>Bold</b>\n\t\t\t\t<!-- Comment 2 !-->\n\t\t\t</article>',
'\n\t\t\t\t',
'<!-- Comment 1 !-->',
'\n\t\t\t\t',
'<b>Bold</b>',
'Bold',
'\n\t\t\t\t',
'<!-- Comment 2 !-->',
'\n\t\t\t',
'\n\t\t'
]);
});
});
describe('previousNode()', () => {
it('Returns the previous node when executed after a nextNode() call.', () => {
const NodeIterator = document.createNodeIterator(document.body);
let expectedPreviousNode: INode | null = null;
let previousNode: INode | null = null;
let currentNode: INode | null = null;
while ((currentNode = NodeIterator.nextNode())) {
if (previousNode) {
previousNode = NodeIterator.previousNode();
expect(previousNode === expectedPreviousNode).toBe(true);
NodeIterator.nextNode();
}
expectedPreviousNode = currentNode;
}
});
});
});
|
71ea805d73811bcabe19cf0a727e2dd877086302 | TypeScript | feljx/mandelbrot-web | /src/app/throttle.ts | 3.03125 | 3 | // Throttle.
function throttle(func: Function, limit: number) {
// @ts-ignore
let inThrottle: NodeJS.Timeout | boolean
return function (...args: any[]) {
if (!inThrottle) {
func(...args)
inThrottle = setTimeout(() => (inThrottle = false), limit)
}
}
}
export default throttle
|
c4707d7a7455368b088897bbe02d1a10e6b892d5 | TypeScript | nadermedhet148/contract-generator | /backend/src/Infrastructure/HTTP/Controllers/ContractController.ts | 2.515625 | 3 | import { createConnection, getConnection } from "typeorm";
import PdfManger from "../../../Domain/Helpers/PdfManger";
import ContractService from "../../../Domain/Services/ContractSerivce";
import { establishConnection } from "../../Database/connection/GetConnection";
import ContractRepository from "../../Database/Repositories/ContractRepository";
import LocalStorage from "../../FileStorage/LocalStorage";
import ErrorHandler from "./Handlers/ErrorHandler";
import SuccessHandler from "./Handlers/SuccessHandler";
export default class ContractController {
constructor() {}
async getContract(uniqueIdentifer: string) {
try {
const contractService = new ContractService(
new ContractRepository(getConnection('default')),
new PdfManger(),
new LocalStorage()
);
return SuccessHandler(await contractService.getContract(uniqueIdentifer));
} catch (e) {
return ErrorHandler(e);
}
}
async createContract(
name: string,
phone: string,
email: string,
address: string,
rentAmount: number,
userId: number,
buffer: Buffer,
type,
) {
try {
const contractService = new ContractService(
new ContractRepository(getConnection('default')),
new PdfManger(),
new LocalStorage()
);
return SuccessHandler(
await contractService.createContract({
name,
phone,
email,
address,
rentAmount,
userId,
buffer ,
fileType : type
})
);
} catch (e) {
return ErrorHandler(e);
}
}
}
|
1ecdea460ed0c825a39049854fed97d05f949aca | TypeScript | Loksli17/diploma | /client/src/canvas/shapes/Bezier.ts | 2.90625 | 3 | import Shape from "./Shape";
import Point from '../Point';
export default class Bezier extends Shape{
public width: number = 1;
constructor(points: Array<Point>, userId: number, color: string, width: number){
super(`Bezier${++Bezier.countNumber}`, userId, color);
this.points = points.slice();
this.width = width;
this.icon = 'bezier.svg';
}
public render(ctx: CanvasRenderingContext2D | null): void{
if(ctx == undefined){
throw new Error("CTX is null. Why?");
}
ctx.lineWidth = this.width;
ctx.strokeStyle = this.color;
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
ctx.bezierCurveTo(this.points[1].x, this.points[1].y, this.points[2].x, this.points[2].y, this.points[3].x, this.points[3].y);
ctx.stroke();
}
}
|
838492b25391e6dbf0a6f7dcf60fa3f305f8912e | TypeScript | marsch/hyperhyperspace-core | /src/crypto/ciphers/JSEncryptRSA.ts | 2.5625 | 3 | //import { JSEncrypt } from 'jsencrypt';
import { SHA, SHAImpl } from '../hashing';
import { RSA } from './RSA';
// dummy objects for JSEncrypt
let fixNavigator = false;
if ((global as any).navigator === undefined) {
(global as any).navigator = {appName: 'nodejs'};
fixNavigator = true;
}
let fixWindow = false;
if ((global as any).window === undefined) {
(global as any).window = {};
fixWindow = true;
}
const JSEncrypt = require('jsencrypt').JSEncrypt;
if (fixNavigator) {
(global as any).navigator = undefined;
}
if (fixWindow) {
(global as any).window = undefined;
}
class JSEncryptRSA implements RSA {
static PKCS8 = 'pkcs8';
private crypto? : typeof JSEncrypt;
private sha : SHA;
constructor(sha?: SHA) {
if (sha === undefined) {
this.sha = new SHAImpl();
} else {
this.sha = sha;
}
}
async generateKey(bits: number) {
this.crypto = new JSEncrypt({default_key_size : bits.toString()});
this.crypto.getKey();
};
async loadKeyPair(publicKey: string, privateKey?: string) {
this.crypto = new JSEncrypt();
this.crypto.setPublicKey(publicKey);
if (privateKey !== undefined) {
this.crypto.setPrivateKey(privateKey);
}
}
getPublicKey() {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to get public key");
} else {
return this.crypto.getPublicKey();
}
}
getPrivateKey() {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to get private key");
} else {
return this.crypto.getPrivateKey();
}
}
getFormat() {
return 'pkcs8';
}
async sign(text: string) {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to sign");
} else {
return this.crypto.sign(text, this.sha.sha256heximpl(), 'sha256');
}
};
async verify(text: string, signature: string) {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to verify");
} else {
return this.crypto.verify(text, signature, this.sha.sha256heximpl());
}
};
async encrypt(plainText: string) {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to encrypt");
} else {
return this.crypto.encrypt(plainText);
}
};
async decrypt(cypherText : string) {
if (this.crypto === undefined) {
throw new Error("RSA key pair initialization is missing, attempted to decrypt");
} else {
return this.crypto.decrypt(cypherText);
}
};
}
export { JSEncryptRSA }; |
7133f786b5fa2790f3a67bee67594ffcae3e91eb | TypeScript | idewindy/yozora | /packages/core-tokenizer/src/types/phrasing-content.ts | 2.890625 | 3 | import type { YastNode } from '@yozora/ast'
import type { NodeInterval, NodePoint } from '@yozora/character'
import type { YastBlockToken } from './token'
/**
* typeof PhrasingContent
*/
export const PhrasingContentType = 'phrasingContent'
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type PhrasingContentType = typeof PhrasingContentType
/**
* Phrasing content represent the text in a document, and its markup.
*
* @see https://github.com/syntax-tree/mdast#phrasingcontent
*/
export interface PhrasingContent extends YastNode<PhrasingContentType> {
/**
* Inline data nodes
*/
contents: NodePoint[]
}
/**
* Middle token during the whole match and parse phase.
*/
export interface PhrasingContentToken
extends YastBlockToken<PhrasingContentType> {
/**
* Lines of a PhrasingContent.
*/
lines: PhrasingContentLine[]
}
/**
* Phrasing content lines
*/
export interface PhrasingContentLine extends NodeInterval {
/**
* Array of NodePoint which contains all the contents of this line.
*/
nodePoints: ReadonlyArray<NodePoint>
/**
* The index of first non-blank character in the rest of the current line
*/
firstNonWhitespaceIndex: number
/**
* The precede space count, one tab equals four space.
* @see https://github.github.com/gfm/#tabs
*/
countOfPrecedeSpaces: number
}
|
66edb64c15f077c6c7bbf352cb7ff5b9f1560b7d | TypeScript | NetroScript/rezeptinator | /server/ingredient/nutrient.entity.ts | 2.546875 | 3 | import { INutrients } from '@common/Model/Ingredient';
import { ApiHideProperty } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity('nutrient')
export class NutrientEntity implements INutrients {
@Exclude()
@PrimaryGeneratedColumn()
@ApiHideProperty()
id: number;
@Column('float')
alcohol = 0;
@Column('float')
calories = 0;
@Column('float')
carbs = 0;
@Column('float')
fat = 0;
@Column('float')
fibers = 0;
@Column('float')
protein = 0;
@Column('float')
sugar = 0;
constructor(data?: INutrients) {
if (data !== undefined) {
Object.assign(this, data);
}
}
}
|
62ad33e3a8bd7275c52ec4ac90e9418ba5b7d4c4 | TypeScript | VladThePaler/screeps-typescript-starter | /src/Api/Spawn.Api.ts | 2.59375 | 3 | import { SpawnHelper } from "Helpers/SpawnHelper";
import UtilHelper from "Helpers/UtilHelper";
import {
domesticRolePriority,
militaryRolePriority,
remoteRolePriority,
ROLE_REMOTE_MINER,
ROLE_REMOTE_RESERVER,
GROUPED,
COLLATED
} from "utils/Constants";
import MemoryHelperRoom from "../Helpers/MemoryHelper_Room";
import RoomHelper from "../Helpers/RoomHelper";
import MemoryApi from "./Memory.Api";
/**
* The API used by the spawn manager
*/
export default class SpawnApi {
/**
* Get count of all creeps, or of one if creepConst is specified
* @param room the room we are getting the count for
* @param creepConst [Optional] Count only one role
*/
public static getCreepCount(room: Room, creepConst?: RoleConstant): number {
const filterFunction = creepConst === undefined ? undefined : (c: Creep) => c.memory.role === creepConst;
return MemoryApi.getMyCreeps(room, filterFunction).length;
}
/**
* get creep limits
* @param room the room we want the limits for
*/
public static getCreepLimits(room: Room): CreepLimits {
const creepLimits: CreepLimits = {
domesticLimits: Memory.rooms[room.name].creepLimit["remoteLimits"],
remoteLimits: Memory.rooms[room.name].creepLimit["remoteLimits"],
militaryLimits: Memory.rooms[room.name].creepLimit["militaryLimits"]
};
return creepLimits;
}
/**
* set domestic creep limits
* @param room the room we want limits for
*/
public static generateDomesticCreepLimits(room: Room): DomesticCreepLimits {
const domesticLimits: DomesticCreepLimits = {
miner: 0,
harvester: 0,
worker: 0,
powerUpgrader: 0,
lorry: 0
};
// check what room state we are in
switch (room.memory.roomState) {
// Intro
case ROOM_STATE_INTRO:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 1;
domesticLimits[ROLE_HARVESTER] = 1;
domesticLimits[ROLE_WORKER] = 1;
break;
// Beginner
case ROOM_STATE_BEGINNER:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 4;
domesticLimits[ROLE_HARVESTER] = 4;
domesticLimits[ROLE_WORKER] = 4;
break;
// Intermediate
case ROOM_STATE_INTER:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 2;
domesticLimits[ROLE_HARVESTER] = 3;
domesticLimits[ROLE_WORKER] = 5;
break;
// Advanced
case ROOM_STATE_ADVANCED:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 2;
domesticLimits[ROLE_HARVESTER] = 2;
domesticLimits[ROLE_WORKER] = 4;
domesticLimits[ROLE_POWER_UPGRADER] = 0;
domesticLimits[ROLE_LORRY] = 0;
break;
// Upgrader
case ROOM_STATE_UPGRADER:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 2;
domesticLimits[ROLE_HARVESTER] = 2;
domesticLimits[ROLE_WORKER] = 2;
domesticLimits[ROLE_POWER_UPGRADER] = 1;
break;
// Stimulate
case ROOM_STATE_STIMULATE:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 2;
domesticLimits[ROLE_HARVESTER] = 3;
domesticLimits[ROLE_WORKER] = 3;
domesticLimits[ROLE_POWER_UPGRADER] = 2;
domesticLimits[ROLE_LORRY] = 2;
break;
// Seige
case ROOM_STATE_SEIGE:
// Domestic Creep Definitions
domesticLimits[ROLE_MINER] = 2;
domesticLimits[ROLE_HARVESTER] = 3;
domesticLimits[ROLE_WORKER] = 2;
domesticLimits[ROLE_LORRY] = 1;
break;
}
// Return the limits
return domesticLimits;
}
/**
* set remote creep limits
* (we got shooters on deck)
* @param room the room we want limits for
*/
public static generateRemoteCreepLimits(room: Room): RemoteCreepLimits {
const remoteLimits: RemoteCreepLimits = {
remoteMiner: 0,
remoteHarvester: 0,
remoteReserver: 0,
remoteColonizer: 0,
remoteDefender: 0
};
const numRemoteRooms: number = RoomHelper.numRemoteRooms(room);
const numClaimRooms: number = RoomHelper.numClaimRooms(room);
// If we do not have any remote rooms, return the initial remote limits (Empty)
if (numRemoteRooms <= 0 && numClaimRooms <= 0) {
return remoteLimits;
}
// Gather the rest of the data only if we have a remote room or a claim room
const numRemoteDefenders = RoomHelper.numRemoteDefenders(room);
const numRemoteSources: number = RoomHelper.numRemoteSources(room);
// check what room state we are in
switch (room.memory.roomState) {
// Advanced
case ROOM_STATE_ADVANCED:
// 1 'Squad' per source (harvester and miner) and a reserver
// Remote Creep Definitions
remoteLimits[ROLE_REMOTE_MINER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_HARVESTER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_RESERVER] = numRemoteRooms;
remoteLimits[ROLE_COLONIZER] = numClaimRooms;
remoteLimits[ROLE_REMOTE_DEFENDER] = numRemoteDefenders;
break;
// Upgrader
case ROOM_STATE_UPGRADER:
// 1 'Squad' per source (harvester and miner) and a reserver
// Remote Creep Definitions
remoteLimits[ROLE_REMOTE_MINER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_HARVESTER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_RESERVER] = numRemoteRooms;
remoteLimits[ROLE_COLONIZER] = numClaimRooms;
remoteLimits[ROLE_REMOTE_DEFENDER] = numRemoteDefenders;
break;
// Stimulate
case ROOM_STATE_STIMULATE:
// 1 'Squad' per source (harvester and miner) and a reserver
// Remote Creep Definitions
remoteLimits[ROLE_REMOTE_MINER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_HARVESTER] = numRemoteSources;
remoteLimits[ROLE_REMOTE_RESERVER] = numRemoteRooms;
remoteLimits[ROLE_COLONIZER] = numClaimRooms;
remoteLimits[ROLE_REMOTE_DEFENDER] = numRemoteDefenders;
break;
}
// Return the limits
return remoteLimits;
}
/**
* set military creep limits
* @param room the room we want limits for
*/
public static generateMilitaryCreepLimits(room: Room): MilitaryCreepLimits {
const militaryLimits: MilitaryCreepLimits = {
zealot: 0,
stalker: 0,
medic: 0
};
// Check for attack flags and adjust accordingly
// Check if we need defenders and adjust accordingly
// Return the limits
return militaryLimits;
}
/**
* set creep limits for the room
* @param room the room we are setting limits for
*/
public static setCreepLimits(room: Room): void {
// Set Domestic Limits to Memory
MemoryHelperRoom.updateDomesticLimits(room, this.generateDomesticCreepLimits(room));
// Set Remote Limits to Memory
MemoryHelperRoom.updateRemoteLimits(room, this.generateRemoteCreepLimits(room));
// Set Military Limits to Memory
MemoryHelperRoom.updateMilitaryLimits(room, this.generateMilitaryCreepLimits(room));
}
/**
* get the first available open spawn for a room
* @param room the room we are checking the spawn for
*/
public static getOpenSpawn(room: Room): Structure<StructureConstant> | null {
// Get all openSpawns, and return the first
const openSpawns = MemoryApi.getStructureOfType(
room,
STRUCTURE_SPAWN,
(spawn: StructureSpawn) => !spawn.spawning
);
return _.first(openSpawns);
}
/**
* get next creep to spawn
* @param room the room we want to spawn them in
*/
public static getNextCreep(room: Room): string | null {
// Get Limits for each creep department
const creepLimits: CreepLimits = this.getCreepLimits(room);
// Check if we need a domestic creep -- Return role if one is found
for (const role of domesticRolePriority) {
if (this.getCreepCount(room, role) < creepLimits.domesticLimits[role]) {
return role;
}
}
// Check if we need a military creep -- Return role if one is found
for (const role of militaryRolePriority) {
if (this.getCreepCount(room, role) < creepLimits.militaryLimits[role]) {
return role;
}
}
// Check if we need a remote creep -- Return role if one is found
for (const role of remoteRolePriority) {
if (this.getCreepCount(room, role) < creepLimits.remoteLimits[role]) {
return role;
}
}
// Return null if we don't need to spawn anything
return null;
}
/**
* spawn the next creep
* TODO Complete this
* @param room the room we want to spawn them in
* @param BodyPartConstant[] the body array of the creep
* @param RoleConstant the role of the creep
*/
public static spawnNextCreep(room: Room): void {
// brock hates empty blocks
}
/**
* get energy cost of creep
* TODO Complete this
* @param room the room we are spawning them in
* @param RoleConstant the role of the creep
* @param tier the tier of this creep we are spawning
*/
public static getEnergyCost(room: Room, roleConst: RoleConstant, tier: number): number {
return 1;
}
/**
* check what tier of this creep we are spawning
* TODO Complete this
* @param room the room we are spawning them in
* @param RoleConstant the role of the creep
*/
public static getTier(room: Room, roleConst: RoleConstant): number {
return 1;
}
/**
* get the memory options for this creep
* TODO Complete this
* @param room the room we are spawning it in
* @param RoleConstant the role of the creep
* @param tier the tier of this creep we are spawning
*/
private static generateCreepOptions(room: Room, roleConst: RoleConstant, tier: number): void {
// .keep
}
/**
* Generate the body for the creep based on the tier and role
* @param tier the tier our room is at
* @param role the role of the creep we want
*/
public static generateCreepBody(tier: TierConstant, role: RoleConstant): BodyPartConstant[] | undefined {
// Call the correct helper function based on creep role
// Miner
switch(role){
case ROLE_MINER: return SpawnHelper.generateMinerBody(tier);
case ROLE_HARVESTER: return SpawnHelper.generateHarvesterBody(tier);
case ROLE_WORKER: return SpawnHelper.generateWorkerBody(tier);
case ROLE_LORRY: return SpawnHelper.generateLorryBody(tier);
case ROLE_POWER_UPGRADER: return SpawnHelper.generatePowerUpgraderBody(tier);
case ROLE_REMOTE_MINER: return SpawnHelper.generateRemoteMinerBody(tier);
case ROLE_REMOTE_HARVESTER: return SpawnHelper.generateRemoteHarvesterBody(tier);
case ROLE_COLONIZER: return SpawnHelper.generateRemoteColonizerBody(tier);
case ROLE_REMOTE_DEFENDER: return SpawnHelper.generateRemoteDefenderBody(tier);
case ROLE_REMOTE_RESERVER: return SpawnHelper.generateRemoteReserverBody(tier);
case ROLE_ZEALOT: return SpawnHelper.generateZealotBody(tier);
case ROLE_MEDIC: return SpawnHelper.generateMedicBody(tier);
case ROLE_STALKER: return SpawnHelper.generateStalkerBody(tier);
default:
UtilHelper.throwError(
"Creep body failed generating.",
"The role specified was invalid for generating the creep body.",
ERROR_ERROR
);
return undefined;
}
// If the role provided does not exist, throw an error and return undefined
}
/**
* Generate a body for a creep given a descriptor object
* @param descriptor An object that looks like { BodyPartConstant: NumberOfParts, ... }
* @param mixType [Optional] How to order the body parts - Default is to group like parts in the order provided
*/
public static getBodyFromObject(descriptor: StringMap, mixType?: string): BodyPartConstant[] {
let creepBody: BodyPartConstant[] = [];
if (mixType === undefined || mixType === GROUPED) {
// Group them by part type -- e.g. MOVE MOVE MOVE CARRY CARRY WORK WORK WORK
creepBody = SpawnHelper.getBody_Grouped(descriptor);
} else if (mixType === COLLATED) {
// Layer the parts -- e.g. MOVE CARRY WORK MOVE CARRY WORK
creepBody = SpawnHelper.getBody_Collated(descriptor);
}
return creepBody;
}
/**
* Returns a creep body part array, or null if invalid parameters were passed in
* @param bodyObject The object that describes the creep's body parts
* @param opts The options for generating the creep body from the descriptor
*/
public static getCreepBody(bodyObject: CreepBodyDescriptor, opts?: CreepBodyOptions): BodyPartConstant[] | null {
let creepBody: BodyPartConstant[] = [];
let numHealParts = 0;
/**
* If opts is undefined, use default options
*/
if (opts === undefined) {
opts = { mixType: GROUPED, toughFirst: false, healLast: false };
}
/**
* Verify bodyObject - Return null if invalid
*/
if (SpawnHelper.verifyDescriptor(bodyObject) === false) {
UtilHelper.throwError(
"Invalid Creep Body Descriptor",
"Ensure that the object being passed to getCreepBody is in the format { BodyPartConstant: NumberParts } and that NumberParts is > 0.",
ERROR_ERROR
);
return null;
}
/**
* Append tough parts on creepBody first - Delete tough property from bodyObject
*/
if (opts.toughFirst && bodyObject.tough) {
creepBody = SpawnHelper.generateParts("tough", bodyObject.tough);
delete bodyObject.tough;
}
/**
* Retain Heal Information to append on the end of creepBody - Delete heal property from bodyObject
*/
if (opts.healLast && bodyObject.heal) {
numHealParts = bodyObject.heal;
delete bodyObject.heal;
}
/**
* If mixType is grouped, add onto creepBody
*/
if (opts.mixType === GROUPED) {
const bodyParts = SpawnHelper.getBody_Grouped(bodyObject);
for (let i = 0; i < bodyParts.length; i++) {
creepBody.push(bodyParts[i]);
}
}
/**
* If mixType is collated, add onto creepBody
*/
if (opts.mixType === COLLATED) {
const bodyParts = SpawnHelper.getBody_Collated(bodyObject);
for (let i = 0; i < bodyParts.length; i++) {
creepBody.push(bodyParts[i]);
}
}
/**
* Append Heal Information that was retained at the beginning of the function
*/
if (opts.healLast) {
for (let i = 0; i < numHealParts; i++) {
creepBody.push("heal");
}
}
return creepBody;
}
/**
* check if our remote room needs a remote defender
* @param room the home room associated with the remote room
*/
private static needRemoteDefender(room: Room): boolean {
return false;
}
/**
* get the number of active miners
* ie miners with more than 50 TTL
* @param room the room we are checking in
*/
private static getActiveMiners(room: Room): number {
// all miners with more than 50 TTL
return 1;
}
}
|
b5b11812efc6962d4b7b4fde3b1795b5c5a6daf2 | TypeScript | getunid/unid-node-wallet-sdk | /src/utils/datetime.ts | 3.21875 | 3 | import moment, { Moment } from 'moment'
/**
*/
enum DateTimeTypes {
default = 'YYYY-MM-DDTHH:mm:ss[Z]',
iso8601 = 'YYYY-MM-DDTHH:mm:ss.SSSSSS[Z]',
}
/**
*/
class DateTimeUtils {
/**
*/
private datetime: Date | undefined
/**
* @param input
*/
constructor(input: string | undefined)
constructor(input: Moment | undefined)
constructor(input: Date | undefined)
constructor(input: any | undefined) {
if (input !== undefined) {
if (typeof(input) === 'string') {
this.datetime = moment(input, DateTimeTypes.iso8601).toDate()
} else if (moment.isMoment(input)) {
this.datetime = input.toDate()
} else {
this.datetime = input
}
}
}
/**
* @returns
*/
toDate(): Date | undefined {
return this.datetime
}
/**
* @returns
*/
$toDate(): Date {
if (this.datetime === undefined) {
this.datetime = new Date(0)
}
return this.datetime
}
/**
* @param format
* @returns
*/
toString(format: string | DateTimeTypes): string | undefined {
if (this.datetime !== undefined) {
return moment(this.datetime).utc().format(format)
}
return undefined
}
/**
* @param format
* @returns
*/
$toString(format: string | DateTimeTypes): string {
if (this.datetime === undefined) {
this.datetime = new Date(0)
}
return moment(this.datetime).utc().format(format)
}
/**
* @returns
*/
adjustMidnight(): DateTimeUtils {
if (this.datetime !== undefined) {
this.datetime = moment(this.datetime).startOf('day').toDate()
}
return this
}
/**
* @returns
*/
adjustEndOfDay(): DateTimeUtils {
if (this.datetime !== undefined) {
this.datetime = moment(this.datetime).endOf('day').toDate()
}
return this
}
/**
* @returns
*/
adjustBeginOfSecond(): DateTimeUtils {
if (this.datetime !== undefined) {
this.datetime = moment(this.datetime).startOf('second').toDate()
}
return this
}
/**
* @returns
*/
adjustEndOfSecond(): DateTimeUtils {
if (this.datetime !== undefined) {
this.datetime = moment(this.datetime).endOf('second').toDate()
}
return this
}
/**
* @returns
*/
add24Hours(): DateTimeUtils {
if (this.datetime !== undefined) {
this.datetime = moment(this.datetime).add(1, 'days').toDate()
}
return this
}
}
export {
DateTimeUtils, DateTimeTypes,
} |
85b765de16256c433271a2f0a60821f439388de6 | TypeScript | Vastlaan/ugorala | /admin/validations/index.ts | 2.84375 | 3 | export function validateMimeTypeMulter(file, cb) {
// Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
// Check mime
const mimetype = filetypes.test(file.mimetype);
if (mimetype) {
return cb(null, true);
} else {
cb({ error: "You can upload images only!" });
}
} |
470e738a972fc3fd13b2a43b580bae205ddd92a0 | TypeScript | emrecavunt/prisma-examples | /misc/react-graphql-fullstack/frontend/src/generated/types.ts | 2.765625 | 3 | export type Maybe<T> = T | null;
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string,
String: string,
Boolean: boolean,
Int: number,
Float: number,
DateTime: any,
};
export type BooleanFilter = {
equals?: Maybe<Scalars['Boolean']>,
not?: Maybe<Scalars['Boolean']>,
};
export type DateTimeFilter = {
equals?: Maybe<Scalars['DateTime']>,
not?: Maybe<Scalars['DateTime']>,
in?: Maybe<Array<Scalars['DateTime']>>,
notIn?: Maybe<Array<Scalars['DateTime']>>,
lt?: Maybe<Scalars['DateTime']>,
lte?: Maybe<Scalars['DateTime']>,
gt?: Maybe<Scalars['DateTime']>,
gte?: Maybe<Scalars['DateTime']>,
};
export type Mutation = {
__typename?: 'Mutation',
signupUser: User,
deletePost?: Maybe<Post>,
createDraft: Post,
publish?: Maybe<Post>,
};
export type MutationSignupUserArgs = {
data: UserCreateInput
};
export type MutationDeletePostArgs = {
where: PostWhereUniqueInput
};
export type MutationCreateDraftArgs = {
title: Scalars['String'],
content?: Maybe<Scalars['String']>,
authorEmail?: Maybe<Scalars['String']>
};
export type MutationPublishArgs = {
id?: Maybe<Scalars['ID']>
};
export type NullableStringFilter = {
equals?: Maybe<Scalars['String']>,
not?: Maybe<Scalars['String']>,
in?: Maybe<Array<Scalars['String']>>,
notIn?: Maybe<Array<Scalars['String']>>,
lt?: Maybe<Scalars['String']>,
lte?: Maybe<Scalars['String']>,
gt?: Maybe<Scalars['String']>,
gte?: Maybe<Scalars['String']>,
contains?: Maybe<Scalars['String']>,
startsWith?: Maybe<Scalars['String']>,
endsWith?: Maybe<Scalars['String']>,
};
export type Post = {
__typename?: 'Post',
id: Scalars['ID'],
createdAt: Scalars['DateTime'],
updatedAt: Scalars['DateTime'],
title: Scalars['String'],
content?: Maybe<Scalars['String']>,
published: Scalars['Boolean'],
author?: Maybe<User>,
};
export type PostCreateManyWithoutPostsInput = {
create?: Maybe<Array<PostCreateWithoutAuthorInput>>,
connect?: Maybe<Array<PostWhereUniqueInput>>,
};
export type PostCreateWithoutAuthorInput = {
id?: Maybe<Scalars['ID']>,
createdAt?: Maybe<Scalars['DateTime']>,
updatedAt?: Maybe<Scalars['DateTime']>,
published?: Maybe<Scalars['Boolean']>,
title: Scalars['String'],
content?: Maybe<Scalars['String']>,
};
export type PostFilter = {
every?: Maybe<PostWhereInput>,
some?: Maybe<PostWhereInput>,
none?: Maybe<PostWhereInput>,
};
export type PostWhereInput = {
id?: Maybe<StringFilter>,
createdAt?: Maybe<DateTimeFilter>,
updatedAt?: Maybe<DateTimeFilter>,
published?: Maybe<BooleanFilter>,
title?: Maybe<StringFilter>,
content?: Maybe<NullableStringFilter>,
AND?: Maybe<Array<PostWhereInput>>,
OR?: Maybe<Array<PostWhereInput>>,
NOT?: Maybe<Array<PostWhereInput>>,
author?: Maybe<UserWhereInput>,
};
export type PostWhereUniqueInput = {
id?: Maybe<Scalars['ID']>,
};
export type Query = {
__typename?: 'Query',
post?: Maybe<Post>,
filterPosts: Array<Post>,
feed: Array<Post>,
};
export type QueryPostArgs = {
where: PostWhereUniqueInput
};
export type QueryFilterPostsArgs = {
where?: Maybe<PostWhereInput>
};
export enum Role {
Author = 'AUTHOR',
Admin = 'ADMIN'
}
export type StringFilter = {
equals?: Maybe<Scalars['String']>,
not?: Maybe<Scalars['String']>,
in?: Maybe<Array<Scalars['String']>>,
notIn?: Maybe<Array<Scalars['String']>>,
lt?: Maybe<Scalars['String']>,
lte?: Maybe<Scalars['String']>,
gt?: Maybe<Scalars['String']>,
gte?: Maybe<Scalars['String']>,
contains?: Maybe<Scalars['String']>,
startsWith?: Maybe<Scalars['String']>,
endsWith?: Maybe<Scalars['String']>,
};
export type User = {
__typename?: 'User',
id: Scalars['ID'],
name?: Maybe<Scalars['String']>,
email: Scalars['String'],
posts: Array<Post>,
role: Role,
};
export type UserCreateInput = {
id?: Maybe<Scalars['ID']>,
email: Scalars['String'],
name?: Maybe<Scalars['String']>,
role: Role,
posts?: Maybe<PostCreateManyWithoutPostsInput>,
};
export type UserWhereInput = {
id?: Maybe<StringFilter>,
email?: Maybe<StringFilter>,
name?: Maybe<NullableStringFilter>,
posts?: Maybe<PostFilter>,
role?: Maybe<Role>,
AND?: Maybe<Array<UserWhereInput>>,
OR?: Maybe<Array<UserWhereInput>>,
NOT?: Maybe<Array<UserWhereInput>>,
};
export type CreateDraftMutationVariables = {
title: Scalars['String'],
content: Scalars['String'],
authorEmail: Scalars['String']
};
export type CreateDraftMutation = (
{ __typename?: 'Mutation' }
& { createDraft: (
{ __typename?: 'Post' }
& Pick<Post, 'id' | 'title' | 'content'>
) }
);
export type PostQueryVariables = {
id: Scalars['ID']
};
export type PostQuery = (
{ __typename?: 'Query' }
& { post: Maybe<(
{ __typename?: 'Post' }
& Pick<Post, 'id' | 'title' | 'content' | 'published'>
& { author: Maybe<(
{ __typename?: 'User' }
& Pick<User, 'id' | 'name'>
)> }
)> }
);
export type PublishMutationVariables = {
id: Scalars['ID']
};
export type PublishMutation = (
{ __typename?: 'Mutation' }
& { publish: Maybe<(
{ __typename?: 'Post' }
& Pick<Post, 'id' | 'published'>
)> }
);
export type DeletePostMutationVariables = {
id: Scalars['ID']
};
export type DeletePostMutation = (
{ __typename?: 'Mutation' }
& { deletePost: Maybe<(
{ __typename?: 'Post' }
& Pick<Post, 'id'>
)> }
);
export type DraftsQueryVariables = {};
export type DraftsQuery = (
{ __typename?: 'Query' }
& { filterPosts: Array<(
{ __typename?: 'Post' }
& Pick<Post, 'id' | 'content' | 'title' | 'published'>
& { author: Maybe<(
{ __typename?: 'User' }
& Pick<User, 'id' | 'name'>
)> }
)> }
);
export type FeedQueryVariables = {};
export type FeedQuery = (
{ __typename?: 'Query' }
& { feed: Array<(
{ __typename?: 'Post' }
& Pick<Post, 'id' | 'content' | 'title' | 'published'>
& { author: Maybe<(
{ __typename?: 'User' }
& Pick<User, 'id' | 'name' | 'role'>
)> }
)> }
);
export type SignupUserMutationVariables = {
name: Scalars['String'],
email: Scalars['String']
};
export type SignupUserMutation = (
{ __typename?: 'Mutation' }
& { signupUser: (
{ __typename?: 'User' }
& Pick<User, 'id'>
) }
);
|
dbb4977c77e63ff2259dec335b1e4de46783498b | TypeScript | filimon-danopoulos/wizard-sheet | /src/model/bases/Brewery.ts | 2.71875 | 3 | import Character from '../Character'
import Base from './Base'
export default class Brewery extends Base {
public name: string = 'Brewery'
public description: string =
'There is still some life left in those old casks, and the warband takes full advantage. All soldiers hired by the warband cost 5gc less than the standard price. In addition, the warband gains an additional 10gc after each game through the sale of excess stock.'
public readonly type: string = 'brewery'
public apply(character: Character): void {}
}
|
64d6e564f314b6fb087b3d88537d57d729a0e309 | TypeScript | o-su/warplanes | /src/components/player.ts | 2.921875 | 3 | import { Plane } from "./plane";
import { Projectile } from "./projectile";
import { Point, ProjectileSource } from "../types";
export type PlayerConfiguration = {
sprite: HTMLImageElement;
width: number;
height: number;
gunPositions: Point[];
spriteProjectile: HTMLImageElement;
};
export class Player extends Plane {
private upgrades: PlayerConfiguration[];
constructor(
x: number,
y: number,
lives: number,
config: PlayerConfiguration,
upgrades: PlayerConfiguration[]
) {
super(
x,
y,
lives,
config.sprite,
config.width,
config.height,
config.gunPositions,
config.spriteProjectile
);
this.upgrades = upgrades;
}
shoot = (): Projectile[] => super.shoot(ProjectileSource.Player);
upgrade = (upgradeId: number): void => {
if (this.upgrades[upgradeId]) {
const upgrade: PlayerConfiguration = this.upgrades[upgradeId];
this.sprite = upgrade.sprite;
this.gunPositions = upgrade.gunPositions;
this.width = upgrade.width;
this.height = upgrade.height;
this.spriteProjectile = upgrade.spriteProjectile;
} else {
throw new Error(`Unknown upgrade ${upgradeId}`);
}
};
}
|
1e27f085150e3910a1e0f3b3cd5d78dcf2631175 | TypeScript | ravindudiaz/CompInt | /src/app/child/child.component.ts | 2.53125 | 3 | import { Component, Input, OnChanges, OnInit, SimpleChanges, EventEmitter, Output } from '@angular/core';
import { InteractionService } from '../interaction.service';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() loggedIn: boolean;
// private _loggedIn: boolean;
message: string;
name = 'Ravi';
@Output() greetEvent = new EventEmitter();
person = 'Ravindu';
// get loggedIn(): boolean{
// return this._loggedIn;
// }
// @Input()
// set loggedIn(value: boolean){
// this._loggedIn = value;
// if(value == true){
// this.message = 'Welcome back Ravi!';
// console.log("User is logged in");
// }else{
// this.message = 'Please login';
// console.log("User logged out")
// }
// }
constructor(private _interactionService: InteractionService) { }
ngOnInit(){
this._interactionService.teacherMessage$.subscribe(message =>{
if(message =='Good Morning!'){
alert('Good Morning Teacher');
}else if(message =='Well Done!'){
alert('Thank you teacher')
}
})
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
const loggedInValue = changes['loggedIn'];
if (loggedInValue.currentValue == true){
this.message = "Welcome back Ravi!";
}else{
this.message = 'Please login';
}
}
greetRavi(){
alert('Hey Ravi!')
}
callParentGreet(){
this.greetEvent.emit(this.person);
}
}
|
117d347b29ede78dbe7390f84a909c0fa3989e2b | TypeScript | kimlimjustin/xplorer | /src/Components/Functions/path/joinPath.ts | 3.5625 | 4 | /**
* Join multiple path into a string.
* @param {string[]} ...args paths
* @returns {string}
*/
const joinPath = (...args: string[]): string => {
if (args.length === 0) return '.';
let joined;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg.length > 0) {
if (joined === undefined) joined = arg;
else {
if (!(joined?.endsWith('/') || joined?.endsWith('\\')))
joined += '/';
joined += arg;
}
}
}
if (joined === undefined) return '.';
return joined;
};
export default joinPath;
|
7d884903d986edd76be4aec5a2cd7046ce11b374 | TypeScript | djabraham/vscode-yaml-validation | /server/src/yaml/common.ts | 2.71875 | 3 | 'use strict';
// Source code is substantially from these repositories
// https://github.com/mulesoft-labs/yaml-ast-parser
// https://github.com/nodeca/js-yaml
export function isNothing(subject) {
return (typeof subject === 'undefined') || (null === subject);
}
export function isObject(subject) {
return (typeof subject === 'object') && (null !== subject);
}
export function toArray(sequence) {
if (Array.isArray(sequence)) {
return sequence;
} else if (isNothing(sequence)) {
return [];
}
return [ sequence ];
}
export function extend(target, source) {
var index, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index = 0, length = sourceKeys.length; index < length; index += 1) {
key = sourceKeys[index];
target[key] = source[key];
}
}
return target;
}
export function repeat(string, count) {
var result = '', cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
export function isNegativeZero(number) {
return (0 === number) && (Number.NEGATIVE_INFINITY === 1 / number);
}
|
6bb996a9a2a8e49f4e68af7c0769afd6d198b909 | TypeScript | gameless/babel-forest | /app/octopus.ts | 2.71875 | 3 | /// <reference path="../node_modules/phaser/types/phaser.d.ts" />
import * as MatterJS from 'matter-js';
// @ts-ignore: Property 'Matter' does not exist on type 'typeof Matter'.
const Matter: typeof MatterJS = Phaser.Physics.Matter.Matter;
import * as _ from 'underscore';
import * as color from './color';
import * as random from './random';
import { raycast } from './raycast';
import { Progress } from './save';
function adjacents<T>(array: T[]): [T, T][] {
return _.times(array.length - 1, i => [array[i], array[i + 1]]);
}
function bodyToWorld(body: Matter.Body, point: Matter.Vector): Matter.Vector {
return Matter.Vector.add(
body.position,
Matter.Vector.rotate(point, body.angle)
);
}
interface CollisionFilter {
group: number;
category: number;
mask: number;
}
interface ArmConfig {
x: number;
y: number;
numSegments: number;
segmentLength: number;
segmentRadius: number;
collisionFilter: CollisionFilter;
}
const orange = 0xffa500;
class Arm {
segmentLength: number;
segmentRadius: number;
comp: Matter.Composite;
segments: Matter.Body[];
hook: Matter.Body;
spring: Matter.Constraint;
stopped: boolean;
constructor(config: ArmConfig) {
this.comp = Matter.Composite.create();
const {
x, y,
numSegments,
segmentLength,
segmentRadius,
collisionFilter,
} = config;
this.segmentLength = segmentLength;
this.segmentRadius = segmentRadius;
this.segments = _.times(numSegments, () => Matter.Bodies.rectangle(
x, y, segmentLength, segmentRadius*2,
{ chamfer: { radius: segmentRadius }, collisionFilter, }
));
const constraints = adjacents(this.segments).map(([s1, s2], i) => {
const direction = i % 2 === 0 ? 1 : -1;
const offset = direction * (segmentLength / 2.0 - segmentRadius);
return Matter.Constraint.create({
bodyA: s1,
pointA: { x: offset, y: 0 },
bodyB: s2,
pointB: { x: offset, y: 0 },
stiffness: 1,
length: 0,
});
});
// @ts-ignore: Argument of type 'Body[]' is not assignable ...
Matter.Composite.add(this.comp, this.segments);
// @ts-ignore: Argument of type 'Constraint[]' is not assignable ...
Matter.Composite.add(this.comp, constraints);
this.hook = Matter.Bodies.rectangle(x, y, 1, 1, {
isStatic: true,
collisionFilter: { ...collisionFilter, mask: 0 }
});
const i = numSegments - 1;
const direction = i % 2 === 0 ? 1 : -1;
const offset = direction * (segmentLength / 2.0 - segmentRadius);
this.spring = Matter.Constraint.create({
bodyA: this.segments[numSegments - 1],
bodyB: this.hook,
pointA: { x: offset, y: 0 },
stiffness: 0.01,
length: 0,
});
Matter.Composite.add(this.comp, this.hook);
Matter.Composite.add(this.comp, this.spring);
this.stopped = true;
}
segmentTip(index: number): Matter.Vector {
const direction = index % 2 === 0 ? 1 : -1;
const offset = direction * (this.segmentLength / 2.0 - this.segmentRadius);
return bodyToWorld(this.segments[index], { x: offset, y: 0 });
}
tipPosition(): Matter.Vector {
return this.segmentTip(this.segments.length - 1);
}
stop() {
this.stopped = true;
}
move(point: Matter.Vector) {
this.hook.position = point;
this.stopped = false;
}
update(center: Matter.Vector, reach: number) {
const v = Matter.Vector.sub(this.hook.position, center);
const dist = Matter.Vector.magnitude(v);
if (dist > reach) {
this.stop();
}
if (this.stopped) {
this.hook.position = this.tipPosition();
}
}
render(
graphics: Phaser.GameObjects.Graphics, center: Matter.Vector, mult: number
) {
const vectors = this.segments.map((s, i) => this.segmentTip(i));
const points = [center, ...vectors].map(({ x, y }) => {
return new Phaser.Math.Vector2(x, y);
});
const spline = new Phaser.Curves.Spline(points);
graphics.lineStyle(this.segmentRadius * 2, color.multiply(orange, mult));
spline.draw(graphics);
vectors.forEach(({ x, y }) => {
graphics.fillCircle(x, y, this.segmentRadius);
})
}
}
// in ms
const jumpLength = 1000;
interface OctopusConfig {
x: number;
y: number;
headRadius: number;
numArms: number;
segmentLength: number;
segmentRadius: number;
segmentsPerArm: number;
}
export class Octopus {
headRadius: number;
reach: number;
comp: Matter.Composite;
head: Matter.Body;
arms: Arm[];
hook: Matter.Body;
spring: Matter.Constraint;
goal: Matter.Vector;
cooldown: number;
jumpCooldown: number;
jumpDirection: Matter.Vector;
armOrder: number[];
brightness: number;
constructor(config: OctopusConfig) {
this.comp = Matter.Composite.create();
const {
x, y,
headRadius,
numArms,
segmentLength,
segmentRadius,
segmentsPerArm,
} = config;
this.headRadius = headRadius;
this.reach = (segmentLength - 2 * segmentRadius) * segmentsPerArm;
const group = Matter.Body.nextGroup(true);
const collisionFilter = {
group,
mask: ~0,
category: 1,
};
this.head = Matter.Bodies.circle(x, y, headRadius, { collisionFilter });
this.arms = _.times(numArms, () => new Arm({
x, y: y - 30,
numSegments: segmentsPerArm,
segmentLength,
segmentRadius,
collisionFilter,
}));
const constraints = this.arms.map(arm => {
const offset = -1 * (segmentLength / 2.0 - segmentRadius);
return Matter.Constraint.create({
bodyA: this.head,
bodyB: arm.segments[0],
pointB: { x: offset, y: 0 },
stiffness: 1,
length: 0,
});
});
Matter.Composite.add(this.comp, this.head);
// @ts-ignore: Argument of type 'Composite[]' is not assignable ...
Matter.Composite.add(this.comp, this.arms.map(arm => arm.comp));
// @ts-ignore: Argument of type 'Constraint[]' is not assignable ...
Matter.Composite.add(this.comp, constraints);
this.hook = Matter.Bodies.rectangle(x, y, 1, 1, {
isStatic: true,
collisionFilter: { ...collisionFilter, mask: 0 }
});
this.spring = Matter.Constraint.create({
bodyA: this.head,
bodyB: this.hook,
stiffness: 0.01,
length: 0,
});
Matter.Composite.add(this.comp, this.hook);
Matter.Composite.add(this.comp, this.spring);
this.goal = null;
this.cooldown = 0;
this.jumpCooldown = 0;
this.jumpDirection = { x: 0, y: 0 };
this.replenishArmOrder();
this.brightness = 0;
}
replenishArmOrder() {
this.armOrder = this.arms.map((arm, i) => i);
}
maybeReachable(bodies: Matter.Body[]): Matter.Body[] {
const octobodies = new Set(Matter.Composite.allBodies(this.comp));
// haha see what I did there?
const relevantBodies = bodies.filter(b => !octobodies.has(b));
const center = this.head.position;
const reachBody = Matter.Bodies.circle(center.x, center.y, this.reach);
return Matter.Query.region(relevantBodies, reachBody.bounds);
}
isGrounded(): boolean {
return this.arms.some(arm => !(arm.stopped));
}
jump(toward: Matter.Vector) {
if (this.isGrounded() && this.jumpCooldown <= 0) {
this.jumpCooldown = jumpLength;
this.arms.forEach(arm => arm.stop());
const rawDiff = Matter.Vector.sub(toward, this.head.position);
const normalized = Matter.Vector.normalise(rawDiff);
this.jumpDirection = Matter.Vector.mult(normalized, 200);
}
}
moveArm(reachable: Matter.Body[], toMove: Arm, tries: number) {
const start = this.head.position;
const angles = _.times(tries, () => random.weighted(-Math.PI/2, Math.PI/2));
const points = angles.map(angle => {
const v1 = Matter.Vector.sub(this.goal, start);
const v2 = Matter.Vector.rotate(v1, angle);
const end2 = Matter.Vector.add(start, v2);
const ray = Matter.Query.ray(reachable, start, end2);
const cast = raycast(ray.map(obj => obj.body), start, end2);
return cast.map(raycol => raycol.point)[0];
}).filter(point => {
if (!point) {
return false;
}
const dist = Matter.Vector.magnitude(Matter.Vector.sub(point, start));
if (dist > this.reach) {
return false;
}
return true;
});
if (points.length > 0) {
const point = points.reduce((acc, cur) => {
const d1 = Matter.Vector.magnitude(Matter.Vector.sub(acc, this.goal));
const d2 = Matter.Vector.magnitude(Matter.Vector.sub(cur, this.goal));
return d2 < d1 ? cur : acc;
}, points[0]);
toMove.move(point);
}
}
update(time: number, delta: number, world: Matter.World) {
this.cooldown = Math.max(0, this.cooldown - delta);
this.jumpCooldown = Math.max(0, this.jumpCooldown - delta);
if (this.isGrounded()) {
const total = this.arms.reduce((acc, cur) => {
return Matter.Vector.add(acc, cur.tipPosition());
}, { x: 0, y: 0 });
const centroid = Matter.Vector.div(total, this.arms.length);
if (this.goal) {
const dir = Matter.Vector.sub(this.goal, this.head.position);
const normie = Matter.Vector.normalise(dir); // yes I'm fun at parties
const lean = Matter.Vector.mult(normie, 3*this.headRadius);
this.hook.position = Matter.Vector.add(centroid, lean);
} else {
this.hook.position = centroid;
}
} else {
this.hook.position = Matter.Vector.add(
this.head.position,
Matter.Vector.mult(
this.jumpDirection,
(1.0/jumpLength)*Math.max(0, this.jumpCooldown - jumpLength*0.5)
),
);
}
const bodies = Matter.Composite.allBodies(world);
const reachable = this.maybeReachable(bodies);
if (this.goal) {
this.arms.filter(arm => arm.stopped).forEach(arm => this.moveArm(reachable, arm, 1));
if (this.cooldown <= 0) {
this.cooldown = 250;
const bestArm = this.arms[this.armOrder[0]];
this.armOrder.shift();
if (this.armOrder.length === 0) {
this.replenishArmOrder();
}
this.moveArm(reachable, bestArm, 100);
}
}
this.arms.forEach(arm => arm.update(this.head.position, this.reach));
}
render(graphics: Phaser.GameObjects.Graphics, progress: Progress) {
graphics.fillStyle(color.multiply(orange, this.brightness));
this.arms.forEach(arm => arm.render(graphics, this.head.position, this.brightness));
const center = this.head.position;
const radius = this.headRadius;
graphics.fillCircle(center.x, center.y, radius);
graphics.fillStyle(color.multiply(0xffffff, this.brightness));
if (progress === 'sleeping') {
graphics.fillRoundedRect(center.x - radius / 3.0 - radius / 5.0, center.y, radius / 3.0, radius / 10.0, radius / 20.0);
graphics.fillRoundedRect(center.x + radius / 3.0 - radius / 5.0, center.y, radius / 3.0, radius / 10.0, radius / 20.0);
} else {
graphics.fillEllipse(center.x - radius / 3.0, center.y, radius / 5.0, radius / 2.0);
graphics.fillEllipse(center.x + radius / 3.0, center.y, radius / 5.0, radius / 2.0);
}
}
}
|
d58e1dcb7d30f89a9de142977c1d7b74d04ecc35 | TypeScript | uu-cubitt/graph | /src/NodeElement.ts | 2.953125 | 3 | import {ElementType} from "./ElementType";
import {AbstractElement} from "./AbstractElement";
import {Graph} from "./Graph";
/**
* Element representing a true higher-level Node in the graph, see documentation for more information
*/
export class NodeElement extends AbstractElement {
/**
* @inheritdoc
*/
public getType(): ElementType {
return ElementType.Node;
}
/**
* @inheritdoc
*/
public delete(graph: Graph): void {
/* Delete of this node, should remove all
* connectors connected to this element.
*
*/
let connectors = this.getChildConnectorNeighbours();
let models = this.getParentModelNeighbours();
for (let conId of connectors) {
let connector = graph.getElement(conId);
connector.delete(graph);
}
for (let modelId of models) {
let model = graph.getElement(modelId);
model.unlinkChildNodeNeighbour(this.id); // Remove the reference to this class
}
// Remove child models (if any)
let childModels = this.getChildModelNeighbours();
for (let childModelId of childModels) {
let childModel = graph.getElement(childModelId);
childModel.delete(graph);
}
this.remove(graph);
}
}
|
d170fe06bad5e981cc59c4214a17ef04cdb9d926 | TypeScript | MichalKoszalka/front-end-development-ug | /lab6-homework/src/Dog.ts | 3.46875 | 3 | import { Breed } from "./Breed";
export class Dog {
public startWeight: number;
public exp: number;
public intelligence: number;
constructor(public name: string, public breed: Breed, public weight: number, public height: number) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.startWeight = weight;
this.height = height;
this.exp = 0;
this.intelligence = 1;
}
public introduce () {
console.log(`I am ${this.name}`);
}
public bark() {
console.log("wow wow");
}
public feed() {
console.log("yummy");
this.weight++
}
public canRun() {
return this.weight < 2 * this.startWeight;
}
public run() {
if (this.weight >= (2 * this.startWeight)) {
this.bark();
} else {
console.log("running");
if(this.weight > this.startWeight) {
this.weight--;
}
}
}
public walk() {
console.log("walking");
if(this.weight > this.startWeight) {
this.weight--;
}
}
public train() {
this.exp = this.exp + (1 * this.intelligence);
}
public sit() {
if(this.exp > 0) {
console.log("siting");
} else {
this.bark();
}
}
public canDoTheTrick() {
return this.exp > 5;
}
public doTheTrick() {
if(this.exp > 5) {
console.log("doing trick")
} else {
this.bark();
}
}
} |
10642537719cc3b44034f33b2716892f391aa1b8 | TypeScript | lineCode/redis-om-node | /spec/functional/core/update-hash.spec.ts | 2.703125 | 3 | import { fetchHashKeys, fetchHashFields, keyExists } from '../helpers/redis-helper';
import { HashEntity, AN_ENTITY, createHashEntitySchema, loadTestHash, ANOTHER_ENTITY } from '../helpers/data-helper';
import Client from '../../../lib/client';
import Schema from '../../../lib/schema/schema';
import Repository from '../../../lib/repository/repository';
describe("update hash", () => {
let client: Client;
let repository: Repository<HashEntity>;
let schema: Schema<HashEntity>;
let entity: HashEntity;
let entityId: string;
let entityKey: string;
beforeAll(async () => {
client = new Client();
await client.open();
schema = createHashEntitySchema();
repository = client.fetchRepository<HashEntity>(schema);
});
beforeEach(async () => {
await client.execute(['FLUSHALL']);
await loadTestHash(client, 'HashEntity:full', AN_ENTITY);
});
afterAll(async () => await client.close());
describe("when updating a fully populated entity to redis", () => {
beforeEach(async () => {
entity = await repository.fetch('full');
entity.aString = ANOTHER_ENTITY.aString;
entity.anotherString = ANOTHER_ENTITY.anotherString;
entity.aFullTextString = ANOTHER_ENTITY.aFullTextString;
entity.anotherFullTextString = ANOTHER_ENTITY.anotherFullTextString;
entity.aNumber = ANOTHER_ENTITY.aNumber;
entity.anotherNumber = ANOTHER_ENTITY.anotherNumber;
entity.aBoolean = ANOTHER_ENTITY.aBoolean;
entity.anotherBoolean = ANOTHER_ENTITY.anotherBoolean;
entity.anArray = ANOTHER_ENTITY.anArray;
entity.anotherArray = ANOTHER_ENTITY.anotherArray;
entityId = await repository.save(entity);
entityKey = `HashEntity:full`;
});
it("returns the expected entity id", () =>{
expect(entityId).toBe('full');
});
it("preserves the expected fields in a hash", async () => {
let fields = await fetchHashKeys(client, entityKey);
expect(fields).toHaveLength(10);
expect(fields).toEqual(expect.arrayContaining([ 'aString', 'anotherString',
'aFullTextString', 'anotherFullTextString', 'aNumber', 'anotherNumber',
'aBoolean', 'anotherBoolean', 'anArray', 'anotherArray' ]));
});
it("updates the expected fields in the hash", async () => {
let values = await fetchHashFields(client, entityKey, 'aString', 'anotherString',
'aFullTextString', 'anotherFullTextString', 'aNumber', 'anotherNumber',
'aBoolean', 'anotherBoolean', 'anArray', 'anotherArray');
expect(values).toEqual([
ANOTHER_ENTITY.aString,
ANOTHER_ENTITY.anotherString,
ANOTHER_ENTITY.aFullTextString,
ANOTHER_ENTITY.anotherFullTextString,
ANOTHER_ENTITY.aNumber?.toString(),
ANOTHER_ENTITY.anotherNumber?.toString(),
ANOTHER_ENTITY.aBoolean ? '1' : '0',
ANOTHER_ENTITY.anotherBoolean ? '1' : '0',
ANOTHER_ENTITY.anArray?.join('|'),
ANOTHER_ENTITY.anotherArray?.join('|')
]);
});
});
describe("when updating a partially populated entity to redis", () => {
beforeEach(async () => {
entity = await repository.fetch('full');
entity.aString = ANOTHER_ENTITY.aString;
entity.anotherString = null;
entity.aFullTextString = ANOTHER_ENTITY.aFullTextString;
entity.anotherFullTextString = null;
entity.aNumber = ANOTHER_ENTITY.aNumber;
entity.anotherNumber = null;
entity.aBoolean = ANOTHER_ENTITY.aBoolean;
entity.anotherBoolean = null;
entity.anArray = ANOTHER_ENTITY.anArray;
entity.anotherArray = null;
entityId = await repository.save(entity);
entityKey = `HashEntity:full`;
});
it("returns the expected entity id", () =>{
expect(entityId).toBe('full');
});
it("removes the nulled fields from the hash", async () => {
let fields = await fetchHashKeys(client, entityKey);
expect(fields).toHaveLength(5);
expect(fields).toEqual(expect.arrayContaining([ 'aString', 'aFullTextString', 'aNumber', 'aBoolean', 'anArray' ]));
});
it("updates the expected fields in the hash", async () => {
let values = await fetchHashFields(client, entityKey, 'aString', 'anotherString',
'aFullTextString', 'anotherFullTextString', 'aNumber', 'anotherNumber',
'aBoolean', 'anotherBoolean', 'anArray', 'anotherArray');
expect(values).toEqual([
ANOTHER_ENTITY.aString, null,
ANOTHER_ENTITY.aFullTextString, null,
ANOTHER_ENTITY.aNumber?.toString(), null,
ANOTHER_ENTITY.aBoolean ? '1' : '0', null,
ANOTHER_ENTITY.anArray?.join('|'), null
]);
});
});
describe("when updating an empty entity to redis", () => {
beforeEach(async () => {
entity = await repository.fetch('full');
entity.aString = null;
entity.anotherString = null;
entity.aFullTextString = null;
entity.anotherFullTextString = null;
entity.aNumber = null;
entity.anotherNumber = null;
entity.aBoolean = null;
entity.anotherBoolean = null;
entity.anArray = null;
entity.anotherArray = null;
entityId = await repository.save(entity);
entityKey = `HashEntity:full`;
});
it("returns the expected entity id", () =>{
expect(entityId).toBe('full');
});
it("removes all the fields in a hash", async () => {
let fields = await fetchHashKeys(client, entityKey);
expect(fields).toHaveLength(0);
});
it("removes all the values from the hash", async () => {
let values = await fetchHashFields(client, entityKey, 'aString', 'anotherString',
'aFullTextString', 'anotherFullTextString', 'aNumber', 'anotherNumber',
'aBoolean', 'anotherBoolean', 'anArray', 'anotherArray');
expect(values).toEqual([ null, null, null, null, null, null, null, null, null, null ]);
});
it("removes the entire hash", async () => {
let exists = await keyExists(client, entityKey);
expect(exists).toBe(false);
});
});
});
|
a683ac2a6b8b83e8ef291f14cc33dac980284c59 | TypeScript | malufell/react-avancado-client | /src/components/Menu/styles.ts | 2.609375 | 3 | import styled, { css } from 'styled-components'
import media from 'styled-media-query'
export const Wrapper = styled.menu`
${({ theme }) => css`
display: flex;
align-items: center;
padding: ${theme.spacings.small} 0;
position: relative; //isso é pra logo ficar absoluta em relação ao menu
`}
`
export const LogoWrapper = styled.div`
${media.lessThan('medium')` //será aplicado só no mobile
position: absolute; //deixar a logo fixada no lugar
left: 50%; //mover 50% a esquerda da div
transform: translateX(-50%); //indica que será alinhado na metade do próprio tamanho da logo
`}
`
export const IconWrapper = styled.div`
${({ theme }) => css`
color: ${theme.colors.white};
cursor: pointer;
width: 2.4rem;
height: 2.4rem;
`}
`
//para os dois ícones que ficam no canto direito
export const MenuGroup = styled.div`
${({ theme }) => css`
display: flex; //deixa os dois ícones lado a lado
flex-grow: 1; //faz o icone ocupar o espaço máximo que tiver
justify-content: flex-end; //alinha no final da div
align-items: center;
//os ícones são div
> div {
margin-left: ${theme.spacings.xsmall}; //dá um espaço entre os ícones
}
`}
`
export const MenuNav = styled.div`
${({ theme }) => css`
${media.greaterThan('medium')`
margin-left: ${theme.spacings.small};
`}
`}
`
export const MenuLink = styled.a`
${({ theme }) => css`
position: relative;
color: ${theme.colors.white};
font-size: ${theme.font.sizes.medium};
margin: 0.3rem ${theme.spacings.small} 0;
text-decoration: none;
text-align: center;
&:hover {
//sublinhado que fica embaixo do elemento quando passa o mouse
&::after {
content: '';
position: absolute;
display: block;
height: 0.3rem;
background-color: ${theme.colors.primary};
animation: hoverAnimation 0.2s forwards;
}
@keyframes hoverAnimation {
from {
width: 0;
left: 50%;
}
to {
width: 100%;
left: 0;
}
}
}
`}
`
type MenuFullProps = {
isOpen: boolean
}
export const MenuFull = styled.nav<MenuFullProps>`
${({ theme, isOpen }) => css`
display: flex;
flex-direction: column; //deixa toda info do menu em uma coluna
justify-content: space-between;
background: ${theme.colors.white};
position: fixed;
z-index: ${theme.layers.menu};
top: 0; //borda
bottom: 0; //borda
left: 0; //borda
right: 0; //borda
height: 100vh; //pra ter a altura da tela inteira
overflow: hidden; //pra não ter scroll no próprio menu
transition: opacity ${theme.transition.default}; //transição suave da aparição do menu
opacity: ${isOpen ? 1 : 0}; //opacidade zero esconde o menu da tela
//se o menu estiver aberto, poderei clicar
pointer-events: ${isOpen ? 'all' : 'none'};
//svg corresponde ao icone "fechar" do menu
//pega o primeiro filho svg do componente (se tiver outro não pega)
> svg {
position: absolute;
top: 0;
right: 0;
margin: ${theme.spacings.xsmall};
cursor: pointer;
width: 2.4rem;
height: 2.4rem;
}
//é onde está os links de navegação do menu ('home' e 'explore')
${MenuNav} {
display: flex;
align-items: center;
justify-content: center;
flex: 1;
flex-direction: column;
}
//estiliza os links do menu que estão dentro do menu full
//(se estiver na versão desktop, está fora do menu full e não pega essa formatação)
${MenuLink} {
color: ${theme.colors.black};
font-weight: ${theme.font.bold};
font-size: ${theme.font.sizes.xlarge};
margin-bottom: ${theme.spacings.small};
//animação que sobe e desce os elementos quando abre o menu
transform: ${isOpen ? 'translateY(0)' : 'translateY(3rem)'};
transition: transform ${theme.transition.default};
}
//animação que sobe e desce os elementos quando abre o menu
${RegisterBox} {
transform: ${isOpen ? 'translateY(0)' : 'translateY(3rem)'};
transition: transform ${theme.transition.default};
}
`}
`
//div que contém opção de login ou cadastro
export const RegisterBox = styled.div`
${({ theme }) => css`
display: flex;
flex-direction: column;
align-items: center;
padding: 0 ${theme.spacings.xlarge} ${theme.spacings.xlarge};
//esse span é o texto "or" entre login e cadastre-se
> span {
display: block;
margin: ${theme.spacings.xxsmall} 0;
font-size: ${theme.font.sizes.xsmall};
}
`}
`
//estilo do link "sign up"
export const CreateAccount = styled.a`
${({ theme }) => css`
text-decoration: none;
color: ${theme.colors.primary};
border-bottom: 0.2rem solid ${theme.colors.primary};
`}
`
|
7e584bc05171357045a96f0a9f883280a5ff657b | TypeScript | blindmonkey/programming-challenge | /src/renderable/shapes/pixi-rect.ts | 3.359375 | 3 | /**
* The rendering parameters of a PIXIRect.
*/
type PIXIRectRenderingParameters = {
// The width and height of the rectangle.
width: number, height: number,
// The radius of the corners, or 0.
cornerRadius: number,
// The fill color as a number. i.e. 0xFF0000 for red.
fillColor: number,
// The stroke color as a number.
strokeColor: number,
// The line width of the outline, or 0.
lineWidth: number,
};
/**
* A basic rectangle that is renderable to PIXI (as opposed to a
* PIXI.Rectangle), optionally with rounded corners.
*/
export class PIXIRect extends PIXI.Graphics {
private options: PIXIRectRenderingParameters;
constructor(width: number, height: number,
options: {cornerRadius?: number, fillColor?: number,
lineWidth?: number, strokeColor?: number} = null) {
super();
this.options = {
cornerRadius: options && (
options.cornerRadius == null ? 5 : options.cornerRadius),
fillColor: options && options.fillColor || 0,
lineWidth: options && options.lineWidth || 0,
strokeColor: options && options.strokeColor,
width,
height,
};
this.updateGeometry();
}
/**
* Set new parameters for the fill and stroke colors.
*/
public setColors(colors: {fill?: number, stroke?: number}) {
if (colors.fill != null) {
this.options.fillColor = colors.fill;
}
if (colors.stroke != null) {
this.options.strokeColor = colors.stroke;
}
this.updateGeometry();
}
/**
* Updates the path associated with this PIXI.Graphics object to accurately
* represent the rectangle detailed by the options.
*/
private updateGeometry() {
let options = this.options;
let width = options.width;
let height = options.height;
let radius = options.cornerRadius;
/**
* Below is a diagram of the order in which the rectangle is rendered.
* The numbers coincide with comments on the lines below that are used
* to construct the geometry for the rectangle.
*
* 8/0 --------------- 1
* / \
* 7 2
* | |
* | |
* | |
* | |
* 6 3
* \ /
* 5 --------------- 4
*/
// NOTE: The arcs are sometimes imprecise when rendered, and having a
// lineTo command after them helps make them look better. These lineTo
// commands will be numbered as N.5, where N is the number of the arc.
this.clear();
this.beginFill(options.fillColor);
this.lineStyle(options.lineWidth, options.strokeColor);
this.moveTo(radius, 0); // 0
this.lineTo(width - radius, 0); // 1
if (radius > 0) {
// (2) Top-right corner.
this.arc(width - radius, radius,
radius, Math.PI / 2 * 3, Math.PI * 2);
}
this.lineTo(width, radius); // 2.5
this.lineTo(width, height - radius); // 3
if (radius > 0) {
// (4) Bottom-right corner.
this.arc(width - radius, height - radius,
radius, 0, Math.PI / 2);
}
this.lineTo(width - radius, height); // 4.5
this.lineTo(radius, height); // 5
if (radius > 0) {
// (6) Bottom-left corner.
this.arc(radius, height - radius,
radius, Math.PI / 2, Math.PI);
}
this.lineTo(0, height - radius); // 6.5
this.lineTo(0, radius); // 7
if (radius > 0) {
// (8) Top-left corner.
this.arc(radius, radius,
radius, Math.PI, Math.PI / 2 * 3);
}
}
}
|
de4b33f07144f4d947f62b948a31c3a75491f29f | TypeScript | luccasbarros/LAMA | /src/controller/BandController.ts | 2.71875 | 3 | import { Request, Response } from "express";
import { BandInputDTO } from "../model/Band";
import BandBusiness from "../business/BandBusiness";
import BandDatabase from "../data/BandDatabase";
class UserController {
public createBand = async (req: Request, res: Response) => {
try {
const token: string = req.headers.authorization as string;
const input: BandInputDTO = {
name: req.body.name,
musicGenre: req.body.musicGenre,
responsible: req.body.responsible,
};
await BandBusiness.createBand(input, token);
res.status(201).send({ message: "Band created sucessfully"});
} catch (error) {
res.status(400).send({
message: error.message || error.sqlMessage,
});
}
};
public getBandById = async(req:Request, res:Response):Promise<any> => {
try {
const token:string = req.headers.authorization as string
const input = {
id: req.params.id
}
const band = await BandBusiness.getBandById(input, token)
res.status(200).send({band: band})
} catch(error) {
res.status(400).send({message: error.message || error.sqlMessage})
}
}
}
export default new UserController();
|
291d6425e0a59f18486711f1ce617b95f7b627fb | TypeScript | esimpsontheartist/gp-ui | /src/hooks/useOperatorTrades.ts | 2.65625 | 3 | import { getTrades, Order, Trade } from 'api/operator'
import { useCallback, useEffect, useState } from 'react'
import { useNetworkId } from 'state/network'
import { Network } from 'types'
import { transformTrade } from 'utils'
type Params = {
owner?: string
orderId?: string
}
type Result = {
trades: Trade[]
error: string
isLoading: boolean
}
/**
* Fetches trades for given filters
* When no filter is given, fetches all trades for current network
*/
export function useTrades(params: Params): Result {
const { owner, orderId } = params
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState('')
const [trades, setTrades] = useState<Trade[]>([])
// Here we assume that we are already in the right network
// contrary to useOrder hook, where it searches all networks for a given orderId
const networkId = useNetworkId()
const fetchTrades = useCallback(async (networkId: Network, owner?: string, orderId?: string): Promise<void> => {
setIsLoading(true)
setError('')
try {
const trades = await getTrades({ networkId, owner, orderId })
// TODO: fetch buy/sellToken objects
setTrades(trades.map((trade) => transformTrade(trade)))
} catch (e) {
const msg = `Failed to fetch trades`
console.error(msg, e)
setError(msg)
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => {
if (!networkId) {
return
}
fetchTrades(networkId, owner, orderId)
}, [fetchTrades, networkId, orderId, owner])
return { trades, error, isLoading }
}
/**
* Fetches trades for given order
*/
export function useOrderTrades(order: Order | null): Result {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState('')
const [trades, setTrades] = useState<Trade[]>([])
// Here we assume that we are already in the right network
// contrary to useOrder hook, where it searches all networks for a given orderId
const networkId = useNetworkId()
const fetchTrades = useCallback(async (networkId: Network, order: Order): Promise<void> => {
setIsLoading(true)
setError('')
const { uid: orderId, buyToken, sellToken } = order
try {
const trades = await getTrades({ networkId, orderId })
setTrades(trades.map((trade) => ({ ...transformTrade(trade), buyToken, sellToken })))
} catch (e) {
const msg = `Failed to fetch trades`
console.error(msg, e)
setError(msg)
} finally {
setIsLoading(false)
}
}, [])
const executedSellAmount = order?.executedSellAmount.toString()
const executedBuyAmount = order?.executedBuyAmount.toString()
useEffect(() => {
if (!networkId || !order?.uid) {
return
}
fetchTrades(networkId, order)
// Depending on order UID to avoid re-fetching when obj changes but ID remains the same
// Depending on `executedBuy/SellAmount`s string to force a refetch when there are new trades
// using the string version because hooks are bad at detecting Object changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetchTrades, networkId, order?.uid, executedSellAmount, executedBuyAmount])
return { trades, error, isLoading }
}
|
426a6cb6ab429cc62cd95847e593a4cd74d63e89 | TypeScript | RedBlazerFlame/conways-game-of-life | /scripts/map-to-grid-converter.ts | 2.9375 | 3 | import { CellularAutomatonTypes, String2d } from "./cellular-automaton.js";
import { Grid2d } from "./grid.js";
import { CompositionState, CompositionStateArray } from "./state.js";
import { Vector } from "./vector.js";
export const convertMapToGrid2d = (gridState: CellularAutomatonTypes.State): Grid2d => {
let gridStateVectorKeys: Array<Vector<number>> = [...gridState.keys()].map(i => Vector.from(JSON.parse(i)))
let minX = Math.min(...gridStateVectorKeys.map(i => i.entries[0]));
let maxX = Math.max(...gridStateVectorKeys.map(i => i.entries[0]));
let minY = Math.min(...gridStateVectorKeys.map(i => i.entries[1]));
let maxY = Math.max(...gridStateVectorKeys.map(i => i.entries[1]));
let xLength = maxX - minX + 1;
let yLength = maxY - minY + 1;
let result: Grid2d = [...Array(yLength)].map((_, y) => [...Array(xLength)]);
for(let y = minY; y <= maxY; y++) {
for(let x = minX; x <= maxX; x++) {
let newCoords = JSON.stringify([x, y]) as String2d;
let cellValue = gridState.get(newCoords) ?? 0;
result[y - minY][x - minX] = cellValue;
}
}
return result;
}
export const convertStateArrayToMap = (gridState: CompositionStateArray): CellularAutomatonTypes.State => {
return (new CompositionState(gridState)).compile();
}
export const convertStateArrayToGrid2d = (gridState: CompositionStateArray): Grid2d => {
return convertMapToGrid2d((new CompositionState(gridState)).compile());
} |
95504d9ce532f30e664e6470256e5b0de32d0cd2 | TypeScript | mhshifat/graphql-faker | /src/Base.ts | 2.546875 | 3 | import * as path from "path";
import { log } from "./fake-schema/utils";
export class Base {
config: any;
log: (...args) => void;
constructor(config) {
this.config = config;
if (this.isEnabled("logging")) {
config.log = config.log || log;
}
this.log = config.log;
}
error(msg, data?) {
data ? console.error(msg, data) : console.error(msg);
throw new Error(msg);
}
isEnabled(name) {
const enabled = this.config.enable || {};
return enabled[name];
}
get rootPath() {
return path.join(__dirname, "..");
}
validateFunction({ method, functionName, func, data, error }) {
if (typeof func !== "function") {
error(`${method}: missing or invalid ${functionName} function`, {
[functionName]: func,
...data
});
}
}
}
|
a3117fb6f87d5ccef3d7682cce1725e65ff5c80a | TypeScript | dkds/assignment-1-auto-club | /frontend/src/app/core/model/car-make.model.ts | 3.140625 | 3 | export class CarMake {
static fromObject(carMake: any): CarMake {
if (!carMake.id || !carMake.name) {
throw new Error("Invalid object, needs id and name");
}
const obj = new CarMake(carMake.name);
obj.id = carMake.id
return obj;
}
id: number = 0;
constructor(public name: string) { }
} |
ec4c261a3e07b4d28d9674bdd525c9d07234afe1 | TypeScript | awbraunstein/segmented-searchbox | /src/index.ts | 3.453125 | 3 | interface LookupValue {
color: string;
data: string;
ignoreCase: boolean;
}
interface ReverseLookupValue {
color: string;
text: string;
}
class Searchbox {
private _el: HTMLInputElement;
private _lookup: { [text: string]: LookupValue; } = {};
// This is the container that will contain our searchbox.
private _container!: HTMLElement;
// This is the searchbox that the user will actually interact with.
private _sb!: HTMLElement;
// This is the dropdown that will show the possible values the user can input.
private _dropDown!: HTMLElement;
// The current focus in the dropdown. -1 indicates that there is no focus.
private _currentFocus = -1;
// Validates the config and updates any optional fields with their default
// values. Returns false if the config isn't valid.
private validateConfig(config: SearchboxConfig): boolean {
let seenTextValues: { [text: string]: boolean; } = {};
for (let kind of config.valueKinds) {
if (kind.ignoreCase === undefined) {
kind.ignoreCase = true;
}
for (let value of kind.values) {
if (value.text === undefined) {
value.text = value.data;
}
// If we have already seen this value, then the config is invalid.
if (seenTextValues[value.text]) {
return false;
}
seenTextValues[value.text] = true;
}
}
return true;
}
private getCurrentSbText(): string {
for (let i = 0; i < this._sb.childNodes.length; i++) {
let node = this._sb.childNodes[i];
// If the node is a textnode, then return the value.
if (node.nodeType === 3) {
return node.textContent || '';
}
}
// If we didn't find one, then return the empty string.
return '';
}
private updateInputValue() {
let vals: Array<string> = [];
let spans = this._sb.getElementsByTagName('span');
for (let i = 0; i < spans.length; i++) {
let val = spans[i].dataset['value']
if (val) {
vals.push(val);
}
}
this._el.value = vals.join(' ');
}
// If there is no content at the end of the searchbox, we can end up with the
// caret outside of the box, which looks very weird. This method makes sure
// that there is a text node at the end of the searchbox with a nbsp in it. If
// there is no text at all, it works fine though.
private ensureSbHasContent() {
let len = this._sb.childNodes.length;
if (len != 0 && this._sb.childNodes[len - 1].nodeType != 3) {
// String.fromCharCode(160) gets around a bug where webpack/ts-loader
// messes with the nbsp literal.
let node = document.createTextNode(String.fromCharCode(160));
this._sb.appendChild(node);
this._sb.focus()
document.getSelection()!.collapse(node, 1);
}
}
private createSpanForSb(text: string, color: string, value: string):
HTMLSpanElement {
var span = document.createElement('span');
span.classList.add('segmented-searchbox-valid-item')
span.textContent = text;
span.style.backgroundColor = color;
span.dataset['value'] = value;
span.contentEditable = 'false';
return span;
}
// Inserts a valid value into the searchbox. This makes that value uneditable
// and colors it appropriately.
private insertValueIntoSb(el: HTMLElement) {
for (let i = 0; i < this._sb.childNodes.length; i++) {
let node = this._sb.childNodes[i];
// If the node is a textnode, then we should replace it.
if (node.nodeType === 3) {
var replacement = this.createSpanForSb(el.dataset['text'] || '',
el.dataset['color'] || '',
el.dataset['value'] || '');
node.parentNode!.insertBefore(replacement, node);
node.parentNode!.removeChild(node);
this.ensureSbHasContent();
this.updateInputValue();
return;
}
}
}
// If a node that isn't the last node is the value, return false.
private isInputValueAtEnd(): boolean {
for (let i = 0; i < this._sb.childNodes.length - 1; i++) {
if (this._sb.childNodes[i].nodeType === 3) {
return false;
}
}
return true;
}
private onInput(_: Event) {
let val = this.getCurrentSbText();
// If the user hit delete when in the sentinel textnode, we would end up
// with and empty text node. In this case we should remove the last child
// that's a span, if there is one and then call ensureSbHasContent().
if (this.isInputValueAtEnd() && !val) {
for (let i = this._sb.childNodes.length - 1; i >= 0; i--) {
let node = this._sb.childNodes[i];
if (node.nodeName == 'SPAN') {
node.parentNode!.removeChild(node);
break;
}
}
this.ensureSbHasContent();
}
this.updateInputValue();
// Close any already open lists of autocompleted values.
this.closeList();
// If the val is the empty string, then we have nothing to do.
if (!val) {
return false;
}
// Everytime the user enters new text, we should reset the focus.
this._currentFocus = -1;
// Check to see which values match the current text value.
for (let possibleValue in this._lookup) {
let ourValue = val.trim();
let matchValue = possibleValue;
if (this._lookup[possibleValue].ignoreCase) {
ourValue = ourValue.toLowerCase();
matchValue = matchValue.toLowerCase();
}
if (ourValue && matchValue.indexOf(ourValue) > -1) {
// Create a div for each match.
let entry = document.createElement("div");
/*make the matching letters bold:*/
entry.dataset['text'] = possibleValue;
entry.dataset['value'] = this._lookup[possibleValue].data;
entry.dataset['color'] = this._lookup[possibleValue].color;
entry.innerText = possibleValue;
let that = this;
entry.addEventListener("click", function(_) {
// insert the value for the autocomplete text field:
that.insertValueIntoSb(entry);
that.closeList();
that._sb.focus();
});
this._dropDown.appendChild(entry);
}
}
this._dropDown.hidden = false;
}
private onKeydown(e: KeyboardEvent) {
let entries = this._dropDown.getElementsByTagName("div");
// If there are no entries, then don't do anything unless the event was
// enter. Then we should submit the form.
if (!entries.length) {
if (e.keyCode == 13) { // ENTER
e.preventDefault()
let parentForm = this._el.closest('form');
if (parentForm) {
parentForm.submit();
}
}
return;
}
if (e.keyCode == 40) { // DOWN
this._currentFocus++;
this.setActive(entries);
} else if (e.keyCode == 38) { // UP
this._currentFocus--;
this.setActive(entries);
} else if (e.keyCode == 13) { // ENTER
e.preventDefault();
if (this._currentFocus > -1) {
entries[this._currentFocus].click();
} else {
entries[0].click();
}
if (entries.length == 1) {
entries[0].click();
}
}
}
// Marks the element at this._currentFocus as active and deactivates all
// others.
private setActive(els: HTMLCollectionOf<HTMLDivElement>) {
// Remove the active tag on all items.
this.removeActive(els);
// If the focus has moved past the end of the list, it is in the text box
// and 0.
if (this._currentFocus >= els.length) {
this._currentFocus = 0;
}
// If the current focus is less than 0 (aka the user hit the up arrow in the
// text box, move the focus to the last element.
if (this._currentFocus < 0) {
this._currentFocus = (els.length - 1);
}
// Add the active class to the element in focus.
els[this._currentFocus].classList.add("autocomplete-active");
}
// Remove the active class from all the elements.
private removeActive(els: HTMLCollectionOf<HTMLDivElement>) {
/*a function to remove the "active" class from all autocomplete items:*/
for (let i = 0; i < els.length; i++) {
els[i].classList.remove("autocomplete-active");
}
}
// Closes the Autocomplete list.
private closeList() {
this._dropDown.hidden = true;
this._dropDown.innerHTML = '';
}
private setupSearchbox() {
// Perform necessary initial DOM manipulation. Hide the original input,
// create a container with an input and dropdown as children.
this._el.style.display = 'none';
this._container = document.createElement('div');
this._container.classList.add('segmented-searchbox-container');
this._sb = document.createElement('div');
this._sb.classList.add('segmented-searchbox-input');
this._container.appendChild(this._sb);
this._dropDown = document.createElement('div');
this._dropDown.classList.add('segmented-searchbox-dropdown');
this._container.appendChild(this._dropDown);
this._el.parentNode!.insertBefore(this._container, this._el.nextSibling);
this._sb.addEventListener('input', (e) => { this.onInput(e); });
this._sb.addEventListener('keydown', (e) => { this.onKeydown(e); });
}
// If the input has a value to start with, we should render that first.
private renderFromInputValue() {
let val = this._el.value;
if (!val) {
return;
}
// There may be collisions so we will pick the shortest text value.
let reverseLookup: { [value: string]: ReverseLookupValue; } = {};
for (let text in this._lookup) {
let lv = this._lookup[text];
// If the lookup value is already in the reverse lookup and the lenth of
// the text in the lookup value is less than length of the text we are
// trying to add, don't overwrite it.
if (lv.data in reverseLookup &&
reverseLookup[lv.data].text.length < text.length) {
continue
}
reverseLookup[lv.data] = {
color: lv.color,
text: text
};
}
let queryPieces = val.split(/\s+|([\(\)])/);
for (let piece of queryPieces) {
if (!piece) {
continue
}
if (!(piece in reverseLookup)) {
// This is an error.
console.log('Query part: ' + piece + ' is invalid.');
return;
}
let rl = reverseLookup[piece];
let span = this.createSpanForSb(rl.text, rl.color, piece);
this._sb.appendChild(span);
}
this.updateInputValue();
this.ensureSbHasContent();
}
private createLookup(config: SearchboxConfig): { [text: string]: LookupValue; } {
let lookup: { [text: string]: LookupValue; } = {};
for (let kind of config.valueKinds) {
for (let value of kind.values) {
lookup[value.text!] = {
color: kind.color,
data: value.data,
ignoreCase: kind.ignoreCase!
}
}
}
return lookup;
}
private fetchConfig(url: string) {
let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
this.setupWithConfig(xhr.response);
}
}
xhr.open("GET", url);
xhr.send()
}
private setupWithConfig(config: SearchboxConfig) {
if (!this.validateConfig(config)) {
throw new Error('Config contains duplicate values and is invalid.')
}
this._lookup = this.createLookup(config);
// Make the searchbox contenteditable.
this._sb.contentEditable = 'true';
this.renderFromInputValue();
}
public constructor(el: HTMLInputElement, config: SearchboxConfig | string) {
this._el = el;
this.setupSearchbox();
if (typeof config === 'string') {
this.fetchConfig(config);
} else {
this.setupWithConfig(config)
}
}
}
class SearchboxManager {
private static _instance: SearchboxManager;
private searchboxes: { [id: string]: Searchbox; } = {};
private constructor() { }
public static getInstance() {
if (!SearchboxManager._instance) {
SearchboxManager._instance = new SearchboxManager();
}
return SearchboxManager._instance;
}
public addSearchbox(el: HTMLInputElement, config: SearchboxConfig | string) {
if (!el.id) {
throw new Error('The provided element must have an id.')
}
if (el.tagName !== 'INPUT') {
throw new Error('The provided element must be of type input.')
}
this.searchboxes[el.id] = new Searchbox(el, config);
}
}
interface Value {
// The actual data of the value. This is what will be in the underlying textbox.
data: string;
// The human text that the user will enter/see. If empty, defaults to
// text. This value must be unique across the whole config.
text?: string;
}
interface ValueKind {
// The name for this kind.
name: string;
// The css color that this value kind will be set to.
color: string;
// The valid values for this kind.
values: ReadonlyArray<Value>;
// Whether or not the case of the values should be ignored. Defaults to true.
ignoreCase?: boolean;
}
interface SearchboxConfig {
// An array of the valid values that can be in the input.
valueKinds: ReadonlyArray<ValueKind>;
}
export function initSearchbox(el: HTMLInputElement, config: SearchboxConfig | string) {
SearchboxManager.getInstance().addSearchbox(el, config);
}
|
60985729cfbaf9a00e6a7155088cb8fb48eddf77 | TypeScript | Murreey/GuessTheMovieBot | /src/scores/ScoreFlairManager.ts | 2.84375 | 3 | import { Logger } from '../Logger'
import { RedditBot } from '../RedditBot'
import { ScoreManager } from '../types'
const thresholds: [number, string][] = [
[1, '#7EFF7B'], [5, '#68B4E7'], [10, '#FFE47B'],
[20, '#FFBC7B'], [50, '#7B9BFF'], [100, '#C07BFF'],
[200, '#FF7BD0'], [500, '#FF7B85'], [1000, '#FFDA7B'],
[2000, '#7B82FF'], [5000, '#FF25D3']
]
const chooseTextColour = (colour: string): 'light' | 'dark' => {
// Magic code that chooses light or dark text based on the background colour
// I'd hoped to be able to use one text colour for all of them (they all look okay on dark)
// But when actually displayed on reddit the design makes some a bit hard to read
const r = parseInt(colour.substring(1, 3), 16)
const g = parseInt(colour.substring(3, 5), 16)
const b = parseInt(colour.substring(5, 7), 16)
return (((r * 0.299) + (g * 0.587) + (b * 0.114)) > 186) ? 'dark' : 'light'
}
const getThresholdInfo = (points: number) => [...thresholds].reverse().find(threshold => threshold[0] <= points) || thresholds[0]
export default (bot: RedditBot, scoreManager?: ScoreManager) => {
const setPoints = async (user: string, amount: number): Promise<void> => {
if (bot.readOnly) return
if (amount < 0 || !amount) amount = 0
const [ threshold, colour ] = getThresholdInfo(amount)
const options = {
text: `${amount} points`,
css_class: `points points-${threshold || 1}`,
background_color: colour,
text_color: chooseTextColour(colour)
}
await bot.setUserFlair(user, options)
Logger.info(`Set ${user}'s points flair to ${amount} (${options.background_color})`)
}
return {
setPoints,
syncPoints: async (username: string) => {
if (!scoreManager) return
await setPoints(username, await scoreManager.getUserPoints(username))
}
}
} |
a7ed05561a7dc188ca84c48b5493de8e7500bec8 | TypeScript | tboothman/satisfactory_simulator | /src/frontend/items.ts | 3.265625 | 3 |
// A thing that goes on the grid
import {connect, Conveyor, Input, Merger, Output, Sink, Source, Splitter} from "../index";
export const enum GridItemType {
Source = "Source",
Sink = "Sink",
Merger = "Merger",
Splitter = "Splitter"
}
export class PlaceableItem {
public description: string = "";
private type: GridItemType;
private initialSettings: {};
constructor(description: string, type: GridItemType, initialSettings: {} = {}) {
this.description = description;
this.type = type;
this.initialSettings = initialSettings;
}
public createGridItem(x: number, y: number): GridItem {
return GridItem.create(x, y, this.type, this.initialSettings);
}
}
export interface SerialisedGridItem {
x: number
y: number
type: GridItemType
settings: object
}
export interface SerialisedConnection {
from: {x: number, y: number}
to: {x: number, y: number}
speed: number
}
export class GridItem {
protected description: string = "";
public x: number;
public y: number;
public model: Input|Output;
public settings: object|any;
public type: GridItemType;
public static create(x: number, y: number, type: GridItemType, settings: {}|any) {
let model: Input|Output|null = null;
switch (type) {
case GridItemType.Merger:
model = new Merger();
break;
case GridItemType.Sink:
model = new Sink(settings.speed);
break;
case GridItemType.Source:
model = new Source(settings.speed);
break;
case GridItemType.Splitter:
model = new Splitter();
break;
}
return new GridItem(type, x, y, model!, settings);
}
constructor(type: GridItemType, x: number, y: number, model: Input|Output, settings: {}) {
this.description = type;
this.x = x;
this.y = y;
this.model = model;
this.settings = settings;
this.type = type;
}
displayText(): string {
if (this.type === GridItemType.Source) {
return this.description + " " + this.settings.speed;
}
return this.description;
}
toJSON(): SerialisedGridItem {
return {
x: this.x,
y: this.y,
type: this.type,
settings: this.settings,
}
}
}
export class Connection {
public from: GridItem;
public to: GridItem;
public conveyor: Conveyor;
private maxSpeed: number;
constructor(from: GridItem, to: GridItem, conveyorSpeed = 450) {
this.from = from;
this.to = to;
// @todo gross ... fix the typing
this.conveyor = connect(this.from.model as Output, this.to.model as Input, conveyorSpeed);
this.maxSpeed = conveyorSpeed;
}
toJSON(): SerialisedConnection {
return {
from: {x: this.from.x, y: this.from.y},
to: {x: this.to.x, y: this.to.y},
speed: this.maxSpeed
}
}
} |
879b90c97a1ccb7124e2dd9e9d0de1d0c648c729 | TypeScript | Muhitori/Shop | /apps/server/src/database/migrations/20201220orderedProduct.migration.ts | 2.609375 | 3 | import {
MigrationInterface,
QueryRunner,
Table,
TableForeignKey
} from 'typeorm'
import { User } from '../../entities/user.entity'
// eslint-disable-next-line prettier/prettier
export class OrderedProductMigration20201220235639 implements MigrationInterface {
private tableName = 'OrderedProducts'
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: this.tableName,
columns: [
{
name: 'id',
type: 'uuid',
default: 'uuid_generate_v4()',
isPrimary: true
},
{
name: 'count',
type: 'int',
isNullable: false
},
{
name: 'orderId',
type: 'uuid',
isNullable: false
},
{
name: 'productId',
type: 'uuid',
isNullable: false
},
{
name: 'createdAt',
type: 'timestamptz',
default: 'now()',
isNullable: false
},
{
name: 'updatedAt',
type: 'timestamptz',
isNullable: true
},
{
name: 'deletedAt',
type: 'timestamptz',
isNullable: true
}
]
})
)
await queryRunner.createForeignKey(
this.tableName,
new TableForeignKey({
columnNames: ['orderId'],
referencedColumnNames: ['id'],
referencedTableName: 'Orders',
onDelete: 'CASCADE'
})
)
await queryRunner.createForeignKey(
this.tableName,
new TableForeignKey({
columnNames: ['productId'],
referencedColumnNames: ['id'],
referencedTableName: 'Products',
onDelete: 'CASCADE'
})
)
const [
user
]: User[] = await queryRunner.query(
'SELECT * FROM "Users" WHERE username = $1',
['admin']
)
const [
order
]: User[] = await queryRunner.query(
'SELECT * FROM "Orders" WHERE "userId" = $1',
[user.id]
)
const [
product
]: User[] = await queryRunner.query(
'SELECT * FROM "Products" WHERE name = $1',
['test']
)
await queryRunner.query(
`INSERT INTO "OrderedProducts" ("id", "count", "orderId", "productId")
VALUES (DEFAULT, $1, $2, $3);`,
[2, order.id, product.id]
)
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable(this.tableName)
}
}
|
fe8662c493ac30d0629021a43fbd6f2082dc23f3 | TypeScript | ebagos/typescript | /src/p010.ts | 3.84375 | 4 | /*
10以下の素数の和は 2 + 3 + 5 + 7 = 17 である.
200万以下の全ての素数の和を求めよ.
*/
function makePrimeList(num: number): number[] {
let result: number[] = [];
if (num < 2) {
return result;
}
let primeList: number[] = [];
for (let i: number = 0; i < num + 1; i++) {
primeList[i] = i;
}
primeList[1] = 0;
let numSqrt: number = Math.floor(Math.sqrt(num));
for (let i: number = 0; i < primeList.length; i++) {
let prime: number = primeList[i];
if (prime == 0) {
continue;
}
if (prime > numSqrt) {
break;
}
for (let nonPrime: number = prime * 2; nonPrime < num + 1; nonPrime += prime) {
primeList[nonPrime] = 0;
}
}
for (let i: number = 0; i < primeList.length; i++) {
let prime: number = primeList[i];
if (prime != 0) {
result.push(prime);
}
}
return result;
}
export function main() {
let max: number = 2000000;
let result: number[] = makePrimeList(max);
let sum: number = result.reduce(function(prev, current: number) {
return prev + current;
});
console.log("p010: " + sum.toString());
} |
5f1c518cedad97564e30a2029307a5c821878d90 | TypeScript | ChanScen/cocos-game-framework | /assets/script/game/TColor.ts | 2.53125 | 3 | import { FColor } from "../framework/FColor";
const { ccclass, property } = cc._decorator;
/**
* 颜色工具
* - 不在 onLoad 中执行,因为只有一个颜色配置文件,所以在编辑器中操作保证所见即所得。
* - 如果未来有多个颜色配置文件,则需要同 FText 一样。
*/
@ccclass
export class TColor extends cc.Component {
@property({ tooltip: "颜色字符串" })
private key: string = "none"
@property({ tooltip: "编辑器操作" })
private get E() { return false }
private set E(v: boolean) { CC_EDITOR && this.update_color() }
private update_color() {
this.node.color = FColor.get_color(this.key as any)
}
}
|
f2199728c5a5a1f11042a2b51f06b2ee4caa32ee | TypeScript | SuviVappula/tilavarauspalvelu-ui | /ui/modules/util.test.ts | 2.734375 | 3 | import { ApplicationEventSchedule, Cell, DAY } from "./types";
import {
cellsToApplicationEventSchedules,
applicationEventSchedulesToCells,
applicationRoundState,
} from "./util";
jest.mock("next/config", () => () => ({
serverRuntimeConfig: {},
publicRuntimeConfig: {},
}));
const cell = (hour: number, state = true): Cell => ({
label: "cell",
key: "key",
hour,
state,
});
test("test that time selector ui model converts to api model", () => {
const week = [
[cell(7), cell(8), cell(9), cell(11)],
[cell(12)],
[cell(22), cell(23)],
];
const result = cellsToApplicationEventSchedules(week);
expect(result.length).toBe(4);
expect(result[0]).toStrictEqual({ begin: "07:00", end: "10:00", day: 0 });
expect(result[1]).toStrictEqual({ begin: "11:00", end: "12:00", day: 0 });
expect(result[2]).toStrictEqual({ begin: "12:00", end: "13:00", day: 1 });
expect(result[3]).toStrictEqual({ begin: "22:00", end: "00:00", day: 2 });
const noSelections = cellsToApplicationEventSchedules([
[cell(7, false), cell(8, false), cell(9, false)],
]);
expect(noSelections.length).toBe(0);
});
const appEventSchedule = (
begin: string,
end: string,
day: DAY
): ApplicationEventSchedule => ({ begin, end, day });
const cellWithHour = (cells: Cell[], hour: number) =>
cells.find((c) => c.hour === hour);
test("test that api model converts to time selector ui model", () => {
const result = applicationEventSchedulesToCells([
appEventSchedule("08:00", "11:00", 0),
appEventSchedule("07:00", "08:00", 1),
]);
expect(result.length).toBe(7);
expect(cellWithHour(result[0], 7)?.state).toBe(false);
expect(cellWithHour(result[0], 8)?.state).toBe(true);
expect(cellWithHour(result[0], 9)?.state).toBe(true);
expect(cellWithHour(result[0], 10)?.state).toBe(true);
expect(cellWithHour(result[0], 11)?.state).toBe(false);
expect(cellWithHour(result[1], 7)?.state).toBe(true);
});
test("applicationRoundState", () => {
jest
.useFakeTimers("modern")
.setSystemTime(new Date("2021-01-01T007:59:59Z").getTime());
expect(
applicationRoundState("2021-01-01T08:00:00Z", "2021-02-01T08:00:00Z")
).toBe("pending");
jest
.useFakeTimers("modern")
.setSystemTime(new Date("2021-01-01T08:00:01Z").getTime());
expect(
applicationRoundState("2021-01-01T08:00:00Z", "2021-02-01T08:00:00Z")
).toBe("active");
jest
.useFakeTimers("modern")
.setSystemTime(new Date("2021-02-01T08:00:01Z").getTime());
expect(
applicationRoundState("2021-01-01T08:00:00Z", "2021-02-01T08:00:00Z")
).toBe("past");
});
|
3eee91e5fb19cbe073957b032e330e2897c623e8 | TypeScript | mikemountjoy/open-source-design-system | /src/brandColours.ts | 2.71875 | 3 | export const colourPalette = {
examplePalette: {
primary: {
main: {
hex: "#A42824",
RGB: "164,40,36",
on: "#FFFFFF",
},
light: {
hex: "#DA342F",
RGB: "218,52,47",
on: "#FFFFFF",
},
dark: {
hex: "#661614",
RGB: "102,22,20",
on: "#FFFFFF",
},
},
secondary: {
main: {
hex: "#0B466B",
RGB: "11,70,107",
on: "#FFFFFF",
},
light: {
hex: "#599CAF",
RGB: "89,156,175",
on: "#FFFFFF",
},
dark: {
hex: "#05263B",
RGB: "5,38,59",
on: "#FFFFFF",
},
},
complimentary: {
main: {
hex: "#FFEE52",
RGB: "255,238,82",
on: "#272727",
},
light: {
hex: "#FFF59D",
RGB: "255,245,157",
on: "#272727",
},
dark: {
hex: "#CEB900",
RGB: "206,185,0",
on: "#272727",
},
},
action: {
main: {
hex: "#743C8F",
RGB: "116,60,143",
on: "#FFFFFF",
},
light: {
hex: "#AD65CF",
RGB: "173,101,207",
on: "#FFFFFF",
},
dark: {
hex: "#4E2662",
RGB: "79,38,98",
on: "#FFFFFF",
},
},
error: {
main: {
hex: "#FF7320",
RGB: "255,115,32",
on: "#FFFFFF",
},
dark: {
hex: "#C54901",
RGB: "197,73,1",
on: "#FFFFFF",
},
},
background: {
hex: "#F6F6F6",
RGB: "246,246,246",
},
surface: {
hex: "#FFFFFF",
RGB: "255,255,255",
on: "#272727",
},
white: {
hex: "#FFFFFF",
RGB: "255,255,255",
on: "#272727",
},
black: {
main: { hex: "#272727", RGB: "39,39,39", on: "#FFFFFF" },
tint80: { hex: "#696969", RGB: "105,105,105", on: "#FFFFFF" },
tint60: { hex: "#A0A0A0", RGB: "160,160,160", on: "#FFFFFF" },
tint40: { hex: "#C7C7C7", RGB: "199,199,199", on: "#272727" },
tint20: { hex: "#ECECEC", RGB: "236,236,236", on: "#272727" },
},
},
};
interface IColourCodes {
hex: string;
RGB: string;
on?: string;
}
interface IColourVariations {
main: IColourCodes;
light?: IColourCodes;
dark?: IColourCodes;
}
interface IBlackVariations {
main: IColourCodes;
tint80: IColourCodes;
tint60: IColourCodes;
tint40: IColourCodes;
tint20: IColourCodes;
}
export interface IColourPalette {
primary: IColourVariations;
secondary: IColourVariations;
complimentary: IColourVariations;
action: IColourVariations;
error: IColourVariations;
background: IColourCodes;
surface: IColourCodes;
white: IColourCodes;
black: IBlackVariations;
}
|
b9173fb088e6a1fe0dab2be827faa0202d4d2dbb | TypeScript | stormherz/vscode-jumpy | /src/jumpy-positions.ts | 3.15625 | 3 | export interface JumpyPosition {
line: number;
character: number;
charOffset: number;
}
export interface JumpyFn {
(maxDecorations: number, firstLineNumber: number, lines: string[], regexp: RegExp): JumpyPosition[]
}
export function jumpyWord(maxDecorations: number, firstLineNumber: number, lines: string[], regexp: RegExp): JumpyPosition[] {
let positionIndex = 0;
const positions: JumpyPosition[] = [];
for (let i = 0; i < lines.length && positionIndex < maxDecorations; i++) {
let lineText = lines[i];
let word: RegExpExecArray;
while (!!(word = regexp.exec(lineText)) && positionIndex < maxDecorations) {
positions.push({ line: i + firstLineNumber, character: word.index, charOffset: 2 });
}
}
return positions;
}
export function jumpyLine(maxDecorations: number, firstLineNumber: number, lines: string[], regexp: RegExp): JumpyPosition[] {
let positionIndex = 0;
const positions: JumpyPosition[] = [];
for (let i = 0; i < lines.length && positionIndex < maxDecorations; i++) {
if (!lines[i].match(regexp)) {
positions.push({ line: i + firstLineNumber, character: 0, charOffset: lines[i].length == 1 ? 1 : 2 });
}
}
return positions;
}
|
880c585cfbfcdb96dcf2e1b81635319a0df7ad1f | TypeScript | frenebo/ts_canvas | /client/app/scripts/view/graphicWrappers/edgeWrapper.ts | 3.1875 | 3 | import { GraphicWrapper } from "./graphicWrapper.js";
import { PortWrapper } from "./portWrapper.js";
import { VertexWrapper } from "./vertexWrapper.js";
/** Class for containing a graph edge's PIXI graphic */
export class EdgeWrapper extends GraphicWrapper {
private static readonly spriteLeftRightPadding = 25;
private static readonly spriteTopBottomPadding = 25;
private static readonly lineWidth = 10;
private static readonly unselectedLineColor = 0x000000;
private static readonly selectedLineColor = 0xFFFF00;
private static readonly inconsistentLineColor = 0xCC0000;
/**
* Redraws a PIXI edge graphic to the given specifications
* @param graphics - The PIXI graphic to redraw
* @param sourceX - The source X position of the edge
* @param sourceY - The source Y position of the edge
* @param targetX - The target X position of the edge
* @param targetY - The target Y position of the edge
* @param selected - Whether or not the edge is selected
* @param consistent - Whether or not the edge is consistent, whether source and target values agree
*/
private static draw(
graphics: PIXI.Graphics,
sourceX: number,
sourceY: number,
targetX: number,
targetY: number,
selected: boolean,
consistent: "consistent" | "inconsistent", // @TODO implement
): void {
graphics.clear();
let lineColor: number;
if (selected) {
lineColor = EdgeWrapper.selectedLineColor;
} else {
if (consistent === "consistent") {
lineColor = EdgeWrapper.unselectedLineColor;
} else {
lineColor = EdgeWrapper.inconsistentLineColor;
}
}
graphics.lineStyle(EdgeWrapper.lineWidth, lineColor);
const topLeftX = Math.min(sourceX, targetX);
const topLeftY = Math.min(sourceY, targetY);
graphics.moveTo(
(sourceX - topLeftX) + EdgeWrapper.spriteLeftRightPadding,
(sourceY - topLeftY) + EdgeWrapper.spriteTopBottomPadding,
);
graphics.lineTo(
(targetX - topLeftX) + EdgeWrapper.spriteLeftRightPadding,
(targetY - topLeftY) + EdgeWrapper.spriteTopBottomPadding,
);
}
private readonly graphics: PIXI.Graphics;
private isSelected = false;
private previousSourceX = 0;
private previousTargetX = 0;
private previousSourceY = 0;
private previousTargetY = 0;
private previousIsSelected = false;
/**
* Constructs an edge wrapper.
* @param sourceVertex - The source vertex wrapper
* @param sourcePort - The source port wrapper
* @param targetVertex - The target vertex wrapper
* @param targetPort - The target port wrapper
* @param consistency - Whether or not the edge is consistent, whether source and target values agree
*/
constructor(
private readonly sourceVertex: VertexWrapper,
private readonly sourcePort: PortWrapper,
private readonly targetVertex: VertexWrapper,
private readonly targetPort: PortWrapper,
private readonly consistency: "consistent" | "inconsistent",
) {
super();
this.graphics = new PIXI.Graphics();
this.addChild(this.graphics);
this.refresh(true);
}
/**
* Sets whether or not the edge is selected.
* @param selected - Whether or not the edge should be selected
*/
public toggleSelected(selected: boolean): void {
this.isSelected = selected;
this.refresh();
}
/**
* Decides whether the edge has changed, then redraws it if it has.
* @param force - Tells refresh to redraws the edge regardless of whether it has changed
*/
public refresh(force = false): void {
const sourceX = this.sourcePort.localX() + this.sourceVertex.localX() + PortWrapper.width / 2;
const sourceY = this.sourcePort.localY() + this.sourceVertex.localY() + PortWrapper.height / 2;
const targetX = this.targetPort.localX() + this.targetVertex.localX() + PortWrapper.width / 2;
const targetY = this.targetPort.localY() + this.targetVertex.localY() + PortWrapper.height / 2;
if (
!force &&
sourceX === this.previousSourceX &&
sourceY === this.previousSourceY &&
targetX === this.previousTargetX &&
targetY === this.previousTargetY &&
this.isSelected === this.previousIsSelected
) {
// if the line has not changed at all, do nothing
return;
}
// Don't redraw if the line dimensions have not changed - just move it
if (
!force &&
targetY - sourceY === this.previousTargetY - this.previousSourceY &&
targetX - sourceX === this.previousTargetX - this.previousSourceX &&
this.isSelected === this.previousIsSelected
) {
// skip redraw
} else {
EdgeWrapper.draw(
this.graphics,
sourceX,
sourceY,
targetX,
targetY,
this.isSelected,
this.consistency,
);
}
this.previousSourceX = sourceX;
this.previousSourceY = sourceY;
this.previousTargetX = targetX;
this.previousTargetY = targetY;
this.previousIsSelected = this.isSelected;
this.setLocalPosition(
Math.min(sourceX, targetX) - EdgeWrapper.spriteLeftRightPadding,
Math.min(sourceY, targetY) - EdgeWrapper.spriteTopBottomPadding,
);
const angle = Math.atan((targetY - sourceY) / (targetX - sourceX)) + (targetX < sourceX ? Math.PI : 0);
const thicknessHorizontalOffset = Math.sin(angle) * EdgeWrapper.lineWidth / 2;
const thicknessVerticalOffset = Math.cos(angle) * EdgeWrapper.lineWidth / 2;
this.updateHitArea(new PIXI.Polygon(
new PIXI.Point(
sourceX - this.localX() + thicknessHorizontalOffset,
sourceY - this.localY() - thicknessVerticalOffset,
),
new PIXI.Point(
sourceX - this.localX() - thicknessHorizontalOffset,
sourceY - this.localY() + thicknessVerticalOffset,
),
new PIXI.Point(
targetX - this.localX() - thicknessHorizontalOffset,
targetY - this.localY() + thicknessVerticalOffset,
),
new PIXI.Point(
targetX - this.localX() + thicknessHorizontalOffset,
targetY - this.localY() - thicknessVerticalOffset,
),
));
}
}
|
c355ed67065f46928cdaa753557b68013ade9acf | TypeScript | Kyappy/Tour-of-Heroes | /src/app/components/hero-search/hero-search.component.ts | 2.609375 | 3 | import {Component, Input, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {Subject} from 'rxjs/Subject';
import {HeroService} from '../../services/hero.service';
import {Hero} from '../../supports/hero';
/**
* App hero search component.
*/
@Component({
selector: 'app-hero-search',
styleUrls: ['./hero-search.component.css'],
templateUrl: './hero-search.component.html'
})
export class HeroSearchComponent implements OnInit {
/**
* Gets the heroes search results.
* @returns {Observable<Hero[]>}
*/
public get heroes$(): Observable<Hero[]> { return this._heroes$; }
/**
* The heroes search results.
* @type {Observable<Hero[]>}
*/
private _heroes$: Observable<Hero[]>;
/**
* The string to search.
* @type {Subject<string>}
*/
private _searchTerms: Subject<string> = new Subject<string>();
/**
* The delay between to search requests.
* @type {Subject<string>}
*/
@Input('searchDelay') private _searchDelay: number = 300;
/**
* Creates a new HeroSearchComponent instance.
* @param {HeroService} heroService The hero service to inject.
* @returns {HeroSearchComponent} A new HeroSearchComponent instance.
*/
public constructor(private heroService: HeroService) {}
/**
* Initialize the component.
* @returns {void}
*/
public ngOnInit(): void {
this._heroes$ = this._searchTerms.pipe(
debounceTime(this._searchDelay),
distinctUntilChanged(),
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
}
/**
* Pushes a search term into the observable stream.
* @param {string} term The term to search
* @returns {void}
*/
public search(term: string): void {
this._searchTerms.next(term);
}
} |
0aa3f074090aba7803076515e10036fd3baaebef | TypeScript | pinguet62/indicative-rules | /src/raw/array.ts | 3.265625 | 3 | /**
* @module indicative-rules
*/
/*
* indicative-rules
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Returns a boolean telling, if value is an array or not.
*
* @example
* ```
* const { is } = require('indicative')
*
* if (is.array([])) {
* }
* ```
*/
export const array = (value: any): boolean => Array.isArray(value)
|
4b385f71c9229aff0a921b469f9a8eb01e05e52a | TypeScript | lpubsppop01/local-note-app | /src/main/directory-utility.ts | 2.90625 | 3 | import * as fs from "fs";
import * as path from "path";
export default class DirectoryUtility {
static mkdirPSync(dirPath: string) {
const tokens = dirPath.split(/\/|\\/);
const buf = []
for (let i = 0; i < tokens.length; ++i) {
buf.push(tokens[i]);
const bufPath = buf.join("/");
if (!fs.existsSync(bufPath)) {
fs.mkdirSync(bufPath);
}
}
}
} |
dfa15d444302b9b3c4d6c60f1288c9dc25e89175 | TypeScript | Aareksio/zombie-net | /src/resolvers/item.resolver.spec.ts | 2.734375 | 3 | import 'mocha';
import { expect } from 'chai';
import { ItemResolver } from './item.resolver';
function createFakeItemRepository() {
const items = [{ id: 1 }, { id: 2 }];
return {
findOne: id => items.find(item => item.id === id),
find: () => items
}
}
describe('ItemResolver', () => {
let itemResolver;
beforeEach(() => {
const itemRepository = createFakeItemRepository();
itemResolver = new ItemResolver(itemRepository as any);
});
describe('query:item', async () => {
it('returns item when item id available', async () => {
const item = await itemResolver.item(1);
expect(item).to.be.deep.equal({ id: 1 });
});
it('returns undefined when item id not available', async () => {
const item = await itemResolver.item(42);
expect(item).to.be.undefined;
});
});
describe('query:items', async () => {
it('resolves with all available items', async () => {
const items = await itemResolver.items();
expect(items).to.be.deep.equal([{ id: 1 }, { id: 2 }]);
});
});
});
|