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
|
|---|---|---|---|---|---|---|
4992863ac3b028dd6a794c01152975547607d493
|
TypeScript
|
rwson/TypeScript
|
/4-Class/class-6.ts
| 3.28125
| 3
|
/**
* class
* typescript中的static
* public private
* build by rwson @11/5/15
* mail:rw_Song@sina.com
*/
class Greeter{
greeting:string;
constructor(message:string){
this.greeting = message;
}
greet(){
return "hello," + this.greeting;
}
}
var greet:Greeter;
greet = new Greeter("呵呵哒");
alert(greet.greet());
|
110dcb4fa89a588217d9f0b773baa9896dc7a64c
|
TypeScript
|
getclaps/worker
|
/src/routes/validate.ts
| 3.03125
| 3
|
import * as er from '../errors';
// A non-empty scheme component followed by a colon (:),
// consisting of a sequence of characters beginning with a letter and
// followed by any combination of letters, digits, plus (+), period (.), or hyphen (-).
const RE_PROTOCOL = /^[a-z][a-z0-9.+-]*:/i;
export const validateURL = (url?: string | null) => {
if (!url) throw new er.BadRequestError('No url provided')
if (url.length > 4096) throw new er.BadRequestError('URL too long. 4096 characters max.');
try {
const withProtocol = url.match(RE_PROTOCOL) ? url : `https://${url}`;
const targetURL = new URL(withProtocol);
targetURL.search = '';
return targetURL;
} catch {
throw new er.BadRequestError('Invalid or missing URL');
}
}
|
93e61022f2f9e5d1d0e18a475bd3da6840d2602a
|
TypeScript
|
danikaze/trpg-connector
|
/src/utils/logging.ts
| 2.984375
| 3
|
// tslint:disable:no-console
export const msgLog = msg.bind(undefined, 'log');
export const msgError = msg.bind(undefined, 'error');
export const msgWarn = msg.bind(undefined, 'warn');
export const msgTable = table.bind(undefined);
type MsgType = 'log' | 'error' | 'warn';
const COLOR_MAP: { [type: string]: string } = {
log: '#000ca2',
error: '#ca0000',
warn: '#ffb818',
table: '#999',
};
const PREFIX_STYLE = (type: MsgType | 'table') =>
`font-weight: bold; background: ${COLOR_MAP[type]}; color: #fff; padding: 0 5px; border-top-left-radius: 7px; border-bottom-left-radius: 7px`;
const DATE_STYLE = `font-weight: bold; background: #666; color: #fff; padding: 0 5px; border-top-right-radius: 7px; border-bottom-right-radius: 7px`;
function msg(type: MsgType, ...data: unknown[]) {
console[type](
`%c${LOG_PREFIX}%c${getDate()}`,
PREFIX_STYLE(type),
DATE_STYLE,
...data
);
}
function table<T extends {}>(data: T): void {
console.log(
`%c${LOG_PREFIX}%c${getDate()}`,
PREFIX_STYLE('table'),
DATE_STYLE
);
console.table(data);
}
function getDate(): string {
// tslint:disable:no-magic-numbers
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
const min = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
const zzz = String(d.getMilliseconds()).padStart(3, '0');
return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}.${zzz}`;
}
|
adb6df04ee9cbdef34ea4a6720d0cfbabf42a610
|
TypeScript
|
marcoszanre/obfuscation-bot-typescript
|
/src/app/tableService.ts
| 2.765625
| 3
|
import * as debug from "debug";
// tslint:disable-next-line:no-var-requires
const azure = require("azure-storage");
// Initialize debug logging module
const log = debug("msteams");
// Initialize Table Service
const tableSvc = azure.createTableService(process.env.STORAGE_ACCOUNT_NAME, process.env.STORAGE_ACCOUNT_ACCESSKEY);
// Function to initialize the table service and return success to the application
const initTableSvc = () => {
tableSvc.createTableIfNotExists("proactiveTable", (error) => {
if (!error) {
// Table exists or created
log("table service done");
}
});
};
// Function to insert a public user and experts team conversation in database, to be used later for proactive messaging
const insertConvReference = (channelConversationReference: string, webConversationReference: string, webConversationID: string) => {
const convReference = {
PartitionKey: {_: "convReference"},
RowKey: {_: webConversationID},
channelRef: {_: channelConversationReference},
webRef: {_: webConversationReference},
};
tableSvc.insertEntity("proactiveTable", convReference, (error) => {
if (!error) {
// Entity inserted
log("success!");
} else {
log(error);
}
});
};
// Function to retrieve the conversation reference by the teams experts, based on the Teams channel thread id
const getConvReference = async (channelRef: string) => {
return new Promise((resolve) => {
const query = new azure.TableQuery()
.where("channelRef eq ?", channelRef);
tableSvc.queryEntities("proactiveTable", query, null, (error, result) => {
if (!error) {
// query was successful
const convReturnReference: IConvReference = {
convRef: result.entries[0].webRef._,
channelRef: result.entries[0].channelRef._
};
resolve(convReturnReference);
}
});
});
};
// Conversation Reference interface
interface IConvReference {
convRef: string;
channelRef: string;
}
// Function to retrieve the conversation reference by the public user, based on the public chat bot conversation id to post to the Teams channel
const getConvChannelReference = async (webconvid: string) => {
return new Promise((resolve) => {
tableSvc.retrieveEntity("proactiveTable", "convReference", webconvid, (error, result) => {
if (!error) {
// query was successful
const convReturnReference: IConvReference = {
convRef: result.webRef._,
channelRef: result.channelRef._
};
resolve(convReturnReference);
}
});
});
};
// Export table service functions
export {
initTableSvc,
insertConvReference,
getConvReference,
IConvReference,
getConvChannelReference
};
|
16c4566b3c4ecce5c6cca979da178bcf9d88f1c7
|
TypeScript
|
kuhel/inferno
|
/packages/inferno-clone-vnode/src/index.ts
| 2.828125
| 3
|
/**
* @module Inferno-Clone-VNode
*/ /** TypeDoc Comment */
import {
createComponentVNode,
createTextVNode,
createVNode,
directClone,
EMPTY_OBJ,
normalizeProps,
VNode
} from 'inferno';
import {
combineFrom,
isArray,
isInvalid,
isStringOrNumber,
isUndefined
} from 'inferno-shared';
import { ChildFlags, VNodeFlags } from 'inferno-vnode-flags';
/*
directClone is preferred over cloneVNode and used internally also.
This function makes Inferno backwards compatible.
And can be tree-shaked by modern bundlers
Would be nice to combine this with directClone but could not do it without breaking change
*/
/**
* Clones given virtual node by creating new instance of it
* @param {VNode} vNodeToClone virtual node to be cloned
* @param {Props=} props additional props for new virtual node
* @param {...*} _children new children for new virtual node
* @returns {VNode} new virtual node
*/
export function cloneVNode(vNodeToClone: VNode, props?, ..._children): VNode {
if (arguments.length === 3) {
if (!props) {
props = {};
}
props.children = _children[0] as VNode;
} else {
const childrenLen = _children.length;
if (childrenLen > 0) {
if (!props) {
props = {};
}
props.children = _children as any;
}
}
let newVNode;
const flags = vNodeToClone.flags;
let className = vNodeToClone.className;
let key = vNodeToClone.key;
let ref = vNodeToClone.ref;
if (props) {
if (!isUndefined(props.className)) {
className = props.className as string;
}
if (!isUndefined(props.ref)) {
ref = props.ref;
}
if (!isUndefined(props.key)) {
key = props.key;
}
}
if (flags & VNodeFlags.Component) {
newVNode = createComponentVNode(
flags,
vNodeToClone.type,
!vNodeToClone.props && !props
? EMPTY_OBJ
: combineFrom(vNodeToClone.props, props),
key,
ref
);
const newProps = newVNode.props;
const newChildren = newProps.children;
// we need to also clone component children that are in props
// as the children may also have been hoisted
if (newChildren) {
if (isArray(newChildren)) {
const len = newChildren.length;
if (len > 0) {
const tmpArray: any[] = [];
for (let i = 0; i < len; i++) {
const child = newChildren[i];
if (isStringOrNumber(child)) {
tmpArray.push(child);
} else if (!isInvalid(child) && child.flags) {
tmpArray.push(directClone(child));
}
}
newProps.children = tmpArray;
}
} else if (newChildren.flags) {
newProps.children = directClone(newChildren);
}
}
newVNode.children = null;
} else if (flags & VNodeFlags.Element) {
if (!props) {
props = {
children: vNodeToClone.children
};
}
newVNode = createVNode(
flags,
vNodeToClone.type,
className,
null,
ChildFlags.HasInvalidChildren,
combineFrom(vNodeToClone.props, props),
key,
ref
);
} else if (flags & VNodeFlags.Text) {
newVNode = createTextVNode(vNodeToClone.children);
}
return normalizeProps(newVNode);
}
|
ed2b830b9bfab10f52f51a5e07b891b0b64b6734
|
TypeScript
|
Armenvardanyan95/gitam-web
|
/src/app/state/tags/tags.reducer.ts
| 2.578125
| 3
|
import { createReducer, on } from '@ngrx/store';
import { loadAllTagsSuccess, selectTag, deselectTag, deselectAllTags } from './tags.actions';
export interface TagsState {
allTags: string[];
selectedTags: string[];
}
const initialTagsState: TagsState = {
allTags: [],
selectedTags: [],
};
/* tslint:disable-next-line:variable-name */
export const _tagsReducer = createReducer(
initialTagsState,
on(loadAllTagsSuccess, (state, {payload}) => ({...state, allTags: payload})),
on(selectTag, (state, {payload}) => ({
...state,
selectedTags: Array.from(new Set([...state.selectedTags, payload])),
})),
on(deselectTag, (state, {payload}) => ({
...state,
selectedTags: state.selectedTags.filter(tag => tag !== payload),
})),
on(deselectAllTags, state => ({...state, selectedTags: []})),
);
|
4a7013e206497ab9323527ac3bb3a1550a5e85df
|
TypeScript
|
mingderwang/lds-jws2020
|
/packages/json-web-key-2020/src/restrictions/JsonWebKey2020.test.ts
| 2.90625
| 3
|
import { JsonWebKey } from '../JsonWebKey';
const message = Buffer.from('hello');
const recommended: any = [
{ kty: 'OKP', crvOrSize: 'Ed25519' },
{ kty: 'OKP', crvOrSize: 'X25519' },
{ kty: 'EC', crvOrSize: 'secp256k1' },
{ kty: 'EC', crvOrSize: 'P-256' },
{ kty: 'EC', crvOrSize: 'P-384' },
{ kty: 'RSA', crvOrSize: 2048 },
{ kty: 'EC', crvOrSize: 'P-521' }, // negative test / not supported at all.
];
recommended.forEach((generateOptions: any) => {
describe(`${generateOptions.kty} ${generateOptions.crvOrSize}`, () => {
let key1: JsonWebKey;
let key2: JsonWebKey;
it('generate', async () => {
try {
key1 = await JsonWebKey.generate(generateOptions);
key2 = await JsonWebKey.generate(generateOptions);
expect(key1).toBeDefined();
expect(key2).toBeDefined();
} catch (e) {
if (generateOptions.crvOrSize === 'P-521') {
return expect(e.message).toBe(
'No recommended generate alg for 2020, EC, P-521'
);
}
throw e;
}
});
it('sign / verify', async () => {
try {
const signature1 = await key1.signer().sign({ data: message });
const signature2 = await key2.signer().sign({ data: message });
let verified1 = await key1
.verifier()
.verify({ data: message, signature: signature1 });
let verified2 = await key2
.verifier()
.verify({ data: message, signature: signature2 });
expect(verified1).toBe(true);
expect(verified2).toBe(true);
verified1 = await key1
.verifier()
.verify({ data: message, signature: signature2 });
verified2 = await key2
.verifier()
.verify({ data: message, signature: signature1 });
expect(verified1).toBe(false);
expect(verified2).toBe(false);
} catch (e) {
if (generateOptions.crvOrSize === 'X25519') {
return expect(e.message).toBe(
'No recommended sign alg for 2020, OKP, X25519'
);
}
// because key generation will fail for forbidden crv
if (generateOptions.crvOrSize === 'P-521') {
return expect(e.message).toBe(
"Cannot read property 'signer' of undefined"
);
}
throw e;
}
});
it('deriveSecret', async () => {
try {
const secret = await key1.deriveSecret({
publicKey: key2,
});
expect(secret.toString('hex').length).toBeDefined();
} catch (e) {
if (generateOptions.crvOrSize === 'Ed25519') {
return expect(e.message).toBe(
'No recommended deriveSecret alg for 2020, OKP, Ed25519'
);
}
if (generateOptions.kty === 'RSA') {
return expect(e.message).toBe(
'No recommended deriveSecret alg for 2020, RSA, 2048'
);
}
// because key generation will fail for forbidden crv
if (generateOptions.crvOrSize === 'P-521') {
return expect(e.message).toBe(
"Cannot read property 'deriveSecret' of undefined"
);
}
throw e;
}
});
it('encrypt / decrypt', async () => {
try {
const publicKeys = [key1, key2];
const jwe: any = await key1.encrypt(message, publicKeys);
expect(jwe.recipients.length).toBe(2);
// expect(jwe.recipients[0].header.alg).toBe('ECDH-ES+A256KW');
const plaintext = await key1.decrypt(jwe as any);
expect(plaintext).toEqual(message);
} catch (e) {
if (generateOptions.crvOrSize === 'Ed25519') {
return expect(e.message).toBe(
'No recommended encrypt alg for 2020, OKP, Ed25519'
);
}
if (generateOptions.crvOrSize === 'secp256k1') {
return expect(e.message).toBe(
'No recommended encrypt alg for 2020, EC, secp256k1'
);
}
// because key generation will fail for forbidden crv
if (generateOptions.crvOrSize === 'P-521') {
return expect(e.message).toBe(
"Cannot read property 'encrypt' of undefined"
);
}
throw e;
}
});
});
});
|
382826bda14a23371fe18200974fc92fbd3fc71d
|
TypeScript
|
SoftwareSeniPT/Life-Coaching-Demo
|
/app/pages/training-schedule/training-schedule.red.ts
| 3.109375
| 3
|
/*
* Reducer for Timeline component
*/
interface IObjectConstructor extends ObjectConstructor {
assign(target: any, ...sources: any[]): any;
}
declare var Object: IObjectConstructor;
const initialState: any = {
scheduleSelected: 0,
schedule: [{
name: "Monday",
date: "May 3",
selected: false
}, {
name: "Tuesday",
date: "May 4",
selected: false
}, {
name: "Wednesday",
date: "May 5",
selected: false
}, {
name: "Thursday",
date: "May 6",
selected: false
}, {
name: "Friday",
date: "May 7",
selected: false
}, {
name: "Saturday",
date: "May 8",
selected: false
}, {
name: "Sunday",
date: "May 9",
selected: false
}],
customEntries: [{
name: "Yoga",
time: "Wednesday AM",
duration: "1 hour",
selected: true
}, {
name: "Walking",
time: "Wednesday AM",
duration: "1 hour",
selected: false
}, {
name: "Yoga",
time: "Wednesday AM",
duration: "1 hour",
selected: false
}]
};
export const trainingScheduleReducer: any = (state: any = initialState, action: any) => {
let scheduleList: any;
let customEntries: any;
switch (action.type) {
case "Select schedule on schedule list":
scheduleList = state.schedule.map((o: any, i: number) => {
if (i === action.id) {
return Object.assign({}, o, {
selected: (action.dayID === action.current ? false : action.dayID)
});
} else {
return o;
}
});
return Object.assign({}, state, {
schedule: scheduleList
});
case "Select custom entry on schedule list":
customEntries = state.customEntries.map((o: any, i: number) => {
if (i === action.id) {
return Object.assign({}, o, {
selected: true
});
} else {
return o;
}
});
return Object.assign({}, state, { customEntries: customEntries });
case "Unselect custom entry on schedule list":
customEntries = state.customEntries.map((o: any, i: number) => {
if (i === action.id) {
return Object.assign({}, o, {
selected: false
});
} else {
return o;
}
});
return Object.assign({}, state, { customEntries: customEntries });
default:
return state;
}
};
|
ce6bc3394d960b39e44668002bd5907ac448cc1e
|
TypeScript
|
athleticspot/athleticspot
|
/web/src/main/webapp/app/training/results/validateDuration.ts
| 2.59375
| 3
|
import {FormGroup} from "@angular/forms";
export function validateDuration(group: FormGroup){
let isAtLeastOne = false;
if (group && group.controls) {
for (const control in group.controls) {
if (group.controls.hasOwnProperty(control) && group.controls[control].valid && group.controls[control].value) {
isAtLeastOne = true;
break;
}
}
}
return isAtLeastOne ? null : { 'required': true };
}
|
41b98072b686262d156c95959151afe7e4af31e6
|
TypeScript
|
nccnm/100days_of_TypeScript
|
/day3_jquery_alike/myJQuery.ts
| 3.15625
| 3
|
class ElementManager {
private elements: NodeListOf<Element>;
constructor(selector: string) {
this.elements = document.querySelectorAll(selector);
}
css(style: string | Object, value: string = '') {
if (typeof style === 'string') {
this.setStyle(style, value);
return this;
}
for (const property in style) {
this.setStyle(property, style[property]);
}
return this;
}
private setStyle(property: string, value: string) {
for (let i = 0; i < this.elements.length; i++) {
const el = this.elements.item(i) as HTMLElement;
el.style[property] = value;
}
}
}
export default function $(selector: string) {
return new ElementManager(selector);
}
|
0df2dd4d9ef60caf521b6cd30c8ba435e27d4844
|
TypeScript
|
a-type/simulated
|
/lib/inputTransformers.ts
| 3.046875
| 3
|
export type PolymorphicInput = {
[kind: string]: {} | undefined;
};
export type PolymorphicFormValues = {
kind: string;
[other: string]: any;
};
export const toPolymorphicInput = <T extends PolymorphicInput>(
values: PolymorphicFormValues | null,
): T => {
if (!values) return null;
const { kind, ...rest } = values;
return {
[(kind as string).toLowerCase()]: rest,
} as T;
};
|
0acec8b7a16d759bdcf96b8e0cc6dd0c7f5dfab3
|
TypeScript
|
UAlbertaALTLab/click-in-text-chrome
|
/src/lib/transover_utils.ts
| 2.765625
| 3
|
// helper functions
import XRegExp from 'xregexp/src'
import {FailedTranslation, SuccessfulTranslation} from './transover_core'
export const TransOver = {
modifierKeys: {
16: 'shift', 17: 'ctrl', 18: 'alt', 224: 'meta', 91: 'command', 93: 'command', 13: 'Return'
},
// fixme: are there handy utility types for the returned HTML? There must be.
/**
*
* @return the HTML that we show
*/
formatTranslation: function (translation: FailedTranslation | SuccessfulTranslation): string {
let formatted_translation = ''
if (translation instanceof Array) {
// translation was successful
translation.forEach(function (pos_block) {
const formatted_pos = pos_block.lemma ? '<strong>' + pos_block.lemma + '</strong>: ' : ''
const formatted_meanings = pos_block.meanings.slice(0, 5).join(', ') + (pos_block.meanings.length > 5 ? '...' : '')
formatted_translation = formatted_translation + '<div class="pos_translation ' + '">' + formatted_pos + formatted_meanings + '</div>'
})
} else {
// translation is a oops message (translation not found)
formatted_translation = '<div class="pos_translation ' + '">' + TransOver.escape_html(translation) + '</div>'
}
return formatted_translation
},
// todo: documentation
/**
*
*/
escape_html: function (text: string): string {
return text.replace(XRegExp('(<|>|&)', 'g'), function ($0, $1) {
switch ($1) {
case '<':
return '<'
case '>':
return '>'
case '&':
return '&'
}
})
}
}
|
14bcbfc615c8dbae23def7d525a95bce4f64e6cc
|
TypeScript
|
williamszk/statistical-learning
|
/angular_study/youtube-freeCodeCamp/01-intro-typescript/datatypes.ts
| 4.25
| 4
|
let lname = "Diffie";
// lname = 19;
// type inference
// does not need to define the datatype
let fname: string = "Mark";
let newname = lname.toUpperCase();
console.log(newname);
// declare
let age: number;
// assign
age = 25;
let dob = "25";
let result = parseInt(dob);
let isValid: boolean; // by default this is undefined
// console.log(isValid); // this gives an error
// every non assigned variable have the value of undefined
let isOk: boolean = false;
console.log(isOk);
// ------------------------------
// two ways of declaring arrays
let empList: string[];
// the generics syntax
let depList: Array<string>;
// empList = ["a", "b", 10]; // this gives an error
let numList: Array<number>;
numList = [1, 2, 3, 4];
let results = numList.filter((num) => {
num > 2;
});
numList.filter((num) => {
num < 10;
});
let result1 = numList.find((num) => {
num === 2;
});
// let result1: number | undefined
let sumNum = numList.reduce((acc, num) => acc + num);
// stopped at:
// https://youtu.be/3qBXWUpoPHo?t=3638
const enum Color {
Red,
Green,
Blue,
}
// Design System
let c: Color = Color.Green;
// Tuples
let swapNumbs: [number, number];
function swapNumbers(num1: number, num2: number): [number, number] {
return [num2, num1];
}
swapNumbs = swapNumbers(10, 20);
console.log(swapNumbs);
swapNumbs[0];
swapNumbs[1];
// swapNumbs[2]; // this will give an error, given that it is a tuple
// any datatype
let department;
department = "IT";
department = 10;
// void
// never
|
2200d0e9908d3f4a1e460a991a93a43c581f8f4d
|
TypeScript
|
hikipuro/tea.js
|
/src/tea/parsers/dae/fx/texturing/DAEHint.ts
| 2.65625
| 3
|
import { DAEUtil } from "../../DAEUtil";
// parent: format
export class DAEHint {
static readonly TagName: string = "hint";
channels: string;
range: string;
precision?: string;
space?: string;
constructor() {
this.channels = null;
this.range = null;
this.precision = "DEFAULT";
this.space = null;
}
static parse(el: Element): DAEHint {
if (el == null) {
return null;
}
var value = new DAEHint();
value.channels = DAEUtil.getStringAttr(el, "channels");
value.range = DAEUtil.getStringAttr(el, "range");
value.precision = DAEUtil.getStringAttr(el, "precision", "DEFAULT");
value.space = DAEUtil.getStringAttr(el, "space");
return value;
}
toXML(): Element {
var el = document.createElement(DAEHint.TagName);
DAEUtil.setAttr(el, "channels", this.channels);
DAEUtil.setAttr(el, "range", this.range);
DAEUtil.setAttr(el, "precision", this.precision);
DAEUtil.setAttr(el, "space", this.space);
return el;
}
}
|
a22ac7aef53bb26f0b16a21239f5b88e4c1b2176
|
TypeScript
|
hitachimaverick/poolpi
|
/server/queues/outboundQueue.ts
| 2.6875
| 3
|
import * as path from 'path';
import * as fs from 'fs';
import * as extend from 'extend';
import { logger } from '../../server/logger/Logger';
class outboundQueueCollection extends Array<outboundQueue> {
private _queuePath: string;
private _isInitialized: boolean = false;
constructor(...items) {
super(...items);
this._queuePath = path.posix.join(process.cwd(), '/data/outQueues/');
this._isInitialized = true;
}
public loadDescriptors() {
this.length = 0; // Truncate the current list.
let data = [];
if (fs.existsSync(this.queuePath + 'outQueues.json')) {
try {
data = JSON.parse(fs.readFileSync(this.queuePath + 'outQueues.json', 'utf8') || '[]');
}
catch (err) {
logger.error(err);
}
}
this.length = 0;
for (let i = 0; i < data.length; i++) {
this.push(Object.assign(new outboundQueue(), data[i]));
}
let nextId = this.getNextId();
// List all the files in the directory
try {
fs.readdirSync(outQueues.queuePath).forEach(file => {
if (path.extname(file) === '.out') {
let name = path.parse(file).name;
let q = this.find(elem => { return elem.fileName === name });
if (typeof q === 'undefined') {
q = new outboundQueue();
q.fileName = name;
q.name = name.replace('_', ' ');
q.id = nextId++;
}
}
});
}
catch (err) {
logger.error(err);
}
// We should have the descriptors matched up with the queues. Now sort them by name.
this.sort((a, b) => { return a.name.localeCompare(b.name); });
// Now lets load up all the .js modules int the testmodules directory.
try {
fs.readdirSync(path.posix.join(process.cwd(), '/scripts/messages/testModules')).forEach(file => {
if (path.extname(file) === '.js') {
let name = path.parse(file).name;
let q = this.find(elem => { return elem.fileName === name });
if (typeof q === 'undefined') {
let d = {
fileName: name + path.extname(file),
name: name.replace('_', ' '),
type: 'testModule',
id: nextId++,
description: `Test module for generating outbound messages`
}
this.push(Object.assign(new outboundQueue(), d));
}
}
});
}
catch (err) { logger.error(err); }
}
public get queuePath(): string { return this._queuePath; }
public getNextId(): number {
let maxId = 0;
this.forEach(q => { maxId = Math.max(q.id, maxId); })
return maxId + 1;
}
public async saveQueue(queue: any): Promise<outboundQueue> {
// First things first. See if we have a queue with the id.
let oldq;
if (typeof queue.id !== 'undefined') {
// This is an existing queue. We are simply renaming it.
oldq = this.find(q => { return queue.id === q.id });
if (typeof oldq === 'undefined') return Promise.reject(new Error(`Queue does not exist. Could not find queue for id# ${queue.id}.`));
if (typeof queue.name !== 'undefined') oldq.name = queue.name;
if (typeof queue.description !== 'undefined') oldq.description = queue.description;
if (typeof queue.fileName !== 'undefined' && queue.fileName !== oldq.fileName && fs.existsSync(this.queuePath + oldq.fileName)) {
// We need to rename the file.
try {
fs.renameSync(this.queuePath + oldq.fileName, this.queuePath + queue.fileName);
oldq.fileName = queue.fileName;
}
catch (err) { return Promise.reject(err); }
}
}
else {
// Make sure we don't have any naming conflicts.
if (typeof queue.name === 'undefined') return Promise.reject(new Error(`Queues must have a valid name.`));
oldq = this.find(q => { return queue.name === q.name });
if (typeof oldq !== 'undefined') return Promise.reject(new Error(`Names must be unique. ${queue.name} aldready exists.`));
let fname: string = queue.fileName || this.makeFileName(queue.name);
oldq = this.find(q => { return queue.fileName === fname });
if (typeof oldq !== 'undefined') return Promise.reject(new Error(`File names must be unique. The filename ${fname} is already used.`));
oldq = new outboundQueue();
oldq.name = queue.name;
oldq.description = queue.description;
oldq.filename = fname;
oldq.id = this.getNextId();
this.push(oldq);
}
this.update((err) => { if (err) return Promise.reject(err); });
// If the messages have been provided then we need to update the file.
if (typeof queue.messages !== 'undefined') {
oldq.saveMessagesSync(queue.messages, (err) => { if (err) return Promise.reject(err); });
}
return Promise.resolve(oldq);
}
public update(cb: (err?) => {}) {
try {
fs.writeFileSync(this.queuePath + 'outQueues.json', JSON.stringify(this));
if (typeof cb !== 'undefined') cb();
}
catch (err) {
if (typeof cb !== 'undefined') cb(err);
}
}
public findQueue(q: outboundQueue) {
return this.find(queue => {
if (typeof q.id !== 'undefined' && queue.id === q.id) return true;
return false;
});
}
public makeFileName(name: string) { return name.replace(/[&\/\\#,+$~%.'":*?<>{}]/g, '_') + '.out'; }
public init() {
this.loadDescriptors();
}
}
class outboundQueue {
private _fileName: string;
constructor() { }
public id: number;
public name: string;
public description: string;
public type: string = 'messageList';
public messages: any[];
public get fileName(): string { return typeof this._fileName === 'undefined' ? this.name.replace(' ', '_') + '.out' : this.fileName; }
public set fileName(val: string) { this._fileName = val; }
public saveMessagesSync(msgs, cb): boolean {
let fd;
let eol = require('os').EOL;
try {
let file = outQueues.queuePath + this.fileName;
if (fs.existsSync(file)) fs.unlinkSync(file);
fd = fs.openSync(file, 'a');
for (let i = 0; i < msgs.length; i++) {
(i !== 0) ? fs.appendFileSync(fd, eol + JSON.stringify(msgs[i]), 'utf8') : fs.appendFileSync(fd, JSON.stringify(msgs[i]), 'utf8');
}
if(typeof cb !== 'undefined') cb();
}
catch (err) {
logger.error(err);
if (typeof cb !== 'undefined') cb(err); return false;
}
finally {
if (typeof fd !== 'undefined') fs.closeSync(fd);
}
return true;
}
public loadMessages(cb?: (err?) => {}): any {
let msgs = [];
let eol = require('os').EOL;
try {
let file = outQueues.queuePath + this.fileName;
let arr = fs.readFileSync(file).toString().split(eol);
for (let i = 0; i < arr.length; i++) {
let msg = JSON.parse(arr[i].trim());
msgs.push(msg);
}
if (typeof (cb) !== 'undefined') cb();
}
catch (err) {
if (typeof (cb) !== 'undefined') cb(err);
}
return msgs;
}
}
export var outQueues: outboundQueueCollection = new outboundQueueCollection();
|
435d95c3b9dfea9d3bc22f528a8c613a383a06da
|
TypeScript
|
ilanuk/programming-with-types
|
/Chapter11/17_functor_interface.ts
| 3.71875
| 4
|
namespace FunctorInterface {
/*
TypeScript doesn't support HKT
interface Functor<H<T>> {
map<U>(func: (value: T) => U): H<U>;
}
class Box<T> implements Functor<Box<T>> {
value: T;
constructor(value: T) {
this.value = value;
}
map<U>(func: (value: T) => U): Box<U> {
return new Box(func(this.value));
}
}
*/
}
|
21bd3d73590c2433dec2e9b0a608d6f08e4438db
|
TypeScript
|
surikaterna/saft
|
/test/module.spec.ts
| 3.1875
| 3
|
import { Provides, Inject, Provider, Singleton, Injector } from '../src';
describe('Injector', () => {
describe('Provides', () => {
it('should return correct instance', () => {
class MyModule {
@Provides('Aloha')
getAloha() {
return 'Tjingeling';
}
}
const injector = new Injector(new MyModule());
expect(injector.get('Aloha')).toBe('Tjingeling');
});
it('should return correct instance with multiple provides', () => {
class MyModule {
@Provides('Aloha')
getAloha() {
return 'Tjingeling';
}
@Provides('Hawaii')
getHawaii() {
return 'Tjo';
}
}
const injector = new Injector(new MyModule());
expect(injector.get('Aloha')).toBe('Tjingeling');
expect(injector.get('Hawaii')).toBe('Tjo');
});
it('should call provides method with correct this', () => {
class MyModule {
private readonly _message: string;
constructor(message: string) {
this._message = message;
}
@Provides('Aloha')
getAloha() {
return this._message;
}
}
const injector = new Injector(new MyModule('Hi Ho'));
expect(injector.get('Aloha')).toBe('Hi Ho');
});
it('should throw when Provides function needs arguments but no Inject', () => {
class MyModule {
@Provides('Hello')
getHelloWorld(aloha: string) {
return `Tjo ${aloha}`;
}
}
expect(() => {
const injector = new Injector(new MyModule());
injector.get('Hello');
}).toThrow();
});
it('should throw when Provides has more params then Inject specifies', () => {
class MyModule {
@Provides('Hello')
@Inject('test')
getHelloWorld(aloha: string) {
return `Tjo ${aloha}`;
}
}
expect(() => {
const injector = new Injector(new MyModule());
injector.get('Hello');
}).toThrow()
});
it('should inject dependencies to provides method', () => {
class MyModule {
@Provides('Aloha')
getAloha() {
return 'Tjingeling';
}
@Provides('Hello')
@Inject('Aloha')
getHelloWorld(aloha: string) {
return `Tjo ${aloha}`;
}
}
const injector = new Injector(new MyModule());
expect(injector.get('Hello')).toBe('Tjo Tjingeling');
});
it('should inject dependencies as provider to provides method', () => {
class MyModule {
@Provides('Aloha')
getAloha() {
return 'Tjingeling';
}
@Provides('Hello')
@Inject(Provider('Aloha'))
getHelloWorld(aloha: () => string) {
return `Tjo ${aloha()}`;
}
}
const injector = new Injector(new MyModule());
expect(injector.get('Hello')).toBe('Tjo Tjingeling');
});
it('should inject same instance for Singleton', () => {
class MyModule {
private _id: number;
constructor() {
this._id = 11;
}
@Provides('counter')
@Singleton()
getCounter() {
return this._id++;
}
}
const injector = new Injector(new MyModule());
const c1 = injector.get('counter');
const c2 = injector.get('counter');
expect(c1).toBe(c2);
});
it('should call configure on module', (done) => {
class MyModule {
configure() {
done();
}
}
new Injector(new MyModule());
});
});
});
|
5687d3118ac75392f22688b7484ec6b61b22db0f
|
TypeScript
|
dhamotharang/previous_projects
|
/Phantom_Riskpal/clientPortalNg6/src/app/core/services/constant.type.ts
| 2.890625
| 3
|
export class ConstantType {
public static limit = 15;
public static sortCreatedAtDesc = { createdAt: 'desc' };
public static textMinLength = 2; // min length defined for text like fullname, department name, first name etc
public static textMaxLength = 200; // max length defined for text like fullname, department name, first name etc
public static emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
public static specialCharactorPattern = /^[ _?\w\s]+$/;
public static templateNameLength = 32;
public static urlPattern = "https?://.+";
public static mobileNo = /^[+][1-9][0-9]{1}/ ;
// This function is to formate array of object where '_id' is the key and value of the _id is object's Id
// specifically while using ng select
public static formateData(data, formatArray) {
formatArray = [];
for (let id of data) {
formatArray.push({ _id: id._id });
}
return formatArray;
}
// get all ids into an array from array of object.
public static getItemIds(data, formateArray) {
formateArray = [];
for (let item of data) {
formateArray.push(item._id);
}
return formateArray;
}
}
|
af6fa278f6db3e1282880044bf17c1391fc14ec5
|
TypeScript
|
nguyer/aws-sdk-js-v3
|
/packages/util-user-agent-browser/src/index.spec.ts
| 2.71875
| 3
|
import { defaultUserAgent, appendToUserAgent } from ".";
it("should response basic node default user agent", () => {
let originUserAgent = "";
if (typeof navigator === "undefined") {
navigator = {} as any;
originUserAgent = "foo/1.0";
(navigator.userAgent as any) = originUserAgent;
} else {
originUserAgent = navigator.userAgent;
}
expect(defaultUserAgent("client-s3-node", "0.1.0")).toBe(
`aws-sdk-js-v3-client-s3-node/0.1.0 ${originUserAgent}`
);
});
it("append to user agent", () => {
const defaultValue = defaultUserAgent("client-s3-node", "0.1.0");
const request = {
headers: { "X-Amz-User-Agent": defaultValue },
method: "GET",
protocol: "json",
hostname: "foo.amazonaws.com",
path: "/"
};
appendToUserAgent(request, "http/2.0");
expect(request.headers["X-Amz-User-Agent"]).toBe(`${defaultValue} http/2.0`);
});
it("append custom user agent when existing user agent was undefined", () => {
const request = {
headers: { "X-Amz-User-Agent": undefined as any },
method: "GET",
protocol: "json",
hostname: "foo.amazonaws.com",
path: "/"
};
appendToUserAgent(request, "http/2.0");
expect(request.headers["X-Amz-User-Agent"]).toBe("http/2.0");
});
|
1cc1948ac82be20d5319c9c203d93322f7cb069c
|
TypeScript
|
angular/angular-cn
|
/public/docs/_examples/universal/ts/src/uni/universal-engine.ts
| 2.515625
| 3
|
/**
* Express/Connect middleware for rendering pages using Angular Universal
*/
import * as fs from 'fs';
import { renderModuleFactory } from '@angular/platform-server';
const templateCache = {}; // cache for page templates
const outputCache = {}; // cache for rendered pages
export function ngUniversalEngine(setupOptions: any) {
return function (filePath: string, options: { req: Request }, callback: (err: Error, html: string) => void) {
let url: string = options.req.url;
let html: string = outputCache[url];
if (html) {
// return already-built page for this url
console.log('from cache: ' + url);
callback(null, html);
return;
}
console.log('building: ' + url);
if (!templateCache[filePath]) {
let file = fs.readFileSync(filePath);
templateCache[filePath] = file.toString();
}
// render the page via angular platform-server
let appModuleFactory = setupOptions.bootstrap[0];
renderModuleFactory(appModuleFactory, {
document: templateCache[filePath],
url: url
}).then(str => {
outputCache[url] = str;
callback(null, str);
});
};
}
|
fb04041c0c11ebfa6e72a03131698cd670cd16e2
|
TypeScript
|
lucified/minard-ui
|
/src/js/modules/commits/reducer.ts
| 2.5625
| 3
|
import { mapKeys } from 'lodash';
import { Reducer } from 'redux';
import { logMessage } from '../../logger';
import { FetchError, isFetchError } from '../errors';
import Requests from '../requests';
import { CLEAR_STORED_DATA } from '../user';
import { ADD_DEPLOYMENT_TO_COMMIT, STORE_COMMITS } from './actions';
import {
AddDeploymentToCommitAction,
Commit,
CommitState,
StoreCommitsAction,
} from './types';
const initialState: CommitState = {};
const reducer: Reducer<CommitState> = (state = initialState, action: any) => {
let commits: Commit[];
let commit: Commit | FetchError | undefined;
let id: string;
switch (action.type) {
case Requests.actions.Commits.LoadCommit.FAILURE.type:
const responseAction = action as FetchError;
id = responseAction.id;
commit = state[id];
if (!commit || isFetchError(commit)) {
return {
...state,
[id]: responseAction,
};
}
logMessage('Fetching failed! Not replacing existing commit entity', {
action,
});
return state;
case ADD_DEPLOYMENT_TO_COMMIT:
const addDeploymentAction = action as AddDeploymentToCommitAction;
id = addDeploymentAction.id;
const deployment = addDeploymentAction.deployment;
commit = state[id];
if (commit && !isFetchError(commit)) {
if (commit.deployment !== deployment) {
return {
...state,
[id]: {
...commit,
deployment,
},
};
}
return state;
}
console.warn(
'Trying to add deployment to commit that does not exis',
action,
);
return state;
case STORE_COMMITS:
commits = (action as StoreCommitsAction).entities;
if (commits && commits.length > 0) {
const newCommitsObject: CommitState = mapKeys(commits, c => c.id);
return {
...state,
...newCommitsObject,
};
}
return state;
case CLEAR_STORED_DATA:
return initialState;
default:
return state;
}
};
export default reducer;
|
5690a58c9b1342f8054c75dd9adb3cc8c9019e96
|
TypeScript
|
zhoumingyang/PlumeGL
|
/src/example/shader/test_frag_webgl2.ts
| 2.609375
| 3
|
export const testFragmentSource =
`#version 300 es
precision highp float;
precision highp int;
#define LIGHT_NUMBER 5
in vec2 vUv;
in vec3 vPos;
in vec3 vNormal;
uniform vec3 diffuse;
struct Light {
vec3 color;
float intensity;
};
uniform Light lights[LIGHT_NUMBER];
out vec4 glColor;
void main() {
vec3 uvColor = vec3(vUv.x / 10.0, vUv.y / 10.0, 0.5);
vec3 posColor = vPos.xyz / 10.0;
vec3 normalColor = vNormal / 10.0;
vec3 tmpColor = vec3(1.0, 1.0, 1.0);
for(int i = 0; i < LIGHT_NUMBER; i++) {
tmpColor *= (lights[i].color.rgb * lights[i].intensity);
}
tmpColor *= diffuse;
vec3 totalColor = uvColor * posColor * normalColor * tmpColor;
glColor = vec4(totalColor.x, totalColor.y, totalColor.z, 1.0);
}`;
|
27c136967a707c3bc920376f5f6a24f67fb1db0b
|
TypeScript
|
xiong35/type-challenges-solutions
|
/src/0016-Pop-medium/index.ts
| 3.640625
| 4
|
namespace T0016 {
/* 答案 */
type Pop<T extends any[]> = T extends [...(infer P), any] ? P : unknown;
type Shift<T extends any[]> = T extends [any, ...(infer S)] ? S : unknown;
type Push<T extends any[], E> = [...T, E];
type Unshift<T extends any[], E> = [E, ...T];
/* 测试 */
type arr1 = ["a", "b", "c", "d"];
type arr2 = [3, 2, 1];
type pop1 = Pop<arr1>; // expected to be ['a', 'b', 'c']
type pop2 = Pop<arr2>; // expected to be [3, 2]
type shift1 = Shift<arr1>; // expected to be ['b', 'c', 'd']
type shift2 = Shift<arr2>; // expected to be [2, 1]
type push1 = Push<arr1, "e">; // expected to be ['a', 'b', 'c', 'd', 'e']
type push2 = Push<arr2, 0>; // expected to be [3, 2, 1, 0]
type unshift1 = Unshift<arr1, "foo">; // expected to be ['foo', 'a', 'b', 'c', 'd']
type unshift2 = Unshift<arr2, 4>; // expected to be [4, 3, 2, 1]
}
|
bbeb6d4d72e6369699e50dde3dcfc880f0e2ed05
|
TypeScript
|
CoderCow/c2j-Player
|
/src/ts/Utils/TemplateUtils.ts
| 2.75
| 3
|
module Player {
'use strict';
/** Provides utility methods for Dust template management. */
export class TemplateUtils {
/** Asynchronously renders the dust template with the given name and contextData. */
public static render(templateName: string, contextData: any, callback: (out: string) => void): void {
dust.render(templateName, contextData, (err: any, out: string) => {
if (err)
alert(`Error on rendering template "${templateName}".\n${err.toString()}`);
callback(out);
});
}
/** Synchronously renders the dust template with the given name and contextData. */
public static renderSynch(templateName: string, contextData: any): string {
var _out: string;
dust.render(templateName, contextData, (err: any, out: string) => {
if (err)
alert(`Error on rendering template "${templateName}".\n${err.toString()}`);
_out = out;
});
return _out;
}
}
}
|
2604edfc8cb33a8a6841be6b8dbae7133809ac89
|
TypeScript
|
xiaodemen/vue
|
/src/core/instance/render-helpers/bind-object-props.ts
| 2.625
| 3
|
import config from 'core/config'
import {
warn,
isObject,
toObject,
isReservedAttribute,
camelize,
hyphenate,
isArray
} from 'core/util/index'
import type { VNodeData } from 'types/vnode'
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
export function bindObjectProps(
data: any,
tag: string,
value: any,
asProp: boolean,
isSync?: boolean
): VNodeData {
if (value) {
if (!isObject(value)) {
__DEV__ &&
warn('v-bind without argument expects an Object or Array value', this)
} else {
if (isArray(value)) {
value = toObject(value)
}
let hash
for (const key in value) {
if (key === 'class' || key === 'style' || isReservedAttribute(key)) {
hash = data
} else {
const type = data.attrs && data.attrs.type
hash =
asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {})
}
const camelizedKey = camelize(key)
const hyphenatedKey = hyphenate(key)
if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {
hash[key] = value[key]
if (isSync) {
const on = data.on || (data.on = {})
on[`update:${key}`] = function ($event) {
value[key] = $event
}
}
}
}
}
}
return data
}
|
d70b0e002b2fb28e2d402951fb1be8e24c2cd8af
|
TypeScript
|
coco-Tang/ttcar-vue-ts-vant
|
/src/typings/common.d.ts
| 2.859375
| 3
|
/*
* @Author: coco-Tang
* @Date: 2019-10-14 10:51:46
* @LastEditors: coco-Tang
* @LastEditTime: 2019-10-22 13:44:22
* @Description:
*/
// 公共类型
declare namespace TTCAR {
/** 用户信息 */
export interface UserEntity {
userid: number; // 用户 id
usercode: string; // user code
username: string; // 用户名
schoolid: number; // 学校 id
source?: number; // 来源 id
category: 0 | 1 | 2 | 3; // 分类 id
address?: string; // 地址
birthday?: string; // 生日
created_at: number; // 创建时间
email: string; // 邮箱
gender: number; // 性别
tel: string; // 电话
photo?: string; // 头像
fullPath?: string; // 头像图片地址
classid?: number; // 班级id
loginname?: string; // 用户别名
// acl?: UserAuthMapType; // 权限映射表
// aclrole?: UserRoleType[]; // 角色信息
// true: 包含角色不需要跳转到设置班级页面
// false: 没有对应角色信息,需跳转到班级设置页面
hasRole?: boolean;
// 是否有设置班级
hasClassinfo?: boolean;
}
/* ============================ services 类型 ============================ */
/**
* 返回数据
*
* @export
* @interface AjaxResponseType
*/
export interface AjaxResponseType {
readonly code: string; // 状态码
readonly msg: string; // 信息
readonly token?: string; // token
readonly data: any; // 具体数据
}
/** 登录接口的返回数据 */
export interface LoginAjaxResponseType {
readonly code: string; // 状态码
readonly message: string; // 信息
readonly token?: string; // token
readonly data: null; // 用户信息
}
/**
* 返回数据的 page 数据
*
* @export
* @interface ResponsePageType
*/
export interface ResponsePageType {
cur: number; // 当前页
line: number; // 每页条数
total: number; // 总数
}
/**
* 状态返回的数据
*
* @export
* @interface ResponseStatusType
*/
export interface ResponseStatusType {
status: boolean;
message: string;
}
/**
* 状态返回的数据 (会携带数据)
*
* @export
* @interface ResponseStatusAndDataType
*/
export interface ResponseStatusAndDataType<T> {
status: boolean;
message: string;
data: T;
}
/**
* get 请求参数
*
* @export
* @interface GetConfigType
*/
export interface GetConfigType {
url: string;
params?: any;
}
/**
* post 请求参数
*
* @export
* @interface PostConfigType
*/
export interface PostConfigType {
url: string;
data?: any;
json?: boolean;
}
/** 学期 */
export interface TermType {
termid: number; // 学期 id
termname: string; // 学期名称
iscurrent?: number; // 是否为当前学期: 1 : 是当前学期; 0 : 不是当前学期
}
/** 携带学期信息的用户信息 */
export interface UserEntityAndTermInfoType {
userEntity: UserEntity;
termVos: TermType[];
}
}
|
0258b40cd6eb88ce73b23abc913d233e4a47e7f3
|
TypeScript
|
bcgov/moh-prime
|
/prime-angular-frontend/src/app/modules/site-registration/shared/services/organization.service.ts
| 2.71875
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Organization } from '@registration/shared/models/organization.model';
/**
* @description
* Service is considered a source of truth and should be set
* directly from a HTTP response.
*/
export interface IOrganizationService {
organization$: Observable<Organization | null>;
organization: Organization | null;
}
@Injectable({
providedIn: 'root'
})
export class OrganizationService implements IOrganizationService {
// eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle, id-blacklist, id-match
private _organization: BehaviorSubject<Organization>;
constructor() {
this._organization = new BehaviorSubject<Organization>(null);
}
public set organization(organization: Organization) {
// Store a copy to prevent updates by reference
this._organization.next((organization) ? { ...organization } : null);
}
public get organization(): Organization | null {
// Allow access to current value, but prevent updates by reference
const value = this._organization.value;
return (value) ? { ...this._organization.value } : null;
}
public get organization$(): Observable<Organization | null> {
// Allow subscriptions, but make the subject immutable
return this._organization.asObservable();
}
}
|
94f6c90d8bcb1a6a6c40c8e8eea6950bcbcf0832
|
TypeScript
|
ThinhTranA/font-icon-to-csharp
|
/src/utils/stringUtils.ts
| 3.3125
| 3
|
export function toUnicodeString(unicode: number) {
let unicodeString = unicode.toString(16);
let prefix;
if (unicodeString.length <= 4) {
unicodeString = unicodeString.padStart(4, '0');
prefix = 'u';
} else {
unicodeString = unicodeString.padStart(8, '0');
// Using codepoints from the upper bit planes (codes >= 0x10000) require a capital U to get properly encoded into a string literal
prefix = 'U';
}
return `\\${prefix}${unicodeString}`;
}
|
aba23133b2a5146a9612fcd5781ad39eb0a0cac9
|
TypeScript
|
Braw115/yuefanba
|
/src/dinner-srv/ts/deamon/deed/index.ts
| 2.53125
| 3
|
import * as winston from "winston"
import { Deed } from "../../model/users/deed"
import { Users } from "../../model/users/users"
import { System } from "../../model/crm/system"
import { PayLog } from "../../model/users/paylog"
const DEED_TIME_INTERVAL = 300
const DEED_FETCH_INTERVAL = DEED_TIME_INTERVAL * 1000 * 60
export async function init(map: { deamonNotifyMap: Map<string, Function>, deamonGetMap: Map<string, Function> }) {
CheckDeedIsTimeout.getInstance().run()
}
function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
class CheckDeedIsTimeout {
private static instance = new CheckDeedIsTimeout()
private constructor() { }
public static getInstance() {
return CheckDeedIsTimeout.instance
}
private async deedIsTimeout(): Promise<any> {
let deposit = await System.getInstance().findOne('deposit')
deposit = parseInt(deposit.value.deposit)
let notTimeoutList = await Deed.getInstance().findByObj({ istimeout: "false", state: "false", del: "false" })
if (notTimeoutList.length === 0) return { "msg": "无未过期且未匹配契约单" }
for (let index = 0; index < notTimeoutList.length; index++) {
let r = notTimeoutList[index];
let user = await Users.getInstance().findByPrimary(r.useruuid)
let payType
let description
if (r.type === "spend") {
deposit = r.deposit
payType = "backdeed"
description = "赏金"
} else if (r.type === "make") {
payType = "depositback"
description = "押金"
} else {
payType = "depositback"
description = "押金"
}
let mealtime = r.mealtime
let deedtime = parseInt(mealtime[1])
let nowtime = new Date().getTime()
if (nowtime > deedtime) {
await Deed.getInstance().update({ istimeout: "true" }, r.uuid)
//退还吃货币
await Users.getInstance().updateByUuid(r.useruuid, { balance: user.balance + deposit })
let paylogObj = { useruuid: r.useruuid, type: payType, deeduuid: r.uuid, coin: deposit, description: `契约单过期未匹配,回退相应的${description}` }
await PayLog.getInstance().add(paylogObj)
}
}
return { "msg": "检测契约单是否过期完毕" }
}
public async run() {
while (true) {
await sleep(DEED_FETCH_INTERVAL)
try {
await this.deedIsTimeout()
} catch (e) {
winston.error(`check deed is timeout manager fail. ${e.message}`)
}
}
}
}
|
f9d826f0587cc097960f68017de7e314df745b0e
|
TypeScript
|
vncnzd/genealogy-visualizer
|
/src/typescript/models/person.ts
| 3.09375
| 3
|
import { SexOrGender } from "../sexOrGender";
import { SexOrGenderId } from "../sexOrGenderId";
export class Person {
private id: string;
private name: string;
private description: string;
private father: Person;
private mother: Person;
private children: Person[];
private datesOfBirth: Date[];
private datesOfDeath: Date[];
private sexOrGender: SexOrGender;
constructor(id: string) {
this.id = id;
this.datesOfBirth = [];
this.datesOfDeath = [];
this.children = [];
}
public deleteAndRemoveReferences(): void {
if (this.father != null) {
const indexOfThisPerson: number = this.father.getChildren().indexOf(this);
this.father.setChildren(this.father.getChildren().splice(indexOfThisPerson, 1));
}
if (this.mother != null) {
const indexOfThisPerson: number = this.mother.getChildren().indexOf(this);
this.mother.setChildren(this.mother.getChildren().splice(indexOfThisPerson, 1));
}
for (const child of this.children) {
if (child.father == this) {
child.father = null;
} else if (child.mother == this) {
child.mother = null;
}
}
}
public removeChildrenAndParents(): void {
this.children.length = 0;
this.father = null;
this.mother = null;
}
public setId(id: string, suffix: string = null): void {
if (suffix != null) {
this.id = id + "-" + suffix;
} else {
this.id = id;
}
}
public getId(): string {
return this.id;
}
public getBaseId(): string {
return this.id.split("-")[0];
}
public setName(name: string): void {
this.name = name;
}
public getName(): string {
return this.name;
}
public setDescription(description: string): void {
this.description = description;
}
public getDescription(): string {
return this.description
}
public getFather(): Person {
return this.father;
}
public setFather(father: Person): void {
this.father = father;
}
public getMother(): Person {
return this.mother;
}
public setMother(mother: Person): void {
this.mother = mother;
}
public getChildren(): Person[] {
return this.children;
}
public setChildren(children: Person[]): void {
this.children = children;
}
public getDatesOfBirth(): Date[] {
return this.datesOfBirth;
}
public getDatesOfDeath(): Date[] {
return this.datesOfDeath;
}
public setSexOrGender(sexOrGender: SexOrGender): void {
this.sexOrGender = sexOrGender;
}
public getSexOrGender(): SexOrGender {
return this.sexOrGender;
}
public setParent(person: Person) {
if (person.getSexOrGender().getSexOrGenderId() == SexOrGenderId.female) {
this.setMother(person);
} else if (person.getSexOrGender().getSexOrGenderId() == SexOrGenderId.male) {
this.setFather(person);
}
}
}
|
cd7db0eea99dd25ad1c3004b11713ab767ca841e
|
TypeScript
|
OisinKyne/EthTransactionMap
|
/frontend/src/app/validators/transaction-list.validator.ts
| 3.09375
| 3
|
import { AbstractControl } from '@angular/forms';
export function ValidateHashes(control: AbstractControl) {
if (control.value) {
//Parse the field to see if a valid set of hashes has been supplied.
let hashes: string[];
try {
const csv = parseCSV(control.value);
}
catch (e) {
console.log('Exception thrown validating: ' + control.value)
console.log(e);
return { validHashes: true };
}
}
return null;
}
function parseCSV(input: string) {
const cleanedHashes: string[] = [];
try {
// Need CSV splitter here and another helper to verify that hashes are the correct format.
const hashes = input.split(',');
for (const hash of hashes) {
const cleanedHash = hash.replace(/[\W_]+/g, "");
if (parseHash(cleanedHash)) {
cleanedHashes.push(cleanedHash);
}
}
} catch {
console.log('Unknown error parsing CSV hashes.')
}
if (cleanedHashes.length === 0) {
// Throw an error if we didn't parse a single hash.
throw new ErrorEvent('No valid hashes supplied.');
}
}
//Function to verify that a given item is a valid transaction hash.
function parseHash(input: string): boolean {
const hexRegEx = new RegExp(/0[xX][0-9A-Fa-f]{64}/);
return hexRegEx.test(input);
}
|
7fb0c914aa00f9b1d8e8a1680ef40e27ae832bc0
|
TypeScript
|
EvgenyKalyuk/js-patterns
|
/src/strategy/index.ts
| 2.640625
| 3
|
import { IStrategy } from './strategy.interface';
export class Context {
constructor(private _strategy: IStrategy) {}
set strategy(strategy: IStrategy) {
this._strategy = strategy;
}
public doSomeLogic(args: Array<string>): Array<string> {
return this._strategy.doAlgorithm(args);
}
}
|
9e39b2dc185baf5621c83f4afeeeffb9525b1816
|
TypeScript
|
gannochenko/generators
|
/__deprecated/application.gatsby/template/[application_code_kebab]/src/components/default/[content_name_pascal]Detail/hooks/useCombinedData.ts
| 2.609375
| 3
|
import { HeritageObjectDetailType } from '../type';
import { normalizeHeritageObject } from '../../../../services/HeritageObject/normalize';
import { makePublicPath } from '../../../../util/makePublicPath';
import { HeritageObjectType } from '../../../../services/HeritageObject/type';
export const useCombinedData = (
currentData?: HeritageObjectDetailType,
newData?: HeritageObjectType,
) => {
if (!newData) {
return currentData;
}
const normalNewData = normalizeHeritageObject(
newData,
) as HeritageObjectDetailType;
const newHeader = normalNewData.photos.find((photo) => photo.header);
if (newHeader) {
// check if there was a gatsby image generated before
const headerUrlPart = newHeader.variants.normalized;
if (currentData?.headerPhotoImage) {
if (currentData.headerPhotoImage.url.includes(headerUrlPart)) {
// same header as before
normalNewData.headerPhotoImage = currentData.headerPhotoImage;
} else {
normalNewData.headerPhotoImage = {
url: makePublicPath(headerUrlPart),
};
}
}
}
// take all pictures and find gatsby images for them, if available
normalNewData.photoImages = normalNewData.photos.map((photo) => {
return {
url: makePublicPath(photo.variants.normalized),
};
});
// console.log('new data');
// console.log(newData);
console.log('normal new data');
console.log(normalNewData);
console.log('current data');
console.log(currentData);
return normalNewData;
};
|
78d904d4ff7f1aafa473ab2c0312da785f86645d
|
TypeScript
|
meenniam/fastify-decorators-boilerplate
|
/src/modules/hello/hello.schema.ts
| 2.578125
| 3
|
import { Static, Type } from '@sinclair/typebox';
import { FastifyRequest } from 'fastify';
export const HelloTypes = Type.Object({
name: Type.String(),
mail: Type.Optional(Type.String({ format: 'email' })),
age: Type.Optional(Type.Number())
});
export const HelloParamsTypes = Type.Object({
helloId: Type.String()
});
export type HelloBodyType = Static<typeof HelloTypes>;
export type HelloParamsType = Static<typeof HelloParamsTypes>;
export type HelloRequest = FastifyRequest<{
Body: HelloBodyType;
Params: HelloParamsType;
}>;
// schema
export const helloSchema = {
body: HelloTypes,
response: {
201: {
type: 'object',
properties: {
data: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
}
},
code: { type: 'number' }
}
}
}
};
|
27619b1fb79278eb4b096c959a72e00ab2a1945d
|
TypeScript
|
SomeGuy3000/scraper-interview
|
/src/otomoto/otomotoScraper.ts
| 2.671875
| 3
|
import { Credentials } from "../models/credentials.model";
import { Page } from "puppeteer";
import { FuelType, Offer, TransmissionType } from "../models/offer.model";
import { Context } from "../models/context.model";
import { runInPage } from "../scraping/runInPage";
import { getWatchedOffersTitledLinks, scrapeOffer } from "./otomotoFunctions";
export class OtomotoScraper {
constructor(private readonly pageFactory: () => Promise<Page>) {}
async scrape(credentials: Credentials): Promise<Offer[]> {
return runInPage(this.pageFactory, async (page: Page) => {
await this.login(page, credentials);
const titledLinks = await this.getWatchedOffersTitledLinks(page);
return await this.scrapeLinks(page, titledLinks);
});
}
private async scrapeLinks(page: Page, titledLinks: TitledLink[]) {
const offers: Offer[] = [];
for (const titledLink of titledLinks) {
const offer = await this.scrapeOffer(page, titledLink);
offers.push(offer);
}
return offers;
}
private async login(page: Page, credentials: Credentials) {
await page.goto("https://www.otomoto.pl/konto/");
await page.type("#current-email", credentials.username);
await page.type("#current-password", credentials.password);
await Promise.all([
page.waitForNavigation(),
page.evaluate(() =>
(document.querySelector(
"[data-testid=sign-in-button]"
) as HTMLButtonElement).click()
),
]);
}
private async getWatchedOffersTitledLinks(page: Page): Promise<TitledLink[]> {
await page.goto("https://www.otomoto.pl/obserwowane");
return await page.evaluate(getWatchedOffersTitledLinks);
}
private async scrapeOffer(page: Page, titledLink: TitledLink) {
await page.goto(titledLink.link);
const context: Context = {
data: {
title: titledLink.title,
},
extras: {
FuelType,
TransmissionType,
},
};
return await page.evaluate(scrapeOffer, { ...context });
}
}
interface TitledLink {
title: string;
link: string;
}
|
e62ec93a84cc8fed37096a96ae3db973ebdf9ea9
|
TypeScript
|
Shrkawy/audio-player
|
/hooks/audio-player-context-hook.ts
| 2.65625
| 3
|
import { useReducer } from "react";
import { Song } from "../models/Song";
import { playerReducer } from "./player-reducer";
export interface PlayerState {
songs: Song[];
currentSong: number;
}
const initPlayerState: PlayerState = {
songs: [],
currentSong: 0,
};
export const usePlayer = () => {
const [playerState, dispatch] = useReducer(playerReducer, initPlayerState);
return { playerState, dispatch };
};
|
e7d300364744b640bc9f589b68e01b8e8d4523a7
|
TypeScript
|
antiwise/GameTemplateTS
|
/assets/scripts/framework/godGuide/GodCommand.ts
| 2.703125
| 3
|
import GodGuide from "./GodGuide";
/**
* zxh
*/
let async = require('async');
//根据命令
export class GodCommand {
static readonly DIALOGUE: string = 'dialogue';//对话框
static readonly FINGER: string = 'finger';//节点定位加手指指引
static readonly TEXT: string = 'text';//文本显示
static readonly LOCATOR: string = 'locator';//节点定位
static readonly SAVE: string = 'save';//保存进度
static readonly typeList = [GodCommand.DIALOGUE, GodCommand.FINGER, GodCommand.TEXT, GodCommand.LOCATOR, GodCommand.SAVE];
//定位节点
static locator(godGuide, step, callback) {
let { args } = step.command;
godGuide.find(args, (node) => {
godGuide._targetNode = node;
//点击确认
node.once(cc.Node.EventType.TOUCH_END, () => {
cc.log('节点被点击');
//任务完成
callback();
});
//触摸模拟
let autorun = godGuide.getTask().autorun;
if (autorun) {
godGuide.touchSimulation(node);
}
});
}
//定位节点,显示一个手指动画
static finger(godGuide, step, callback) {
let { args } = step.command;
godGuide._targetNode = null;
//定位节点
godGuide.find(args, (node) => {
//手指动画
godGuide.fingerToNode(node, () => {
godGuide._targetNode = node;
//点击确认
node.once(cc.Node.EventType.TOUCH_END, () => {
cc.log('节点被点击');
//任务完成
callback();
});
});
//触摸模拟
let autorun = godGuide.getTask().autorun;
if (autorun) {
godGuide.touchSimulation(node);
}
});
}
//文本指令
static text(godGuide, step, callback) {
let { args } = step.command;
if (args && (typeof args === 'string' || typeof args === 'number')) {
args = [args];
}
//触摸模拟
let autorun = godGuide.getTask().autorun;
let index = 0;
//顺序显示文本
async.eachSeries(args, (str, cb) => {
let flag = false;
godGuide.showText(str, () => {
if (flag) {
return;
}
flag = true;
cb();
});
if (index++ >= args.length - 1) {
flag = true;
cb();
return;
}
//自动引导
if (autorun) {
setTimeout(() => {
if (flag) {
return;
}
flag = true;
cb();
}, 1000);
}
}, callback);
}
// //文本指令
// static text(godGuide: GodGuide, step, callback) {
// let { args } = step.command;
// if (args && (typeof args === 'string' || typeof args === 'number')) {
// args = [args];
// }
// //触摸模拟
// let autorun = godGuide.getTask().autorun;
// let index = 0;
// //顺序显示文本
// async.eachSeries(args, (str, cb) => {
// let flag = false;
// let next = () => {
// if (++index >= args.length - 1) {
// flag = true;
// console.log('step------------->',step)
// cb();
// return;
// } else {
// if (flag) {
// return;
// }
// flag = true;
// cb();
// }
// }
// godGuide.showText(str, () => {//点击回调
// next();
// });
// //自动引导
// if (autorun) {
// setTimeout(() => {
// next();
// }, 1000);
// }
// }, callback);
// }
//对话框
static dialogue(godGuide, step, callback) {
let { args } = step.command;
if (args && (typeof args === 'string' || typeof args === 'number')) {
args = [args];
}
//触摸模拟
let autorun = godGuide.getTask().autorun;
let index = 0;
//顺序显示文本
async.eachSeries(args, (str, cb) => {
let flag = false;
let next = () => {
if (++index >= args.length - 1) {
godGuide._dialogue.active = false;
flag = true;
cb();
return;
} else {
if (flag) {
return;
}
flag = true;
godGuide._dialogue.active = false;
cb();
}
}
godGuide.showDialogue(str, () => {//点击回调
next();
});
//自动引导
if (autorun) {
setTimeout(() => {
if (flag) {
return;
}
flag = true;
cb();
}, 10000);
}
}, callback);
}
};
|
7aa965ed12d811f7e56db8a375b1a49655a6b6a7
|
TypeScript
|
automaticdreams/nest_example
|
/src/services/films/sortedfilm.service.spec.ts
| 2.59375
| 3
|
import { Test, TestingModule } from '@nestjs/testing';
import { SortedfilmService } from './sortedfilm.service';
import * as testArrays from '../../../test/testArrays'
import { FilmsService } from './films.service'
import { of } from 'rxjs'
import { AxiosResponse } from 'axios'
import * as functions from '../../common/functions'
class FilmServiceMock {
getFilms () {
return of(testArrays.fullArr)
}
}
jest.mock('../../common/functions')
describe('SortedfilmService', () => {
let service: SortedfilmService;
let filmservice: FilmsService;
beforeEach(async () => {
const FilmServiceProvider = {
provide: FilmsService,
useClass: FilmServiceMock
}
const module: TestingModule = await Test.createTestingModule({
providers: [SortedfilmService, FilmServiceProvider],
}).compile();
service = module.get<SortedfilmService>(SortedfilmService);
filmservice = module.get<FilmsService>(FilmsService);
})
it('should be defined', () => {
expect(service).toBeDefined();
})
it ('should return unsorted array when no params provided', async () => {
service.getSortedFilms().subscribe(resp => {
expect(resp).toStrictEqual(testArrays.unchangedArray)
expect(functions.sort).not.toHaveBeenCalled()
})
})
it ('should call sort function when param provided', () => {
service.getSortedFilms('title').subscribe(resp => {
expect(functions.sort).toHaveBeenCalledWith(testArrays.fullArr, 'title', undefined)
})
})
it ('should limit response when limit provided', () => {
service.getSortedFilms('', '', 5).subscribe(resp => {
expect(resp.length).toBe(5)
})
})
// it ('should return array sorted by title when param: title provided', async () => {
// service.getSortedFilms('title').subscribe(resp => {
// expect(resp).toStrictEqual(testArrays.sortedByTitle)
// })
// })
// it ('should return array of 3 when limit: 3 provided', async () => {
// service.getSortedFilms('','',3).subscribe(resp => {
// expect(resp).toStrictEqual(testArrays.unsortedLimited)
// })
// })
// it ('should return array of 3 sorted by title when param: title and limit: 5 provided', async () => {
// service.getSortedFilms('title','',5).subscribe(resp => {
// expect(resp).toStrictEqual(testArrays.sortedByTitleAndLimited)
// })
// })
})
|
4d18fd284fca95e8bee7e5e56f7d4d181adf77fd
|
TypeScript
|
mckiernantim/FamilrDnd
|
/src/app/no-undead-events.ts
| 2.59375
| 3
|
import { Event } from './event';
import { Component, OnInit } from '@angular/core';
export const noUndeadEvents: Event[] = [
{
id:1,
title:'Albino Dwarves',
text:"The characters are ambushed by 1d4+3 Albino Dwarf Warriors that spring forth from a burrow. Any character with a passive perception above 13 notices the dwarves, everyone else is surprised. The dwarves prefer to knock out players and steal food, gold, gear rather than kill them. They break off their attacks if anyone speaks Dwarvish or shows peaceful intentions.",
monsters:true,
name: "Albino Dwarf",
rolls:1,
die:4,
extra:3,
},
{
id:2,
title:'Almiraj',
text:"Almiraj are small bunny-unicorn things. Amny character with a pass perception of 12 or higher spots 1d6 Almiraj 60 ft away. The almiraj run away from any creature that they can see within 30 ft of them. Any character who sccessfully traps an Almiraj can use an action to make a DC 14 animal handling check. On success the Almiraj becomes tame an will not run away or attack unless it feels thretened or is harmed.",
monsters:true,
name: "Almiraj",
rolls:1,
die:6,
extra:0,
},
{
id:3,
title:'Ape',
text:"Any character with a passive Widsom (perception) score of 15 or higher spots 1d4+1 aarakocra flying overhead. These creatures are scouts from Kir Sabal or another aeire. They observe the party from a safe distance but dont approach unless the characters demonstrate peaceful intentions. The bird folk are friendly and can point characrers in the direction of nearby landmarks.",
monsters:true,
name: "Aarakocra",
rolls:1,
die:4,
extra:1,
},
{
id:4,
title:'Ape',
text:"Any character with a passive Widsom (perception) score of 15 or higher spots 1d4+1 aarakocra flying overhead. These creatures are scouts from Kir Sabal or another aeire. They observe the party from a safe distance but dont approach unless the characters demonstrate peaceful intentions. The bird folk are friendly and can point characrers in the direction of nearby landmarks.",
monsters:true,
name: "Ape",
rolls:2,
die:4,
extra:0,
},
{
id:5,
title:'Artus Climber',
text:"Artus CLimber with or without his saurial traveling companion DragonBait, can be encounterd almost anywhere. He may use the ring of winter to save the characters. He is friendly ",
monsters:true,
name: "Artus Climber",
rolls:1,
die:1,
extra:0,
}
,
{
id:6,
title:'Assassin Vine',
text:"The characters come across the path of 1d4-1 assassin vines. The vines are indistinguishable from normal plants and cannot be spotted by normal perception checks but the plants draw carrion to them so they party may smell dead corpses. At night the plants may snake their wau into the players camp to drag them away",
monsters:true,
name: "Assassin Vine",
rolls:2,
die:4,
extra:-1,
},
{
id:7,
title:'Assassin Vine',
text:"The characters come across the path of 1d4-1 assassin vines. The vines are indistinguishable from normal plants and cannot be spotted by normal perception checks but the plants draw carrion to them so they party may smell dead corpses. At night the plants may snake their wau into the players camp to drag them away",
monsters:true,
name: "Assassin Vine",
rolls:1,
die:4,
extra:-1,
},
{
id:8,
title:'Axe Beaks',
text:"A flock of 1d6 +3 Axe Beaks (big ass murder ostritch birds) come crashing through the jungle. The parrty can hear them before they arrive but can see nothing until the birds are upons them slashing at everything within range. ",
monsters:true,
name: "Axe Beak",
rolls:1,
die:6,
extra:3,
},
{ id: 9,
title:'Baboons ' ,
text: 'A pack of 3d6 baboons take umbrage with the players entering their territory. They can be distracted by tossing them each a days supply of food. Otherwise they attack.',
monsters:false,
name:"Baboon",
rolls:3,
die:6,
extra:0,
} ,
{ id: 10,
title:'Cache',
text: 'The party finds a Cache of supplies left behind by other explorers.',
monsters:false,
name:"",
rolls:0,
die:0,
extra:0,
} ,
{ id: 11,
title:'Cache',
text: 'The party finds a Cache of supplies left behind by other explorers.',
monsters:false,
name:"",
rolls:0,
die:0,
extra:0,
} ,
{
id: 12,
title: 'Cannibals',
text: 'Chultan cannibals prowl the jungle in small groups, killing and eating zombies while steering clear of more powerful, faster undead. Abandoned by their Gods, the cannibals have returned to worship Dendar the night Serpent and they pay tribute to Ras Nsi in exchange for his favor and protection. They have a blue triangle painted on their forehead (Ras Nsi) and do venture into Omu. Day: 3d6 Canibals feast on a zombie, the players see them. Night: The cannibals sneak into the players camp. DC10 Perception check by the player on guard notices.',
monsters:true,
name:'Tribal Warrior',
rolls:3,
die:6,
extra:0} ,
{
id: 13,
title: 'Cannibals',
text: 'Chultan cannibals prowl the jungle in small groups, killing and eating zombies while steering clear of more powerful, faster undead. Abandoned by their Gods, the cannibals have returned to worship Dendar the night Serpent and they pay tribute to Ras Nsi in exchange for his favor and protection. They have a blue triangle painted on their forehead (Ras Nsi) and do venture into Omu. Day: 3d6 Canibals feast on a zombie, the players see them. Night: The cannibals sneak into the players camp. DC10 Perception check by the player on guard notices.',
monsters:true,
name:'Tribal Warrior',
rolls:3,
die:6,
extra:0},
{
id: 14,
title: 'Chwinga',
text: 'A chwinga takes an interest in the characters. It attempts to steal something valuable from an ungauarded pack or canoe but is noticed by any character witha passive perceptin score of 17 or higher. The chwinga always leaves something in return, a pretty shell, some twigs, or an uncut gemstone (10gold)',
monsters:true,
name:'Chwinga',
rolls:1,
die:1,
extra:0
},
{
id: 15,
title: 'Chwinga',
text: 'A chwinga takes an interest in the characters. It attempts to steal something valuable from an ungauarded pack or canoe but is noticed by any character witha passive perceptin score of 17 or higher. The chwinga always leaves something in return, a pretty shell, some twigs, or an uncut gemstone (10gold)',
monsters:true,
name:'Chwinga',
rolls:1,
die:1,
extra:0,
} ,
{ id: 16,
title: 'Cyclops',
text: 'A cyclops is heading towards his home in snapping turtle bay. He is not looking for a fight but any sudden moves or hostility may trigger one. The Cyclops knows the region around Lake Luo and the western end of the Valley of Dread quite well and it has never seen anything like Omu there before.',
monsters:true,
name: "Cyclops",
rolls:2,
die:6,
extra:0
},
{
id: 17,
title: 'Allosaurus',
text: 'Theparty scent atteracts 1d4-1 allorsaurus. Any characters who succeed ona DC 15 Survival check find a safe place to hide, high branch, hole etc, where the "honkers" cant reach them',
monsters:true,
name:'Allosaurus',
rolls:1,
die:4,
extra:-1
} ,
{ id: 18,
title: 'Ankylosaurus',
text: 'An ornery Ankylosaurus (club tail dino) is gorging itself on plants and attacks any thing that gets in its way.',
monsters:true,
name: "",
rolls:1,
die:0,
extra:3,
} ,
{ id: 19,
title: 'Brontosuarus',
text: 'A large brontosaurus lumbers towards the characters. It doesnt notice the party and may step on them but only ifghts back in self defense',
monsters:true,
name: "plsiosaurus",
rolls:1,
die:0,
extra:3,
} ,
{ id: 20,
title: 'Deinonychus',
text: 'A wild boar races bas the party being chased by 1d4+2 deinonychuses the predators decide the characters are more interesting than the prey.',
monsters:true,
name: "Deinonychus",
rolls:1,
die:4,
extra:2,
} ,
{ id: 21,
title: 'Deinonychus',
text: 'A wild boar races bas the party being chased by 1d4+2 deinonychuses the predators decide the characters are more interesting than the prey.',
monsters:true,
name: "Deinonychus",
rolls:1,
die:4,
extra:2,
} ,
{ id: 22,
title: 'Hadrosaurus',
text: 'A herd of 3d6 hadrosauruses are grazing nearby with 1d6 non combatant young. The adults dont attack onless attacked or antagonized. The young are Small beasts that can be sold to Ifan Talroa in Port Nyanzaru for 50 gp each, or for 100gp each if the player succeeds ona dc 15 charisma check. The young dinosaurs are easy to handle if seperated from their parents but the adults fight if their children are captured.',
monsters:true,
name: "Hadrosaurus",
rolls:3,
die:6,
extra:0,
},
{ id: 23,
title: 'Hadrosaurus',
text: 'A herd of 3d6 hadrosauruses are grazing nearby with 1d6 non combatant young. The adults dont attack onless attacked or antagonized. The young are Small beasts that can be sold to Ifan Talroa in Port Nyanzaru for 50 gp each, or for 100gp each if the player succeeds ona dc 15 charisma check. The young dinosaurs are easy to handle if seperated from their parents but the adults fight if their children are captured.',
monsters:true,
name: "Hadrosaurus",
rolls:3,
die:6,
extra:0,
},
{ id: 24,
title: 'Pternadon',
text: 'A fock of 2d6 Pternadon is spotted overhead. They keep their distance and only attak if threatned',
monsters:true,
name: "Hadrosaurus",
rolls:3,
die:6,
extra:0,
} ,
{ id: 25,
title: 'Stegasaurus',
text: 'This lone stegosaurus is in a genial mood and approaches the characters out of curiosity. Anyone who touches it triggers a swipe from its tail.',
monsters:true,
name: "Pternadon",
rolls:2,
die:6,
extra:0,
} ,
{ id: 26,
title: 'Stegasaurus',
text: 'This lone stegosaurus is in a genial mood and approaches the characters out of curiosity. Anyone who touches it triggers a swipe from its tail.',
monsters:true,
name: "Pternadon",
rolls:2,
die:6,
extra:0,
} ,
{ id: 27,
title: 'Triceratops',
text: 'A triceratops who apperas to be grazing alone is actually a mother with a nearby nest containing one noncombatant hatchling and two unhatched eggs. The mother eyes the characters supiciously but doesnt attack unless they position themselves between her and the nest. Ifan Talor in Port Nyanzaru offers 50gp for a young triceratops or an intact egg. Can be talked up to 150 gold on asuccessful Charisma check of 15',
monsters:true,
name: "Triceratops",
rolls:0,
die:0,
extra:1,
} ,
{ id: 28,
title: 'Triceratops',
text: 'A triceratops who apperas to be grazing alone is actually a mother with a nearby nest containing one noncombatant hatchling and two unhatched eggs. The mother eyes the characters supiciously but doesnt attack unless they position themselves between her and the nest. Ifan Talor in Port Nyanzaru offers 50gp for a young triceratops or an intact egg. Can be talked up to 150 gold on asuccessful Charisma check of 15',
monsters:true,
name: "Triceratops",
rolls:0,
die:0,
extra:1,
} ,
{ id: 29,
title: 'Tyranosaurus Rex',
text: 'The characters spot a Tyranosaurus Rex 50 feet away. On an even roll the dinosaur is locked in combat with a triceratops or stegasaurus, giant ape, a pair of giant constrictor snakes, or a mob of ghouls or zombies. These mobs will not assist the players in any way directly but may weaken the creature so it can be killed by the players. The characters can avoid the encounter with all players making a DC 15 stealth check. If any player is proficient in the stealh skill all checks are made with advantage',
monsters:true,
name: "Tyranosaurus",
rolls:1,
die:10,
extra:0,
} ,
{ id: 30,
title: 'Tyranosaurus Rex',
text: 'The characters spot a Tyranosaurus Rex 50 feet away. On an even roll the dinosaur is locked in combat with a triceratops or stegasaurus, giant ape, a pair of giant constrictor snakes, or a mob of ghouls or zombies. These mobs will not assist the players in any way directly but may weaken the creature so it can be killed by the players. The characters can avoid the encounter with all players making a DC 15 stealth check. If any player is proficient in the stealh skill all checks are made with advantage',
monsters:true,
name: "Tyranosaurus",
rolls:1,
die:10,
extra:0,
} ,
{ id: 31,
title: 'Velociraptors',
text: 'A pck of 3d6 velociraptors burst from behind cover and attack. MAke a stealth check for the dinosaurs with advantage. Any character whos passive wisdom is higher than the stealth check is not surprised',
monsters:true,
name:"Velociraptor",
rolls:3,
die:6,
extra:0,
} ,
{ id: 32,
title: 'Velociraptors',
text: 'A pck of 3d6 velociraptors burst from behind cover and attack. MAke a stealth check for the dinosaurs with advantage. Any character whos passive wisdom is higher than the stealth check is not surprised',
monsters:true,
name:"Velociraptor",
rolls:3,
die:6,
extra:0
} ,
{ id: 33,
title: 'Velociraptors',
text: 'A pck of 3d6 velociraptors burst from behind cover and attack. MAke a stealth check for the dinosaurs with advantage. Any character whos passive wisdom is higher than the stealth check is not surprised',
monsters:true,
name:"Velociraptor",
rolls:3,
die:6,
extra:0
} ,
{ id: 34,
title: 'Velociraptors',
text: 'A pck of 3d6 velociraptors burst from behind cover and attack. MAke a stealth check for the dinosaurs with advantage. Any character whos passive wisdom is higher than the stealth check is not surprised',
monsters:true,
name:"Velociraptor",
rolls:3,
die:6,
extra:0
} ,
{ id: 35,
title: 'Velociraptors',
text: 'A pck of 3d6 velociraptors burst from behind cover and attack. MAke a stealth check for the dinosaurs with advantage. Any character whos passive wisdom is higher than the stealth check is not surprised',
monsters:true,
name:"Velociraptor",
rolls:3,
die:6,
extra:0
} ,
{ id: 36,
title: 'Dragon, Faerie',
text: 'An invisible green faerie dragon takes interest in the players and follows them for a while. If the party is in good spirits the dragon plays cute pranks on them while they camp or travel. If the party is not upset at these tricks, the dragon reveals itself and answers three questions truthfully. The dragon recently visited Omu, knows of the -Snake People- who occupy the place. It also knows things about other landmarks or locations as you determine',
monsters:true,
name:"Faerie Dragon",
rolls:0,
die:0,
extra:0,
} ,
{ id: 37,
title: 'Eblis',
text: 'If the party is on the move while this encounter takes place they stumble upone 1d4+1 eblis (evil, reincarnated people as ostritches) living in reed huts built on stilts abouve the swamp, marsh, or pond. The Eblis will attack any weak looking, or sick characters but offer to trade precious gemstones or information if faced with a well armed, healthy group. For 50 gold they point the party in direction of a nearby landmark. If the characters defeat the Eblis and search the huts roll once on the Treasure table. If this encounter occurs while the party is camped, the Eblis sneak into the camp at night and attack.',
monsters:true,
name:"Eblis",
rolls:1,
die:4,
extra:1,
} ,
{ id: 38,
title: 'Emerald Enclave',
text: 'Thecharacters stumble upon a band of Emerald Enclave scouts OR one of their outposts. Choose whichever works best. SCOUTS: The party meets 1d4+1 members of the EMerald Enclave working to rid the jungle of its undead menace. The group works with a priest of Mielikki, but all other members are scouts.' +
"If on of the characters has died recently you can use this to introduce a new character, a member of the emerald enclave, one of the scouts, or someone who has hired the m or been rescued by them. The scouts will trade information on an equal basis with a nopn evil party. The scouts can also be convinced to join the party for three days by succeeding on a DC 12 group Charisma check." +
"OUTPOST: Any character with a passive perception of 13 or higher spots a wooden platform in a tree 2d6 * 5 feet in the air and requires a dc 12 strength check to climb. The platform is sturdy and can hold up to six characters and their gear ",
monsters:true,
name: "Scout",
rolls:1,
die:4,
extra:1,
} ,
{ id: 39,
title: 'Emerald Enclave',
text: 'Thecharacters stumble upon a band of Emerald Enclave scouts OR one of their outposts. Choose whichever works best. SCOUTS: The party meets 1d4+1 members of the EMerald Enclave working to rid the jungle of its undead menace. The group works with a priest of Mielikki, but all other members are scouts.' +
"If on of the characters has died recently you can use this to introduce a new character, a member of the emerald enclave, one of the scouts, or someone who has hired the m or been rescued by them. The scouts will trade information on an equal basis with a nopn evil party. The scouts can also be convinced to join the party for three days by succeeding on a DC 12 group Charisma check." +
"OUTPOST: Any character with a passive perception of 13 or higher spots a wooden platform in a tree 2d6 * 5 feet in the air and requires a dc 12 strength check to climb. The platform is sturdy and can hold up to six characters and their gear ",
monsters:true,
name: "Scout",
rolls:1,
die:4,
extra:1,
} ,
{id: 40,
title: 'Emerald Enclave',
text: 'Thecharacters stumble upon a band of Emerald Enclave scouts OR one of their outposts. Choose whichever works best. SCOUTS: The party meets 1d4+1 members of the EMerald Enclave working to rid the jungle of its undead menace. The group works with a priest of Mielikki, but all other members are scouts.' +
"If on of the characters has died recently you can use this to introduce a new character, a member of the emerald enclave, one of the scouts, or someone who has hired the m or been rescued by them. The scouts will trade information on an equal basis with a nopn evil party. The scouts can also be convinced to join the party for three days by succeeding on a DC 12 group Charisma check." +
"OUTPOST: Any character with a passive perception of 13 or higher spots a wooden platform in a tree 2d6 * 5 feet in the air and requires a dc 12 strength check to climb. The platform is sturdy and can hold up to six characters and their gear ",
monsters:true,
name: "Scout",
rolls:1,
die:4,
extra:1,
} ,
{ id: 41,
title: 'Emerald Enclave',
text: 'Thecharacters stumble upon a band of Emerald Enclave scouts OR one of their outposts. Choose whichever works best. SCOUTS: The party meets 1d4+1 members of the EMerald Enclave working to rid the jungle of its undead menace. The group works with a priest of Mielikki, but all other members are scouts.' +
"If on of the characters has died recently you can use this to introduce a new character, a member of the emerald enclave, one of the scouts, or someone who has hired the m or been rescued by them. The scouts will trade information on an equal basis with a nopn evil party. The scouts can also be convinced to join the party for three days by succeeding on a DC 12 group Charisma check." +
"OUTPOST: Any character with a passive perception of 13 or higher spots a wooden platform in a tree 2d6 * 5 feet in the air and requires a dc 12 strength check to climb. The platform is sturdy and can hold up to six characters and their gear ",
monsters:true,
name: "Scout",
rolls:1,
die:4,
extra:1,
},
{ id: 42,
title: 'Emerald Enclave',
text: 'Thecharacters stumble upon a band of Emerald Enclave scouts OR one of their outposts. Choose whichever works best. SCOUTS: The party meets 1d4+1 members of the EMerald Enclave working to rid the jungle of its undead menace. The group works with a priest of Mielikki, but all other members are scouts.' +
"If on of the characters has died recently you can use this to introduce a new character, a member of the emerald enclave, one of the scouts, or someone who has hired the m or been rescued by them. The scouts will trade information on an equal basis with a nopn evil party. The scouts can also be convinced to join the party for three days by succeeding on a DC 12 group Charisma check." +
"OUTPOST: Any character with a passive perception of 13 or higher spots a wooden platform in a tree 2d6 * 5 feet in the air and requires a dc 12 strength check to climb. The platform is sturdy and can hold up to six characters and their gear ",
monsters:true,
name: "Scout",
rolls:1,
die:4,
extra:1,
},
{ id: 43,
title: 'Explorers, dead',
text: 'Chult is strewn with the bones and bodies of those who have fallen victim to its terrors. Roll once on the dead adventureres table to see what the players have found, then once on the treasure table to acertain what the explorers were carrying.' ,
monsters:true,
name:"Dead Adventurers",
rolls:1,
die:6,
extra:0
} ,
{ id: 44,
title: 'Explorers, dead',
text: 'Chult is strewn with the bones and bodies of those who have fallen victim to its terrors. Roll once on the dead adventureres table to see what the players have found, then once on the treasure table to acertain what the explorers were carrying.',
monsters:true,
name:"Dead Adventurers",
rolls:1,
die:6,
extra:0
} ,
{ id: 45,
title: 'Explorers',
text: 'Thepart runs upon another band of explorers consisting of a mage, a priest, a scout, and 1d6 tribal warriors. Roll d6 to determine the groups situation. 1-2: Explorers are lost and hungry, 3-4 The eplxorers are in good shape but are actively being hunted by firenewts, ghouls, grungs, or goblins. 5 They are healthy and intent on epxloring the enarest landmark and are headed there. 6 they are healthy and headed back to port Nyanzaru to resupply',
monsters:true,
name:"Tribal Warrior",
rolls:1,
die:6,
extra:0
} ,
{ id: 46,
title: 'Flail Snail',
text: 'The characters come across the slimy trail of a Flail Snail. A DC 10 survival check succesfully tacks the snail.',
monsters:true,
name:"Flail Snail",
rolls:0,
die:0,
extra:1,
} ,
{ id: 47,
title: 'Flaming Fist',
text: 'FLaing Fist know the jungle dangers better than most. A typical band consists of knight or veterna leading a band of 2d6 guards, a ascout, and an acolyte and 1d4 deinonychuses trained to fight and hunt alongside their handlers. The band is friendly to anyone with a charter of exploration issued by Liara Portyr at Fort Belurian. Otherwise, the band attempts to confiscate the partys gear and tells them to resupply at Fort Beluarian',
monsters:true,
name:"guard",
rolls:2,
die:6,
extra:0
} ,
{ id: 48,
title: 'Flaming Fist',
text: 'FLaing Fist know the jungle dangers better than most. A typical band consists of knight or veterna leading a band of 2d6 guards, a ascout, and an acolyte and 1d4 deinonychuses trained to fight and hunt alongside their handlers. The band is friendly to anyone with a charter of exploration issued by Liara Portyr at Fort Belurian. Otherwise, the band attempts to confiscate the partys gear and tells them to resupply at Fort Beluarian',
monsters:true,
name:"guard",
rolls:2,
die:6,
extra:0
} ,
{ id: 49,
title: 'Flaming Fist',
text: 'FLaing Fist know the jungle dangers better than most. A typical band consists of knight or veterna leading a band of 2d6 guards, a ascout, and an acolyte and 1d4 deinonychuses trained to fight and hunt alongside their handlers. The band is friendly to anyone with a charter of exploration issued by Liara Portyr at Fort Belurian. Otherwise, the band attempts to confiscate the partys gear and tells them to resupply at Fort Beluarian',
monsters:true,
name:"guard",
rolls:2,
die:6,
extra:0
} ,
{ id: 49,
title: 'Flaming Fist',
text: 'FLaing Fist know the jungle dangers better than most. A typical band consists of knight or veterna leading a band of 2d6 guards, a ascout, and an acolyte and 1d4 deinonychuses trained to fight and hunt alongside their handlers. The band is friendly to anyone with a charter of exploration issued by Liara Portyr at Fort Belurian. Otherwise, the band attempts to confiscate the partys gear and tells them to resupply at Fort Beluarian',
monsters:true,
name:"guard",
rolls:2,
die:6,
extra:0,
},
{ id: 51,
title: 'Fyling Monkeys',
text: 'The sound of flapping wings heralds the arrival of 3d6 flying monkies which swoop through the adventurers in a wave of grasping hands and feet. Each character must make a dc 12 dex save or lose a useful peice of gear.',
monsters:true,
name:"Flying Monkey",
rolls:3,
die:6,
extra:0,
},
{ id: 53,
title: 'Fyling Snakes',
text: 'Roll any die. On even the party encounters 1 flying snake, on odd they encounter 2d6 flying snakes. These snakes only attack when threatened. A flying snake that has been successfully grappled can be stuffed in a bag or container. After 1 hour of confinement the snake calms down. A character witha DC 13 Animal Handling check can remove a calm snake form the container without causing it to attack or fly away. Ifan Tal Roa will pay 25 gold per snake in Port Nyanzaru and cahn be convinced to buy them for 50g old ona dc 15 charisma check ',
monsters:true,
name:"Flying Snake",
rolls:2,
die:6,
extra:0,
},
{ id: 53,
title: 'Fyling Snakes',
text: 'Roll any die. On even the party encounters 1 flying snake, on odd they encounter 2d6 flying snakes. These snakes only attack when threatened. A flying snake that has been successfully grappled can be stuffed in a bag or container. After 1 hour of confinement the snake calms down. A character witha DC 13 Animal Handling check can remove a calm snake form the container without causing it to attack or fly away. Ifan Tal Roa will pay 25 gold per snake in Port Nyanzaru and cahn be convinced to buy them for 50g old ona dc 15 charisma check ',
monsters:true,
name:"Flying Snake",
rolls:2,
die:6,
extra:0,
} ,
{id: 54,
title: 'Frost Giants',
text: 'Thecharacters hear the sound of huge creatures stomping through the wilderness. If they follow the noise they encounter a party of 3 frost giants searching the jungle accompanied by 1d4-2 winter wolves. Roll a d10, on 9 or 10 this is Drufis search party (page 64 TOA book). The frost giants are looking for Artus Climber and the ring of winter and they may help characters who provide useful information. They immediately attack anyone who witholds information or who threaten to reveal their location to the flaming fist. They carry no treasure',
monsters:true,
name: "Frost Giant",
rolls:0,
die:0,
extra:3
} ,
{ id: 55,
title: 'Frost Giants',
text: 'Thecharacters hear the sound of huge creatures stomping through the wilderness. If they follow the noise they encounter a party of 3 frost giants searching the jungle accompanied by 1d4-2 winter wolves. Roll a d10, on 9 or 10 this is Drufis search party (page 64 TOA book). The frost giants are looking for Artus Climber and the ring of winter and they may help characters who provide useful information. They immediately attack anyone who witholds information or who threaten to reveal their location to the flaming fist. They carry no treasure',
monsters:true,
name: "Frost Giant",
rolls:0,
die:0,
extra:3
} ,
{ id: 56,
title: 'Giant Boars',
text: 'The party comes upon 1d4+1 giant boards foraging ahead. SKirting aruond the boars to prevent an attack requires a DC 12 group Stealth check',
monsters:true,
name: "Giant Boar",
rolls:1,
die:4,
extra:1
} ,
{ id: 57,
title: 'Giant Frogs',
text: 'These 2d6 giant frogs have come together in bunger and tro to eat eeverything that crosses their path. The characters have plenty of warning nas the amphibians hop noisly towards them',
monsters:true,
name: "Giant Frog",
rolls:2,
die:6,
extra:3
} ,
{ id: 58,
title: 'Giant Lizards',
text: 'Thecharacters come across 1d6 giant lizards sunning themselves on warm rocks. The lizards pose no threat to the characters unless threatened and are to set in their ways to be tamed',
monsters:true,
name: "Giant Lizard",
rolls:1,
die:6,
extra:0,
} ,
{ id: 59,
title: 'Giant Scorpions',
text: 'Any character with a passive perception above 11 notices 1d4-1 giant scorpions as they emerge from the underbrush and attack. At the end of the encounter, any character damaged by the creatures must suceed on a DC 11 Con save or contract "Shivering Sickness" ',
monsters:true,
name: "Giant Scorpions",
rolls:1,
die:4,
extra:-1,
} ,
{ id: 60,
title: 'Giant Wasps',
text: 'A droning sound announces the pressence of 1d6 Giant Wasps before the characters see them. The Wasps all attack at once ignoring those with heavy armor in favor of those with limited or no armor. Any character damaged by the wasps must make a DC 11 con save at the end of combat of contract Shivering Sickness',
monsters:true,
name: "Giant Wasp",
rolls:1,
die:6,
extra:0,
} ,
{ id: 61,
title: 'Girralons',
text: 'Two Girallons (four-armed super gorillas) are spotted in the trees or lumnber between crumbling, vine-covered ruins. The group can skirt past ona DC 13 group stealth check. If the characters defeat, ro frighten the gorillons away a search of the area finds a hidden cache, roll on the cache table. Also roll once on the treasure table to determine what the gorillans have stashed',
monsters:true,
name: "Girralon",
rolls:1,
die:0,
extra:2,
} ,
{ id: 62,
title: 'Girralons',
text: 'Two Girallons (four-armed super gorillas) are spotted in the trees or lumnber between crumbling, vine-covered ruins. The group can skirt past ona DC 13 group stealth check. If the characters defeat, ro frighten the gorillons away a search of the area finds a hidden cache, roll on the cache table. Also roll once on the treasure table to determine what the gorillans have stashed',
monsters:true,
name: "Girralon",
rolls:1,
die:0,
extra:2,
} ,
{ id: 63,
title: 'Goblins',
text: 'A Batari patrol of a goblin boss + 2d6+2 golbins all wearing painted wooden masks. NIGHT: any player on watch must suceed on a dc 16 perception check with disadvantage to spot the goblins setting up an ambush. If no one succeed the entire party is suprised. DAY: Each player must make a DC 16 insight check to spot the signs of an ambush and an eerie silence in the jungle. Othersiwse they are surprised. Goblins will baragain for their lives and can be coerced or forced to serve as a guide with +1 survival.',
monsters:true,
name: "Goblin",
rolls:2,
die:6,
extra:2,
} ,
{ id: 63,
title: 'Goblins',
text: 'A Batari patrol of a goblin boss + 2d6+2 golbins all wearing painted wooden masks. NIGHT: any player on watch must suceed on a dc 16 perception check with disadvantage to spot the goblins setting up an ambush. If no one succeed the entire party is suprised. DAY: Each player must make a DC 16 insight check to spot the signs of an ambush and an eerie silence in the jungle. Othersiwse they are surprised. Goblins will baragain for their lives and can be coerced or forced to serve as a guide with +1 survival.',
monsters:true,
name: "Goblin",
rolls:2,
die:6,
extra:2,
} ,
{ id: 65,
title: 'Grungs',
text: 'A grung hunting party led by a Grung ELite Warrior and 2d6 grungs (frog people). DAY: A DC 14 perception check spots an ambush, otherwise the players are surprised. NIGHT: any player on watch must suceed on a dc 14 perception check with disadvantage to spot the goblins setting up an ambush. If no one succeed the entire party is suprised. If a grung is captured, he will offer to lead the characters to treasure in exchange for freedom. The treasure is a cache one half mile from the players. Roll once on the cahce table, ',
monsters:true,
name: "Grung",
rolls:2,
die:6,
extra:1,
} ,
{ id: 66,
title: 'Grungs',
text: 'A grung hunting party led by a Grung ELite Warrior and 2d6 grungs (frog people). DAY: A DC 14 perception check spots an ambush, otherwise the players are surprised. NIGHT: any player on watch must suceed on a dc 14 perception check with disadvantage to spot the goblins setting up an ambush. If no one succeed the entire party is suprised. If a grung is captured, he will offer to lead the characters to treasure in exchange for freedom. The treasure is a cache one half mile from the players. Roll once on the cahce table, ',
monsters:true,
name: "Grung",
rolls:2,
die:6,
extra:1,
} ,
{ id: 67,
title: 'Jaculis',
text: 'Without warning, 1d6 Jaculis (javelin like, dragon faced snakes) leap from the jungle and attack. Any character with a passive perception of 14 or higher is not suprised. ',
monsters:true,
name: "Jaculi",
rolls:1,
die:6,
extra:0,
} ,
{ id: 68,
title: 'Kamadans',
text: 'The party is ambushed by 1d4-2 Kamadans( leopards with snakes growing out of them). Any player with a passive perceptions of 16 or higher are not surpised. A DC 15 search of the area finds a Kamadan lair. roll a d4 , ona 4 the lair contains 1d4-1 noncombatant kamadan cubs the size of housecats. They can be sold in Port Nyanzaru for 150 gold or 300 gol on a dc 15 charisma check.',
monsters:true,
name:"Kamadan",
rolls:2,
die:4,
extra:0,
} ,
{ id: 69,
title: 'Lizardfolk',
text: 'Thecharacters encounter 2d4 lizardfolk and one lizardfolk shaman. They belong to a nearby tribe in the Valley of Dread and can be appeased with food - 1 days supply of food per lizardfolk, otherwise they attack',
monsters:true,
name:"Lizardfolk",
rolls:2,
die:4,
extra:0,
} ,
{ id: 70,
title: 'Lizardfolk',
text: 'Thecharacters encounter 2d4 lizardfolk and one lizardfolk shaman. They belong to a nearby tribe in the Valley of Dread and can be appeased with food - 1 days supply of food per lizardfolk, otherwise they attack',
monsters:true,
name:"Lizardfolk",
rolls:2,
die:4,
extra:0,
} ,
{ id: 71,
title: 'Mad Monkey Mist',
text: 'A blue mist floats toward the players covering 1d6 20 ft squares. Any character with a passive wisdom of 13 spots the mist and can warn the other palyers. At night, the mist drifts through camp at 5ft per round. Characters who come in contact with the mist contract Mad Monkey Fever',
monsters:true,
name:"Mad Monkey Mist",
rolls:1,
die:6,
extra:0,
} ,
{ id: 72,
title: 'Mad Monkey Mist',
text: 'A blue mist floats toward the players covering 1d6 20 ft squares. Any character with a passive wisdom of 13 spots the mist and can warn the other palyers. At night, the mist drifts through camp at 5ft per round. Characters who come in contact with the mist contract Mad Monkey Fever',
monsters:true,
name:"Mad Monkey Mist",
rolls:1,
die:6,
extra:0,
} ,
{ id: 73,
title: 'Mantraps',
text: 'The characters wander into a patch of 1d4+1 mantraps (giant man eating plant). The plants are indistinguishable until they attack. The plants are spaced 10 ft apart and must wait until players come close enough to attack.',
monsters:true,
name:"Mantrap",
rolls:1,
die:4,
extra:1,
} ,
{ id: 74,
title: 'Night Hag',
text: 'One of the Sewn Sisters (hags from the tomb of anihilation) has been following the party staying in the Border Ethereal. During the partys next long rest, she materialzies, snatches one of the partys blood or hair and disappears returning to the ethereal plane.',
monsters:true,
name:"Night Hag",
rolls:1,
die:0
,
extra:0,
} ,
{ id: 75,
title: 'Pterrafolk',
text: 'Looming in the sky 1d4+2 pterafolk watch the characters every move and wait until they blunder into danger, the next time an encounter occurs, the Pterafolk attack launching javelin attacks and staying out of melee range. With firm resistance the pterafolk retreat but may regroup to attack at your discretion' ,
monsters:true,
name:"Pterafolk",
rolls:1,
die:4,
extra:2
} ,
{ id: 76,
title: 'Rare Plant',
text: 'The characters find one or more unusall plants determind by a d6 roll. 1 - 2d6 dancing monkey fruit growing on a tree. 2 - manga bush with 2d6 ounces of leaves. 3 - 1d4 ryath roots growing in gorund. 4 4d6 sindaberries growing in a bush. 5 - wukka tree with 2d6 wukka nuts. 6 1d6 zabu growing on a dead tree.',
monsters:false,
name:"",
rolls:1,
die:6,
extra:0
},
{ id: 77,
title: 'Red Wizard',
text: 'This group consists of 1 red wizard, LE, human mage, 1d6 guards, and 1d6 skeletons, all answerable to Velinda Shadowmantle. If this encounter happens outside of the city of Omu, they are reinforcements on their way to the city. If inside Omu the party is searching the citry for shrines (chapter 3). They are not spoiling for a fight and if things look grim, they will surrender and offer up a crudely drawn map of Chult with the location of known undead hordes.',
monsters:true,
name:"Red Wizard",
rolls:1,
die:6,
extra:0,
},
{ id: 78,
title: 'Snake, Constrictor',
text: 'A constrictor snake attacks a random party member from hiding. The character is suprised unless their passive perception is greater than 11',
monsters:true,
name:"constrictor snake",
rolls:0,
die:0,
extra:0
},
{ id: 79,
title: 'Snake, Constrictor',
text: 'A constrictor snake attacks a random party member from hiding. The character is suprised unless their passive perception is greater than 11',
monsters:true,
name:"constrictor snake",
rolls:0,
die:0,
extra:0
},
{ id: 80,
title: 'Snake, Giant Constrictor',
text: 'A constrictor snake attacks a random party member from hiding. The character is suprised unless their passive perception is greater than 11',
monsters:true,
name:"Giant Constrictor Snake",
rolls:2,
die:6,
extra:0,
},
{ id: 81,
title: 'Snake, Giant Constrictor',
text: 'A constrictor snake attacks a random party member from hiding. The character is suprised unless their passive perception is greater than 11',
monsters:true,
name:"Giant Constrictor Snake",
rolls:2,
die:6,
extra:0,
},
{ id: 82,
title: 'Spiders',
text: 'Giant spiderwbs are easily concealed in Chults dense jungles and swamps. Passive perception of 13 or higher alerts the characeters in time for an encounter with 1d6 giant spiders. Otherwise, the lead party member stumbles into an ambush and becomes grappled with a escape dc of 12 - the spiders have suprise and 100s of harmless baby spiders crawl through the webs',
monsters:true,
name:"Giant Spider",
rolls:1,
die:6,
extra:0,
},
{ id: 83,
title: 'Statue of Ubtao',
text: 'see page 202',
monsters:false,
name:"",
rolls:2,
die:6,
extra:0,
},
{ id: 84,
title: 'Statue of Ubtao',
text: 'see page 202',
monsters:false,
name:"",
rolls:2,
die:6,
extra:0,
},
{ id: 85,
title: 'Statue of Ubtao',
text: 'see page 202',
monsters:false,
name:"",
rolls:2,
die:6,
extra:0,
} ,
{ id: 86,
title: 'Stirges',
text: 'Chut is rich in caves, ruins, and hollow logs where stirges can hide. By day, the party disturbs 2d6 stirges as they move through the jungke. By night, the Stirges descend upon them',
monsters:true,
name:"Stirge",
rolls:2,
die:6,
extra:0,
} ,
{ id: 87,
title: 'Stirges',
text: 'Chut is rich in caves, ruins, and hollow logs where stirges can hide. By day, the party disturbs 2d6 stirges as they move through the jungke. By night, the Stirges descend upon them',
monsters:true,
name:"Stirge",
rolls:2,
die:6,
extra:0,
} ,
{ id: 88,
title: 'Swarm of Bats',
text: 'Ruis, hallow trees, and hidden caves all serve as hiding places for swarms of bats. The party disturbs 1d4 swarm of bats that have become unnaturally aggressive after feasting on undead flesh',
monsters:true,
name:"Swarm of Bats",
rolls:1,
die:4,
extra:0,
} ,
{ id: 89,
title: 'Swarm of Bats',
text: 'Ruis, hallow trees, and hidden caves all serve as hiding places for swarms of bats. The party disturbs 1d4 swarm of bats that have become unnaturally aggressive after feasting on undead flesh',
monsters:true,
name:"Swarm of Bats",
rolls:1,
die:4,
extra:0,
} ,
{ id: 90,
title: 'Tabaxi Hunter',
text: 'Anyplayer with a passive perception score higher than 15 notices a Tabaxi Hunter from a vantage point 300 ft away. If the hunter remains unseen it may follow the characters for a while, assisting them in a tough encounter. If this encounter takes palce in Omu, see chapter 3 for information on the Tabaxi encountered there.',
monsters:true,
name:"Tabaxi Hunter",
rolls:0,
die:0,
extra:1,
} ,
{ id: 91,
title: 'Tabaxi Hunter',
text: 'Anyplayer with a passive perception score higher than 15 notices a Tabaxi Hunter from a vantage point 300 ft away. If the hunter remains unseen it may follow the characters for a while, assisting them in a tough encounter. If this encounter takes palce in Omu, see chapter 3 for information on the Tabaxi encountered there.',
monsters:true,
name:"Tabaxi Hunter",
rolls:0,
die:0,
extra:1,
} ,
{ id: 92,
title: 'Tabaxi Hunter',
text: 'Anyplayer with a passive perception score higher than 15 notices a Tabaxi Hunter from a vantage point 300 ft away. If the hunter remains unseen it may follow the characters for a while, assisting them in a tough encounter. If this encounter takes palce in Omu, see chapter 3 for information on the Tabaxi encountered there.',
monsters:true,
name:"Tabaxi Hunter",
rolls:0,
die:0,
extra:1,
} ,
{ id: 93,
title: 'Vegepygmy',
text: 'The characters cross path with 1d4 vegepygmys each one mounted on a Thorny. The hunters have wandered far from their tribe. They flee if outnumbered otherwise they attack.',
monsters:true,
name:"Vegepygmy",
rolls:0,
die:0,
extra:1,
},
{ id: 94,
title: 'Wereboar',
text: 'A wereboar masquerading as a chultan priest takes a dim view of explorers encroaching on its territory. On its neck is a wooden labrynth carved into a wooden disk. The symbol of Ubtao. He might be guarding a shrine to Ubtao a grove of wukka trees or a cave it uses as a lair. It may also have treasure. Roll 3 trasure drops in the trasure table.',
monsters:true,
name:"Wereboar",
rolls:0,
die:0,
extra:1,
} ,
{ id: 95,
title: 'Weretiger',
text: 'In human forma weretiger offers to excort the party through a very dangerous stretch of wilderness. If they accompany her, they cannot get attacked. She will leave after 24 hours and will not go to Omu Nangalore or Orolunga.',
monsters:true,
name:"Weretiger",
rolls:0,
die:0,
extra:1,
} ,
{ id: 96,
title: 'Winterscape',
text: 'The characters stumble intoa 112 ft radius sphere of winter weather. Artus used the ring of winter to drive off monsters. All plants are covered in glittering ice and frost. The temperature in here is a biting -30 degrees farenhiet and cannot be dispelled.',
monsters:false,
name:"",
rolls:0,
die:0,
extra:1,
} ,
{ id: 97,
title: 'Yellow musk creeper and zombies',
text: 'The characters pass close to a ruin inhabited by 3d6 Yellow Musk Zombies. Somewhere within the ruin a Yellow Musk Creeper clings to a wall. If this encounter occurs while the players are camped the zombies attack the camp and attempt to drag the party back to the ruin',
monsters:true,
name:"Yellow Musk Creeper",
rolls:3,
die:6,
extra:0,
} ,
{ id: 98,
title: 'Yuan-ti',
text: 'Yuan-ti patrols consist of 1d6+1 Yuan-ti purebloods who keep their distance while they try to gather information to bring back to Ras Nsi. The Yuan-ti are disguised but any character who succeeds on a DC 13 Perception check made with disadvantage catches sight of the serpent folk as they withdraw. If within 25 miles of OMU the group is 1d4+1 yuan-ti Malisons instead and the check is DC 14',
monsters:true,
name:"Yuan-ti",
rolls:1,
die:4,
extra:0,
} ,
{ id: 99,
title: 'Zhentarim',
text: 'A zhent assassin with a fling snake pet leads a priest, 2d6 thugs and 1d6 tribal warriors through the wilderness in search of Artus Cimber and The Ring of Winter. If Artus is with the party the Zhents attack to get the ring otherwise they show little interest. Roll on the treasure table to determine what if anything they carry',
monsters:true,
name:"Assassin",
rolls:3,
die:6,
extra:0,
} ,
{ id: 100,
title: 'Zorbos',
text: 'If his encounter happens in the wild the party stumbled upon 2d6 Zorbos in wukka trees who attack if the party makes threatening motions. If during camp, the Zorbos drop from surrounding trees and attack.',
monsters:true,
name:"Zorbo",
rolls:2,
die:6,
extra:0,
},
]
|
ce27014d105d6a1b1a27eb93fef3b1bd17ca55e5
|
TypeScript
|
Untrii/labl-test
|
/src/hooks/useAPI.ts
| 2.59375
| 3
|
import { computed, watch, ref, nextTick, onBeforeMount } from 'vue'
import { useStore } from 'vuex'
import { key } from '@/store'
import router from '@/router'
import { baseApiUrl } from '@/config'
import IProduct from '@/models/IProduct'
import IVariant from '@/models/IVariant'
export default function useAPI(
selectOption: (value: string) => void,
selectSubOption: (name: string, value: string) => void
) {
const store = useStore(key)
const isQueryPending = ref(false)
const isDataFetched = ref(false)
watch(isQueryPending, (newValue) => {
if (!newValue) {
//@ts-ignore
document.activeElement?.blur?.()
}
})
const fillSubOptions = function(variants: IVariant[], options: string[]) {
for (const option of options) selectOption(option)
for (const variant of variants) {
for (let i = 0; i < variant.options.length; i++) {
const element = variant.options[i]
selectSubOption(options[i], element)
}
}
}
const fetchedProduct = ref({} as IProduct)
const fetchData = async function() {
isQueryPending.value = true
const currentRoute = router.currentRoute.value
const productId = currentRoute.params.id ?? 'rose'
try {
const product = await fetch(baseApiUrl + '/products/' + productId)
const response = await product.text()
//Дважды вызываем JSON.parse, чтобы store и fetchedProduct ссылались на разные объекты
fetchedProduct.value = JSON.parse(response)
const responseObject = JSON.parse(response) as IProduct
fillSubOptions(responseObject.product.variants, responseObject.product.options)
nextTick(() => {
store.commit('setData', responseObject)
})
isDataFetched.value = true
} catch {
alert('Ошибка при отправке запроса')
}
isQueryPending.value = false
}
const uploadData = async function() {
const data = JSON.stringify(store.state)
const currentRoute = router.currentRoute.value
const productId = currentRoute.params.id ?? 'rose'
isQueryPending.value = true
try {
await fetch(baseApiUrl + '/products/' + productId, {
method: 'PUT',
body: data,
})
fetchedProduct.value = JSON.parse(data)
} catch {
alert('Ошибка при отправке запроса')
}
isQueryPending.value = false
}
const deleteData = async function() {
const currentRoute = router.currentRoute.value
const productId = currentRoute.params.id ?? 'rose'
isQueryPending.value = true
try {
await fetch(baseApiUrl + '/products/' + productId, {
method: 'DELETE',
})
alert('Продукт удалён')
router.push('/')
} catch {
alert('Ошибка при отправке запроса')
}
isQueryPending.value = false
}
onBeforeMount(() => {
fetchData()
})
return computed(() => ({
isQueryPending: isQueryPending.value,
isDataFetched: isDataFetched.value,
fetchedProduct: fetchedProduct.value,
fetchData,
uploadData,
deleteData,
}))
}
|
27591ea60e7a568b18827d2b16084f3b1a052e32
|
TypeScript
|
ShiriNmi1520/OSTB
|
/server/giveCard.ts
| 3.5
| 4
|
const cards : Array<string> = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
const types : Array<string> = ["♠", "♥", "♣", "♦"];
export function getRandom(pools : Array<number>, count : number): Array<string> {
const arr : Array<string> = [];
for (let i : number = 0; i < count; i++) {
let pool : any = pools[Math.floor(Math.random() * pools.length)];
arr.push(pool);
}
return arr;
}
export function getRandomWithType(count : number): Array<string> {
const arr : Array<string> = [];
for (let i : number = 0; i < count; i++) {
let pool : string = cards[Math.floor(Math.random() * cards.length)];
let type : string = types[Math.floor(Math.random() * types.length)];
let result : string = pool + type;
arr.indexOf(result) === -1 ? arr.push(result) : i--;
}
return arr;
}
|
c01ac2ebda806bca08ee72e1c6cc644614e5e44b
|
TypeScript
|
quenktechnologies/wml
|
/lib/cli.d.ts
| 2.5625
| 3
|
import { Future } from '@quenk/noni/lib/control/monad/future';
import { Options } from './compile';
/**
* CLIOptions
*/
export interface CLIOptions extends Partial<Options> {
/**
* inputExtension is the file extension used when searching for files to
* compile.
*/
inputExtension: string;
/**
* outputExtension is the file extension used when outputing directly to file.
*/
outputExtension: string;
}
/**
* Arguments passed on the command line.
*/
export interface Arguments {
'--main': string;
'--outputExtension': string;
'--inputExtension': string;
'--module': string;
'--dom': string;
'<path>': string;
}
/**
* compileDir will compile each wml file found in the specified path.
*/
export declare const compileDir: (path: string, opts: CLIOptions) => Future<void[]>;
/**
* compileFile will compile a single wml file.
*
* If that file does not have the specified inputExtension, it will be
* ignored.
*/
export declare const compileFile: (path: string, opts: CLIOptions) => Future<void>;
|
090e335a3e3502cb50b546a7694a67251dc34887
|
TypeScript
|
artifact-project/exility
|
/block/src/block/block.ts
| 2.65625
| 3
|
import XEvent, {DOMEvent, IEmitter} from '../event/event';
export interface BlockClass<A = {}, C extends object = {}> {
new (attrs: A, options?: {context?: C}): Block<A, C>;
template?: string;
classNames?: any;
}
export type IBlock = typeof Block;
export interface IBlockIds {
[index: string]: IBlock;
}
export interface IBlockRefs {
[index: string]: HTMLElement;
}
export interface IBlockOptions<C> {
context?: C;
events?: object;
parent?: typeof Block;
slots?: object;
isomorphic?: Element | Document;
}
export interface IPlainBlock<A> {
template: string;
getDefaults?(): A;
connectedCallback?();
disconnectedCallback?();
attributeChangedCallback?<K extends keyof A>(attrName: K, oldValue: A[K], newValue: A[K]): void;
}
export const requiredScopeKeys = [
'attrs',
'context',
'__this__',
'__blocks__',
'__slots__',
'__classNames__',
];
const EMPTY_CONTEXT = {};
let cid = 0;
export default class Block<A = {}, C extends object = {}> implements IEmitter<IBlock> {
static classify<X>(ClassOrLike: string | IPlainBlock<X> | IBlock): typeof Block {
if (typeof ClassOrLike === 'string') {
ClassOrLike = <IPlainBlock<X>>{template: ClassOrLike};
} else if (ClassOrLike instanceof Block) {
return <IBlock>ClassOrLike;
}
class NewBlock extends Block<X, null> {
constructor(attrs, options) {
super(attrs, options);
ClassOrLike.hasOwnProperty('constructor') && ClassOrLike.constructor.call(this, attrs);
}
}
Object.keys(ClassOrLike).forEach(name => {
NewBlock.prototype[name] = ClassOrLike[name];
});
NewBlock.template = ClassOrLike.template;
NewBlock.prototype.constructor = NewBlock;
return <any>NewBlock;
}
ids: IBlockIds = {};
refs: IBlockRefs = {};
cid: number;
name: string;
attrs: A;
context: C;
private __scope__ = null;
private __view__ = null;
// инжектиться из «вне»
private __template__;
private __parent__;
private __events__;
protected __options__: IBlockOptions<C>;
// Базлвый шаблон
static template: string | ((attrs) => void) = null;
static blocks: object;
constructor(attrs: A, options?: IBlockOptions<C>) {
const self = this.constructor;
const defaults = this.getDefaults();
for (const key in defaults) {
if (defaults.hasOwnProperty(key)) {
if (attrs[key] == null) {
attrs[key] = defaults[key];
}
}
}
if (options == null) {
options = {};
}
this.cid = ++cid;
this.attrs = attrs;
this.context = (options.context || EMPTY_CONTEXT) as C;
this.__events__ = options.events;
this.__parent__ = options.parent;
this.__options__ = options;
let classNames = self['classNames'];
if (classNames === true) {
const {$css} = this.context as any;
if ($css === void 0) {
classNames = {};
// console.warn(`[@exility/block] Не найден css-провайдер для ${(self as any).name}`);
} else {
classNames = $css(self);
}
}
this.__scope__ = {
attrs: this.attrs,
context: this.context,
__blocks__: self['blocks'],
__classNames__: classNames,
__this__: this,
__slots__: options.slots,
};
if (this.__template__ === void 0) {
console.warn(`[@exility/block] Not compiled: ${new.target.name}`);
} else {
this.__view__ = Block.createView(
this,
this.__template__,
this.__scope__,
{isomorphic: options.isomorphic}
);
}
}
static createView(block, template: Function, scope, options) {
return template(scope, options);
}
protected getDefaults(): Partial<A> {
return {};
}
protected getContextForNested(): any {
return this.context;
}
protected registerRef(name: string, el: HTMLElement): void {
}
protected connectedCallback(): void {
}
protected disconnectedCallback(): void {
}
protected attributeChangedCallback<K extends keyof A>(attrName: K, oldValue: A[K], newValue: A[K]): void {
}
isBlock() {
return true;
}
dispatchEvent<D extends object, E extends DOMEvent>(event: XEvent<IBlock, D, E>);
dispatchEvent<D extends object, E extends DOMEvent>(type: string, detail?: D, originalEvent?: E);
dispatchEvent(type, detail?, originalEvent?) {
const event = type instanceof XEvent ? type : new XEvent(type, detail, originalEvent);
const eventType = event.type;
const atName = `@${eventType}`;
let __parent__ = this;
event.setTarget(this);
this[atName] && this[atName](event);
do {
const {__events__} = __parent__;
if (__events__ && __events__.hasOwnProperty(eventType)) {
let {ctx, fn, detail} = __events__[eventType];
if (event.detail != null) {
if (detail == null) {
detail = event.detail;
} else {
detail = {...event.detail, ...detail};
}
}
// todo: relatedTarget
const nextEvent = new XEvent(fn, detail, event.originalEvent);
nextEvent.setTarget(this);
if (ctx.dispatchEvent) {
ctx.dispatchEvent(nextEvent);
} else if (ctx.hasOwnProperty(`@${fn}`)) {
ctx[`@${fn}`](nextEvent);
}
// Всегда выходим, иначе получаем дублирование событий.
// В целом выглядит логично, если у нас есть слушатель на блоке, то
// это банальный перехват под новым именем, ну или с тем же.
break;
} else if (__parent__ !== this && __parent__[atName] !== void 0) {
__parent__[atName](event);
if (event.propagationStopped) {
break;
}
}
__parent__ = __parent__.__parent__;
} while (__parent__);
}
update(partialAttrs: Partial<A>, nextContext?: C) {
const previousAttrs = this.attrs;
let attrsChanged;
let attrsChangedLength = 0;
if (partialAttrs !== void 0) {
attrsChanged = [];
for (const key in partialAttrs) {
if (partialAttrs.hasOwnProperty(key)) {
const oldValue = previousAttrs[key];
let newValue = partialAttrs[key];
if (newValue == null) {
newValue = null;
}
if (oldValue !== newValue) {
attrsChanged.push(key, oldValue, newValue);
attrsChangedLength += 3;
this.attrs[key] = newValue;
}
}
}
}
if (nextContext !== void 0) {
this.context = this.__scope__.context = nextContext;
if (attrsChangedLength === 0) {
this.__view__.update(this.__scope__);
}
}
// Если есть изменения, обновляем объект
if (attrsChangedLength) {
this.__scope__.__classNames__ = this.constructor['classNames'];
this.__view__.update(this.__scope__);
for (let idx = 0; idx < attrsChangedLength; idx += 3) {
this.attributeChangedCallback(attrsChanged[idx], attrsChanged[idx + 1], attrsChanged[idx + 2]);
}
}
}
forceUpdate() {
this.__view__.update(this.__scope__);
}
getRootNode(): HTMLElement {
return this.__view__.frag[0];
}
}
|
209f3cea0a47f37a52af08348222b54dae8c8625
|
TypeScript
|
jasonraimondi/cryptozombies
|
/dapp/test/index.ts
| 2.703125
| 3
|
import { expect } from "chai";
import { ethers } from "hardhat";
import type { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers";
import type { Contract } from "ethers";
describe("ZombieOwnership", function () {
let zombies: Contract;
let owner: SignerWithAddress;
let addr1: SignerWithAddress;
let addr2: SignerWithAddress;
let addr3: SignerWithAddress;
beforeEach(async () => {
[owner, addr1, addr2, addr3] = await ethers.getSigners();
console.log("contract owner", owner.address);
console.log("zombie owner", addr1.address);
const ZombieOwnership = await ethers.getContractFactory("ZombieOwnership");
zombies = await ZombieOwnership.deploy();
await zombies.deployed();
});
it("allows a user to create 1 zombie", async function () {
const createZombie1 = await zombies.connect(addr1).createRandomZombie("Ruby");
await createZombie1.wait();
const createZombie2 = await zombies.connect(addr2).createRandomZombie("Dooby");
await createZombie2.wait();
const [zombie1Id, ...extras] = await zombies.getZombiesByOwner(addr1.address);
const zombie = await zombies.zombies(zombie1Id);
// const [zombie2Id] = await zombies.getZombiesByOwner(addr1.address);
// const zombie2 = await zombies.zombies(zombie2Id);
// const attack = await zombies.connect(addr1).attack(zombie1Id, zombie2Id);
// await attack.wait();
expect(extras).to.have.length(0);
expect(zombie.name).to.equal("Fred Zombie");
expect(zombie.level).to.equal(1);
expect(zombie.winCount).to.equal(0);
expect(zombie.lossCount).to.equal(0);
expect(await zombies.zombieToOwner(zombie1Id)).to.equal(addr1.address);
});
});
|
7db5660755097224ec002f92f30bff0b7b32eccc
|
TypeScript
|
Ink-grid/easyformui
|
/src/components/inputs/type.ts
| 2.71875
| 3
|
/**
* interface forms
*/
import { formtype, FormsProps } from "../forms";
/**
* omit props OF FormsProps
*/
type omitpProps = Omit<FormsProps, "form" | "onSubmit" | "children">;
/**
* types props for input Component
* @author Rony cb
* @version 1.0.0
* @param value necesarie for getInput
* @param erros error capture for input;
* @param touched If touch input defaul checked errors
*/
export interface InputsProps extends omitpProps {
value: formtype;
errors: any;
touched: any;
valuesInput: any;
}
|
e6363a725ad393be71428da47de734c049fa7751
|
TypeScript
|
naughtLdy/sandbox-typescript-meetup3
|
/src/store/modules/cs/index.ts
| 2.703125
| 3
|
import { RootState } from '~/store'
import { defineModule, defineGetter } from '~/store/helpers';
import {
actionCreatorFactory,
combineMutation,
combineAction,
action,
mutation
} from 'vuex-typescript-fsa'
interface User {
name: string
}
export const namespace = 'csStore'
const actionCreator = actionCreatorFactory(namespace)
export const FetchUser = actionCreator<{}>('FETCH_USER')
export const ReceiveUser = actionCreator<User>('RECEIVE_USER')
export interface State {
user: User
}
const initialState = (): State => {
return {
user: {
name: ''
}
}
}
const getters = defineGetter<State, RootState>()({
username(state): string {
return state.user.name
}
})
export const csModule = defineModule<State, RootState>()({
namespaced: true,
state: initialState,
actions: combineAction(
action(FetchUser, async function(context, action) {
const user: User = {
name: 'naughtLdy'
}
context.commit(ReceiveUser(user))
})
),
mutations: combineMutation(
mutation(ReceiveUser, function(state, { payload }) {
state.user = payload
})
),
getters
})
|
d6c090b22ec95f5e74f2fae3f5e62cf58217e4dc
|
TypeScript
|
Valdecir190199/ListaTelefonicaAngular
|
/src/app/entidades/lista.ts
| 2.671875
| 3
|
export class Lista{
private nome : string;
private numero : number;
getNumero():number {
return this.numero;
}
setNumero(numero:number) : void{
this.numero = numero;
}
getNome():string {
return this.nome;
}
setNome(nome:string) : void{
this.nome = nome;
}
}
|
c772e70f095deb66b172f82e4bdac2c5b7663bb2
|
TypeScript
|
devskar/clicker-game
|
/src/manager/FileManager.ts
| 2.625
| 3
|
import editJsonFile, { JsonEditor } from 'edit-json-file';
class FileManager {
filePath: string;
saveEveryXSeconds: number;
file: JsonEditor | null;
cashedContent: any;
constructor(filePath: string, saveEveryXSeconds: number = 15) {
this.filePath = filePath;
this.saveEveryXSeconds = saveEveryXSeconds;
this.file = null;
this.cashedContent = null;
this.loadFile();
this.startFileSaveLoop();
}
startFileSaveLoop() {
this.save();
this.cashedContent = this.file?.read();
setTimeout(() => this.startFileSaveLoop(), this.saveEveryXSeconds * 1000);
}
save() {
if (this.cashedContent)
this.file?.write(JSON.stringify(this.cashedContent));
}
fileLoaded = () => {
return this.file != null;
};
loadFile = () => {
this.file = editJsonFile(this.filePath);
};
}
export default FileManager;
|
8e632791f9d075e88b2fa4365a264ecbce4c0492
|
TypeScript
|
isChosen/my-auction-form
|
/src/app/validator/validators.ts
| 2.578125
| 3
|
import { FormControl, FormGroup } from '@angular/forms';
// tslint:disable-next-line:import-blacklist
import { Observable } from 'rxjs';
// 校验方法
export function mobileValidator(val: FormControl): any {
const regExp = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
const valid = regExp.test(val.value);
console.log(`mobile 校验结果是: ${valid}`);
return valid ? null : {mobile: 'invalid'};
}
export function mobileAsyncValidator(val: FormControl): any {
const regExp = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
const valid = regExp.test(val.value);
console.log(`mobile 校验结果是: ${valid}`);
return Observable.of(valid ? null : {mobile: 'invalid'}).delay(10000);
}
export function equalValidator(pwdGroup: FormGroup): any {
const pwd = pwdGroup.get('password') as FormControl;
const pwdConfirm = pwdGroup.get('pconfirm') as FormControl;
const valid = (pwd.value === pwdConfirm.value);
console.log(`密码相等校验: ${valid}`);
return valid ? null : {equal: {description: '两次输入密码不一致'}};
}
|
bd7a9c04b895b201ad6ee02cf2e1fed5bb31e312
|
TypeScript
|
infinitelifter/test-list
|
/src/containers/form/reducer.ts
| 3.109375
| 3
|
import { Reducer } from "redux";
import { ADD_ITEM, REMOVE_ITEM } from "../../constants";
export interface FormReducerState {
items: string[];
}
export const initialState = {
items: []
};
export const formReducer: Reducer<FormReducerState> = (
state = initialState,
action
): FormReducerState => {
switch (action.type) {
case ADD_ITEM:
return {
...state,
items: [...state.items, action.payload].sort(function(a, b) {
const itemA = a.toLowerCase();
const itemB = b.toLowerCase();
if (itemA < itemB) return -1;
if (itemA > itemB) return 1;
return 0;
})
};
case REMOVE_ITEM:
return {
...state,
items: state.items.filter(item => item !== action.payload)
};
default:
return state;
}
};
|
757ddb02d6125787aa7b83c1fe82e7cfc92eddaf
|
TypeScript
|
wizba/Galaxy
|
/src/app/Services/ShortestPath.service.ts
| 2.828125
| 3
|
import { Injectable } from "@angular/core";
import { GRAPH, PLANET_NAMES } from "../Graph/Graph";
@Injectable({
providedIn: "root",
})
export class ShortestPath {
private INFINITY: number = 9999;
private myNodes: string[] = [
"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",
"A'",
"B'",
"C'",
"D'",
"E'",
"F'",
"G'",
"H'",
"I'",
"J'",
"K'",
"L'",
];
private planetsNames: any[] = PLANET_NAMES;
private nodeMax = 38; //max node number
private shortestPaths: any[] = [];
private tempObject: any = {
nodeid: "",
nodePath: [],
distance: 0,
};
private paths: any[];
constructor() {}
/**
*
* @param G represents a the graph
* @param n number of nodes
* @param startnode is a variable that holds the starting node
*/
dijkstra(G: number[][], n: number, startnode: number): void {
let cost: number[][] = new Array(this.nodeMax)
.fill(0)
.map(() => new Array(this.nodeMax).fill(0));
let distance: number[] = [];
let pred: number[] = [];
let visited: number[] = [];
let count: number;
let mindistance: number;
let nextnode: number;
let i: number;
let j: number;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (G[i][j] == 0) {
cost[i][j] = this.INFINITY;
} else {
cost[i][j] = G[i][j];
}
}
}
for (i = 0; i < n; i++) {
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}
distance[startnode] = 0;
visited[startnode] = 1;
count = 1;
while (count < n - 1) {
mindistance = this.INFINITY;
for (i = 0; i < n; i++) {
if (distance[i] < mindistance && !visited[i]) {
mindistance = distance[i];
nextnode = i;
}
}
visited[nextnode] = 1;
for (i = 0; i < n; i++) {
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i]) {
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
}
count++;
}
for (i = 0; i < n; i++) {
if (i != startnode) {
// console.log("Distance of node", i, "=", distance[i]);
// console.log("Path=", i);
this.tempObject["nodeid"] = i;
this.tempObject["distance"] = distance[i];
j = i;
this.tempObject["nodePath"].push(j);
do {
j = pred[j];
//console.log("<-", j);
this.tempObject["nodePath"].push(j);
} while (j != startnode);
this.shortestPaths.push(this.tempObject);
this.tempObject = {
nodeid: "",
nodePath: [],
distance: 0,
};
}
}
}
/**
* getShortestPaths()
* this method returns an array of all the paths
*/
public getShortestPaths(): any[] {
// console.log(this.planetsNames);
return this.planetsNames;
}
setCharecterPath() {
this.paths = [];
this.shortestPaths.forEach((temp, index) => {
let nodeCharecter = this.myNodes[temp.nodeid];
let distance = temp.distance;
let tempPath: any[] = [];
for (let i = 0; i < temp.nodePath.length; i++) {
tempPath.push(this.myNodes[temp.nodePath[i]]);
}
this.planetsNames[index]["path"] = tempPath.reverse();
this.planetsNames[index]["distance"] = distance;
this.paths.push({
node: nodeCharecter,
path: tempPath.reverse(),
distance: distance,
});
tempPath = [];
});
}
}
|
c23457201dad8ac3ff8289fa4dd613c27b1c9a72
|
TypeScript
|
dguo/blood-moon
|
/blood-moon.ts
| 2.671875
| 3
|
import Color from 'color';
import {BaseColorScheme, Theme} from './types';
function lighten(hex: string, value: number): string {
const rgb = Color(hex)
.lighten(value)
.rgb()
.array();
const lightenedHex =
'#' +
rgb
.map(x => {
const xHex = Math.floor(x).toString(16);
return xHex.length === 1 ? '0' + xHex : xHex;
})
.join('');
return lightenedHex;
}
const black = '#10100E';
const gray = '#696969'; // Dim gray
const white = '#C6C6C4';
const brightWhite = '#FFFAFA'; // Snow
const green = '#009F6B'; // NCS green
const brightGreen = '#03C03C'; // Dark pastel green
const cyan = '#20B2AA'; // bright sea green
const brightCyan = '#00CCCC'; // Robin egg blue
const blue = '#0087BD'; // NCS blue
const brightBlue = '#007FFF'; // Azure
const magenta = '#9A4EAE';
const pink = '#FF1493'; // Deep pink
const brown = '#CD853F'; // Peru
const red = '#C40233'; // NCS red
const darkRed = '#800020'; // Oxblood
const brightRed = '#FF2400'; // Scarlet
const orange = '#EE7F2D'; // Princeton
const yellow = '#FFD700'; // Gold
const brightYellow = '#FDFF00'; // Lemon
const background = black;
const colors: BaseColorScheme = {
black,
gray,
white,
brightWhite,
green,
brightGreen,
cyan,
brightCyan,
blue,
brightBlue,
magenta,
pink,
brown,
red,
darkRed,
brightRed,
orange,
yellow,
brightYellow,
// UI
background,
foreground: white,
selection: darkRed,
selectionText: white,
ruler: lighten(background, 0.3),
// syntax
syntaxLink: blue,
syntaxComment: gray
};
const theme: Theme = {
colors,
meta: {
description: 'Dark and bold color scheme',
homepage: 'https://github.com/dguo/blood-moon',
name: 'blood-moon',
maintainer: 'Danny Guo'
}
};
export default theme;
|
746b04d3e571fae5984fd33dd176194900e44f23
|
TypeScript
|
lguertin/log2990
|
/server/app/routes/crossword/crossword-generator/crossWordCreator.ts
| 2.625
| 3
|
import { CrossWordGrid } from "./types/crosswordGrid";
import { GameDifficulty, GridWord, GRID_DIMENSION } from "../../../../../common/crossword/constant";
import { BlackCellFiller } from "./crossword-content-filler/blackCellFiller";
import { injectable } from "inversify";
import { WordFiller } from "./crossword-content-filler/wordFiller";
import { WordSlot, LEXICON_DEFINITION } from "./constant";
import { DataFetcher} from "../lexical-service/dataFetcher";
@injectable()
export class CrossWordCreator {
public static async createCrossWord(difficulty: GameDifficulty): Promise<Array<GridWord>> {
const grid: CrossWordGrid = new CrossWordGrid(GRID_DIMENSION);
const wordFiller: WordFiller = new WordFiller(difficulty);
BlackCellFiller.execute(grid);
wordFiller.execute(grid);
let gridWords: Array<GridWord> ;
gridWords = this.createParsedData(wordFiller.insertedWordsHistory);
for (const gridWord of gridWords) {
const definitions: string[] = await this.assignDefinitions(gridWord);
gridWord.definition = definitions[(difficulty === GameDifficulty.Easy) ? 0 : 1];
this.lookIfWordInDefinition(gridWord, definitions, 0);
}
return gridWords;
}
private static lookIfWordInDefinition(gridWord: GridWord, definitions: string[], index: number): string {
if ( gridWord.definition.search(" " + gridWord.word + " ") !== -1 ) {
gridWord.definition = definitions[index + 1];
if (this.hasNoDefinition(gridWord.definition)) {
gridWord.definition = definitions[index - 1].replace(" " + gridWord.word + " ", " ... ");
} else {
this.lookIfWordInDefinition(gridWord, definitions, index + 1);
}
}
return gridWord.definition;
}
private static hasNoDefinition(definition: string): boolean {
return definition === undefined;
}
private static createParsedData(dataInserted: Array<WordSlot>): Array<GridWord> {
const parsedData: Array<GridWord> = [];
for (const data of dataInserted) {
const newData: GridWord = {
posI: data.posI, posJ: data.posJ, direction: data.direction,
word: data.word.getWord(),
definition: ""
};
parsedData.push(newData);
}
return parsedData;
}
private static async assignDefinitions(gridWordData: GridWord): Promise<string[]> {
return JSON.parse(await DataFetcher.getApiData(LEXICON_DEFINITION + gridWordData.word));
}
}
|
4f232a52f4f121f960194a0a568dfda523a402f4
|
TypeScript
|
HaskellJacobCurry/haskell-ts
|
/dist/Typeclass/Control/Apply.d.ts
| 3.140625
| 3
|
import { HKT, URI1, URI2, Kind1, Kind2 } from '../../Common/HKT';
import { Functor, Functor1, Functor2, Functor2C } from '../Data/Functor';
/**
* class (Functor f) <= Apply f where
* ap :: f (a -> b) -> f a -> f b
* alias :: (<*>)
* liftA2 :: (a -> b -> c) -> f a -> f b -> f c
* fstAp :: f a -> f b -> f a
* alias :: (<*)
* sndAp :: f a -> f b -> f b
* alias :: (*>)
*
* laws
* - fmap f x = pure f <*> x
*
* default
* (<*>) = liftA2 id
* liftA2 f x y = f <$> x <*> y
* u *> v = (id <$ u) <*> v
* u <* v = liftA2 const u v
*/
interface IApply<F> {
ap: <A, B>(_: HKT<F, (_: A) => B>) => (_: HKT<F, A>) => HKT<F, B>;
liftA2: <A, B, C>(_: (_: A) => (_: B) => C) => (_: HKT<F, A>) => (_: HKT<F, B>) => HKT<F, C>;
}
interface IExtApply<F> {
fstAp: <A>(_: HKT<F, A>) => <B>(_: HKT<F, B>) => HKT<F, A>;
sndAp: <A>(_: HKT<F, A>) => <B>(_: HKT<F, B>) => HKT<F, B>;
}
interface Apply<F> extends Functor<F>, IApply<F> {
}
export { Apply };
export { Apply as IApply };
declare namespace Apply {
interface Base<F> extends IApply<F> {
}
let Def: <F>(_: Apply<F>) => IApply<F>;
interface Ext<F> extends IExtApply<F> {
}
let Ext: <F>(_: Apply<F>) => Ext<F>;
let instantiate: <F>() => <TApply extends Apply<F>>(_: TApply) => TApply & Ext<F>;
}
interface IApply1<F extends URI1> {
ap: <A, B>(_: Kind1<F, (_: A) => B>) => (_: Kind1<F, A>) => Kind1<F, B>;
liftA2: <A, B, C>(_: (_: A) => (_: B) => C) => (_: Kind1<F, A>) => (_: Kind1<F, B>) => Kind1<F, C>;
}
interface IExtApply1<F extends URI1> {
fstAp: <A>(_: Kind1<F, A>) => <B>(_: Kind1<F, B>) => Kind1<F, A>;
sndAp: <A>(_: Kind1<F, A>) => <B>(_: Kind1<F, B>) => Kind1<F, B>;
}
interface Apply1<F extends URI1> extends Functor1<F>, IApply1<F> {
}
export { Apply1 };
interface IApply2<F extends URI2> {
ap: <T0, A, B>(_: Kind2<F, T0, (_: A) => B>) => (_: Kind2<F, T0, A>) => Kind2<F, T0, B>;
liftA2: <T0, A, B, C>(_: (_: A) => (_: B) => C) => (_: Kind2<F, T0, A>) => (_: Kind2<F, T0, B>) => Kind2<F, T0, C>;
}
interface IExtApply2<F extends URI2> {
fstAp: <T0, A>(_: Kind2<F, T0, A>) => <B>(_: Kind2<F, T0, B>) => Kind2<F, T0, A>;
sndAp: <T0, A>(_: Kind2<F, T0, A>) => <B>(_: Kind2<F, T0, B>) => Kind2<F, T0, B>;
}
interface Apply2<F extends URI2> extends Functor2<F>, IApply2<F> {
}
export { Apply2 };
interface IApply2C<F extends URI2, T0> {
ap: <A, B>(_: Kind2<F, T0, (_: A) => B>) => (_: Kind2<F, T0, A>) => Kind2<F, T0, B>;
liftA2: <A, B, C>(_: (_: A) => (_: B) => C) => (_: Kind2<F, T0, A>) => (_: Kind2<F, T0, B>) => Kind2<F, T0, C>;
}
interface IExtApply2C<F extends URI2, T0> {
fstAp: <A>(_: Kind2<F, T0, A>) => <B>(_: Kind2<F, T0, B>) => Kind2<F, T0, A>;
sndAp: <A>(_: Kind2<F, T0, A>) => <B>(_: Kind2<F, T0, B>) => Kind2<F, T0, B>;
}
interface Apply2C<F extends URI2, T0> extends Functor2C<F, T0>, IApply2C<F, T0> {
}
export { Apply2C };
declare namespace Apply1 {
interface Base<F extends URI1> extends IApply1<F> {
}
let Def: <F extends URI1>(_: Apply1<F>) => IApply1<F>;
interface Ext<F extends URI1> extends IExtApply1<F> {
}
let Ext: <F extends URI1>(_: Apply1<F>) => Ext<F>;
let instantiate: <F extends URI1>() => <TApply extends Apply1<F>>(_: TApply) => TApply & Ext<F>;
}
declare namespace Apply2 {
interface Base<F extends URI2> extends IApply2<F> {
}
let Def: <F extends URI2>(_: Apply2<F>) => IApply2<F>;
interface Ext<F extends URI2> extends IExtApply2<F> {
}
let Ext: <F extends URI2>(_: Apply2<F>) => Ext<F>;
let instantiate: <F extends URI2>() => <TApply extends Apply2<F>>(_: TApply) => TApply & Ext<F>;
}
declare namespace Apply2C {
interface Base<F extends URI2, T0> extends IApply2C<F, T0> {
}
let Def: <F extends URI2, T0>(_: Apply2C<F, T0>) => IApply2C<F, T0>;
interface Ext<F extends URI2, T0> extends IExtApply2C<F, T0> {
}
let Ext: <F extends URI2, T0>(_: Apply2C<F, T0>) => Ext<F, T0>;
let instantiate: <F extends URI2, T0>() => <TApply extends Apply2C<F, T0>>(_: TApply) => TApply & Ext<F, T0>;
}
export default Apply;
|
0b9596a4da4ecb53b72dc73844f7f453172a6ef5
|
TypeScript
|
bluelovers/random
|
/test/distributions/array-fill.test.ts
| 2.53125
| 3
|
import random from '../..'
describe(`byte`, () =>
{
const fn = random.dfArrayFill();
const tests = [
['Array', new Array(10)],
['Uint8Array', new Uint8Array(10)],
['Buffer', Buffer.alloc(10)],
] as const;
tests.forEach(function (arr)
{
it(`${arr[0]}`, () =>
{
let ret = fn(arr[1]);
expect(ret).toHaveLength(10);
});
});
});
|
fbe7947734f39e55dc99193ee97e994d3347ac6c
|
TypeScript
|
UrosKuzmanov/MVC_mode_single_page_app
|
/TS/URLParser.ts
| 3.171875
| 3
|
export class URLParser{
hash:string
public constructor(hash:string){
this.hash=hash
}
private extractor():string[]{
const no_hash=this.hash.substring(1)
if(no_hash.length==0){
return []
}else{
return no_hash.split("/")
}
}
public parser():any{
let pars=this.extractor()
let controller="home"
let method="default"
let args: string[]=[]
if (pars.length==1){
controller=pars[0]
}else if(pars.length==2){
controller=pars[0]
method=pars[1]
}else if(pars.length>2){
controller=<string>pars.shift()
method=<string>pars.shift()
args=pars
}
return {
"controller":controller,
"method":method,
"args":args
}
}
}
|
3f6fbca29b129efbefa5988526fa4d0fe6af930d
|
TypeScript
|
andreineculau/git-resolver
|
/src/index.ts
| 2.578125
| 3
|
import logger from '@pnpm/logger'
import got = require('got')
import git = require('graceful-git')
import normalizeSsh = require('normalize-ssh')
import path = require('path')
import parsePref, {HostedPackageSpec} from './parsePref'
export {HostedPackageSpec}
const gitLogger = logger // TODO: add namespace 'git-logger'
let tryGitHubApi = true
export default function (
opts: {},
) {
return async function resolveGit (
wantedDependency: {pref: string},
): Promise<{
id: string,
normalizedPref: string,
resolution: ({commit: string, repo: string, type: 'git'} | {tarball: string}),
} | null> {
const parsedSpec = parsePref(wantedDependency.pref)
if (!parsedSpec) return null
const isGitHubHosted = parsedSpec.hosted && parsedSpec.hosted.type === 'github'
if (!isGitHubHosted || isSsh(wantedDependency.pref)) {
const commit = await resolveRef(parsedSpec.fetchSpec, parsedSpec.gitCommittish || 'master')
return {
id: parsedSpec.fetchSpec
.replace(/^.*:\/\/(git@)?/, '')
.replace(/:/g, '+')
.replace(/\.git$/, '') + '/' + commit,
normalizedPref: parsedSpec.normalizedPref,
resolution: {
commit,
repo: parsedSpec.fetchSpec,
type: 'git',
},
}
}
const parts = normalizeRepoUrl(parsedSpec).split('#')
const repo = parts[0]
const ghSpec = {
project: parsedSpec.hosted!.project,
ref: parsedSpec.hosted!.committish || 'HEAD',
user: parsedSpec.hosted!.user,
}
let commitId: string
if (tryGitHubApi) {
try {
commitId = await tryResolveViaGitHubApi(ghSpec)
} catch (err) {
gitLogger.warn({
err,
message: `Error while trying to resolve ${parsedSpec.fetchSpec} via GitHub API`,
})
// if it fails once, don't bother retrying for other packages
tryGitHubApi = false
commitId = await resolveRef(repo, ghSpec.ref)
}
} else {
commitId = await resolveRef(repo, ghSpec.ref)
}
const tarballResolution = {
tarball: `https://codeload.github.com/${ghSpec.user}/${ghSpec.project}/tar.gz/${commitId}`,
}
return {
id: ['github.com', ghSpec.user, ghSpec.project, commitId].join('/'),
normalizedPref: parsedSpec.normalizedPref,
resolution: tarballResolution,
}
}
}
async function resolveRef (repo: string, ref: string) {
const result = await git(['ls-remote', '--refs', repo, ref])
// should output something like:
// 572bc3d4e16220c2e986091249e62a5913294b25 refs/heads/master
// if no ref was found, assume that ref is the commit ID
if (!result.stdout) return ref
return result.stdout.match(/^[a-z0-9]+/)[0]
}
function normalizeRepoUrl (parsedSpec: HostedPackageSpec) {
const hosted = <any>parsedSpec.hosted // tslint:disable-line
return hosted.getDefaultRepresentation() === 'shortcut' ? hosted.git() : hosted.toString()
}
function isSsh (gitSpec: string): boolean {
return gitSpec.substr(0, 10) === 'git+ssh://'
|| gitSpec.substr(0, 4) === 'git@'
}
/**
* Resolves a 'hosted' package hosted on 'github'.
*/
async function tryResolveViaGitHubApi (
spec: {
user: string,
project: string,
ref: string,
},
) {
const url = [
'https://api.github.com/repos',
spec.user,
spec.project,
'commits',
spec.ref,
].join('/')
const response = await got(url, {json: true})
return response.body.sha
}
interface GitHubRepoResponse {
sha: string
}
|
51da3f63b3130c2d0fef6044f570232472079154
|
TypeScript
|
dopeybobo/feathers-service-builder
|
/examples/chat/services/user.ts
| 2.640625
| 3
|
import { Application } from '@feathersjs/feathers';
import * as errors from '@feathersjs/errors';
import { ServiceBuilder } from 'feathers-service-builder';
import { UserRequest, validateUserRequest } from './hooks/validate';
import { toExternalUser } from './hooks/output';
export interface User {
username: string;
name: string;
}
/**
* A simple service for creating and retrieving users. Uses an in-memory map, so users will not
* persist between executions.
*/
export interface UserService {
get(username: string): Promise<User>;
create(data: UserRequest): Promise<User>;
on(event: 'created', callback: ((data: UserRequest) => (Promise<void> | void)),
listener: string): void;
}
export function register(builder: ServiceBuilder, app: Application, path: string): UserService {
const users = new Map<string, User>();
return builder.newService()
.get()
.method(async id => {
if (!users.has(id)) {
throw new errors.NotFound();
}
return users.get(id);
})
// We can use a hook to format output
.formatHook(toExternalUser())
.create()
.validateInput(validateUserRequest())
.method(async data => {
// Pretend the stored user has extra fields like a database might assign
const user = { _id: 'gobbledygook', __v: 0, username: data.username, name: data.name };
users.set(data.username, user);
return user;
})
// We can also just use a simple method to format the output
.format(result => ({ username: result.username, name: result.name }))
.publishTo((_, hook) => hook.app.channel('active'))
.build(path, app);
}
|
53f42e5ee43a687a6941d12d9fc520b30099ddd6
|
TypeScript
|
bvanderdrift/select-experiment
|
/src/analysis.ts
| 3.109375
| 3
|
import { SelectionType } from "./CountryPicker";
export interface ExperimentDataPoint {
age: number;
selectionType: SelectionType;
optionCount: number;
selectionTime: number;
countryCode: string;
}
// Side-effects EVERYWHERE!
export const filterByType = (
data: ExperimentDataPoint[],
selectionType: SelectionType
) => data.filter((thing) => thing.selectionType === selectionType);
export const filterByTypeCount = (
data: ExperimentDataPoint[],
selectionType: SelectionType,
optionCount: number
) =>
filterByType(data, selectionType).filter(
(thing) => thing.optionCount === optionCount
);
export const getAverage = (subset: ExperimentDataPoint[]) =>
subset.length === 0
? 0
: subset.reduce((carry, next) => carry + next.selectionTime, 0) /
subset.length;
// export const output = `category,# Data Points,Avg. Time-To-Selection
// Dropdown,${filterByType("Dropdown").length},${getAverage(
// filterByType("Dropdown")
// )}
// Autocomplete,${filterByType("Autocomplete").length},${getAverage(
// filterByType("Autocomplete")
// )}
// Visual Card,${filterByType("VisualCard").length},${getAverage(
// filterByType("VisualCard")
// )}
// Textual Card,${filterByType("TextualCard").length},${getAverage(
// filterByType("TextualCard")
// )}
// category,Dropdown,Autocomplete,Visual Card,Textual Card
// 3,${getAverage(filterByTypeCount("Dropdown", 3))},${getAverage(
// filterByTypeCount("Autocomplete", 3)
// )},${getAverage(filterByTypeCount("VisualCard", 3))},${getAverage(
// filterByTypeCount("TextualCard", 3)
// )}
// 5,${getAverage(filterByTypeCount("Dropdown", 5))},${getAverage(
// filterByTypeCount("Autocomplete", 5)
// )},${getAverage(filterByTypeCount("VisualCard", 5))},${getAverage(
// filterByTypeCount("TextualCard", 5)
// )}
// 8,${getAverage(filterByTypeCount("Dropdown", 8))},${getAverage(
// filterByTypeCount("Autocomplete", 8)
// )},${getAverage(filterByTypeCount("VisualCard", 8))},${getAverage(
// filterByTypeCount("TextualCard", 8)
// )}
// 13,${getAverage(filterByTypeCount("Dropdown", 13))},${getAverage(
// filterByTypeCount("Autocomplete", 13)
// )},${getAverage(filterByTypeCount("VisualCard", 13))},${getAverage(
// filterByTypeCount("TextualCard", 13)
// )}
// 21,${getAverage(filterByTypeCount("Dropdown", 21))},${getAverage(
// filterByTypeCount("Autocomplete", 21)
// )},${getAverage(filterByTypeCount("VisualCard", 21))},${getAverage(
// filterByTypeCount("TextualCard", 21)
// )}
// 34,${getAverage(filterByTypeCount("Dropdown", 34))},${getAverage(
// filterByTypeCount("Autocomplete", 34)
// )},${getAverage(filterByTypeCount("VisualCard", 34))},${getAverage(
// filterByTypeCount("TextualCard", 34)
// )}
// 55,${getAverage(filterByTypeCount("Dropdown", 55))},${getAverage(
// filterByTypeCount("Autocomplete", 55)
// )},${getAverage(filterByTypeCount("VisualCard", 55))},${getAverage(
// filterByTypeCount("TextualCard", 55)
// )}
// `;
|
4a1aced56ced847a199e17f5b2d29ba83697b0bc
|
TypeScript
|
Rediker-Software/redux-data-service-react
|
/src/WithModelArray.ts
| 2.53125
| 3
|
import "rxjs/add/operator/switchMap";
import "rxjs/add/operator/combineLatest";
import { Observable } from "rxjs/Observable";
import { branch, ComponentEnhancer, mapPropsStreamWithConfig } from "recompose";
import { getDataService } from "redux-data-service";
import { plural } from "pluralize";
import rxjsConfig from "recompose/rxjsObservableConfig";
/**
* An HOC to inject a model array into a component given the name of the DataService for that model and a list of ids.
*
* Automatically updates (rerenders) the component when the observable updates and
* automatically unsubscribes on unmount
*/
export function withModelArray<P>(
dataServiceName: string,
idPropKey: string = dataServiceName + "Ids",
modelPropKey: string = plural(dataServiceName),
): ComponentEnhancer<P, P> {
return branch(
(props) => props[modelPropKey] == null && props[idPropKey] != null,
mapPropsStreamWithConfig(rxjsConfig)<any, P>((props$: Observable<any>) =>
props$.combineLatest(
props$.switchMap(props => getDataService(dataServiceName).getByIds(props[idPropKey])),
(props, model) => ({ [modelPropKey]: model, ...props }),
),
),
);
}
|
bf7cf276b55213ab0125c06de75adebf84fe4349
|
TypeScript
|
asteria-project/asteria-gaia
|
/src/com/asteria/gaia/common/lang/core/AsteriaRegistryAsync.ts
| 3.3125
| 3
|
import { AsteriaException } from '../exception/AsteriaException';
import { AsteriaObject } from './AsteriaObject';
/**
* The <code>AsteriaRegistryAsync</code> interface defines the API that you must implement to create asynchronous
* registries in Asteria projects.
*/
export interface AsteriaRegistryAsync<T> extends AsteriaObject {
/**
* Add the specified item to the registry.
*
* @param {T} item the item to add to the registry.
* @param {(err: AsteriaException)=> void} callback the callback method invoked once the item has been added.
*/
add(item: T, callback: (err: AsteriaException)=> void): void;
/**
* Remove the specified item from the registry.
*
* @param {T} item the item to remove from the registry.
* @param {(err: AsteriaException)=> void} callback the callback method invoked once the item has been removed.
*/
remove(item: T, callback: (err: AsteriaException)=> void): void;
/**
* Remove the item with the specified identifier from the registry.
*
* @param {string} id the identifier of the item to remove.
* @param {(err: AsteriaException)=> void} callback the callback method invoked once the item has been removed.
*/
removeId(id: string, callback: (err: AsteriaException)=> void): void;
/**
* Indicate whether the item with the specified identifier is registered in this registry (<code>true</code>),
* or not (<code>false</code>).
*
* @param {string} id the identifier of the item to check.
* @param {(err: AsteriaException, item: boolean)=> void)} callback the callback method invoked once process is
* finished.
*/
has(id: string, callback: (err: AsteriaException, exists: boolean)=> void): void;
/**
* Return the item with the specified identifier.
*
* @param {string} id the identifier of the item to get.
* @param {(err: AsteriaException, item: T)=> void)} callback the callback method invoked once the item has been
* found.
*/
get(id: string, callback: (err: AsteriaException, item: T)=> void): void;
/**
* Return an array of all items declared in this registry.
*
* @param {(err: AsteriaException, items: Array<T>)=> void)} callback the callback method invoked once the items
* have been collected.
*/
getAll(callback: (err: AsteriaException, items: Array<T>)=> void): void;
/**
* Return an array of all identifiers declared in this registry.
*
* @param {(err: AsteriaException, items: Array<string>)=> void)} callback the callback method invoked once the
* identifiers have been collected.
*/
getIds(callback: (err: AsteriaException, items: Array<string>)=> void):void;
}
|
cf031e9bc0bed1998a1b37742ae56f2b8dbab713
|
TypeScript
|
shortalla/list-programs
|
/src/app/modules/activity/services/activity.service.ts
| 2.6875
| 3
|
import { Injectable } from '@angular/core';
import { ApiService, ActivityOptions } from '../../../core/api/api.service';
import { ActivityModel } from '../models/activity.model';
import { ActivityState } from '../store/activity.reducer';
/**
* Service for handling events related to activities
*/
@Injectable()
export class ActivityService {
private _list: Object[];
get list(): Object[] {
return this._list;
}
constructor(private apiService: ApiService) {
this.loadActivities();
}
/**
* Initialize the activities list
*/
private loadActivities(): void {
this.apiService.listActivities().subscribe(
data => data.map(result => ActivityModel.fromJson(result)),
error => console.error(error),
);
}
/**
* List the activities for a single program
*
* @param programId The identifier of the program
*/
public listForProgram(programId: number): Promise<any> {
return this.apiService.listProgramActivities(programId).toPromise();
}
/**
* Add a new activity to a specific program.
*
* @param activity The activity state
*/
public add(activity: ActivityState) {
return this.apiService.addActivity(
activity.programId,
new ActivityModel(
activity.name,
activity.startDate,
activity.endDate
)
);
}
/**
* Delete a specific activity
*
* @param activityId The identifier of the activity
*/
public delete(activityId: number) {
return this.apiService.deleteActivity(activityId);
}
}
|
2e84a506bde976ddda8cf4557cf7b3d7eeddc025
|
TypeScript
|
zichenma/TypeScript_Crawler_Basic
|
/2_12_Class_inherents/demo.ts
| 4
| 4
|
class Person {
name = 'dell'; // 定义类属性
getName() {
return this.name;
}
}
const person = new Person();
// 类继承
class Teacher extends Person {
getTeacherName() {
return 'techer';
}
}
// 多太:
class Teacher1 extends Person {
getName() {
// 重写之后依然可以用 super 去调用父类中的方法
// return super.getName() + ' lee'; / dell lee
return 'lee';
}
getParentName() {
// super 可以指向父类中的方法
return super.getName() + ' lee';
}
}
// 运行 TS: ts-node demo.ts
const teacher = new Teacher();
console.log(teacher.getName()); // dell
console.log(teacher.getTeacherName()); // teacher
const teacher1 = new Teacher1();
console.log(teacher1.getName()); // lee
console.log(teacher1.getParentName()); // dell lee
|
7a45ac1e359cc30831bb68d5b658e2d84c799629
|
TypeScript
|
lfmm/talk-core
|
/src/lib/src/core/models/layout.model.ts
| 2.75
| 3
|
export interface LayoutState {
// right to left
rtl: boolean;
// visibility
show: {
header: boolean,
nav: boolean,
content: boolean,
aside: boolean,
footer: boolean
};
// sizes
sizes: {
header: number,
nav: number,
content: number,
aside: number,
footer: number
};
}
export const initialLayoutState: LayoutState = {
rtl: false,
show: {
aside: true,
content: true,
footer: true,
header: true,
nav: true
},
sizes: {
aside: 20,
content: 80,
footer: 10,
header: 20,
nav: 20
}
};
|
fe79dd052981e8b2148bd900cdc5d81a4a93a669
|
TypeScript
|
marco-c/gecko-dev-wordified-and-comments-removed
|
/dom/webgpu/tests/cts/checkout/src/common/framework/resources.ts
| 2.78125
| 3
|
let
baseResourcePath
=
'
.
/
resources
'
;
let
crossOriginHost
=
'
'
;
function
getAbsoluteBaseResourcePath
(
path
:
string
)
{
if
(
path
[
0
]
=
=
=
'
/
'
)
{
return
path
;
}
const
relparts
=
window
.
location
.
pathname
.
split
(
'
/
'
)
;
relparts
.
pop
(
)
;
const
pathparts
=
path
.
split
(
'
/
'
)
;
let
i
;
for
(
i
=
0
;
i
<
pathparts
.
length
;
+
+
i
)
{
switch
(
pathparts
[
i
]
)
{
case
'
'
:
break
;
case
'
.
'
:
break
;
case
'
.
.
'
:
relparts
.
pop
(
)
;
break
;
default
:
relparts
.
push
(
pathparts
[
i
]
)
;
break
;
}
}
return
relparts
.
join
(
'
/
'
)
;
}
function
runningOnLocalHost
(
)
:
boolean
{
const
hostname
=
window
.
location
.
hostname
;
return
hostname
=
=
=
'
localhost
'
|
|
hostname
=
=
=
'
127
.
0
.
0
.
1
'
|
|
hostname
=
=
=
'
:
:
1
'
;
}
export
function
getCrossOriginResourcePath
(
pathRelativeToResourcesDir
:
string
onlineUrl
=
'
'
)
{
if
(
crossOriginHost
!
=
=
'
'
)
{
return
(
crossOriginHost
+
getAbsoluteBaseResourcePath
(
baseResourcePath
)
+
'
/
'
+
pathRelativeToResourcesDir
)
;
}
if
(
runningOnLocalHost
(
)
)
{
let
crossOriginHostName
=
'
'
;
if
(
location
.
hostname
=
=
=
'
localhost
'
)
{
crossOriginHostName
=
'
http
:
/
/
127
.
0
.
0
.
1
'
;
}
else
{
crossOriginHostName
=
'
http
:
/
/
localhost
'
;
}
return
(
crossOriginHostName
+
'
:
'
+
location
.
port
+
getAbsoluteBaseResourcePath
(
baseResourcePath
)
+
'
/
'
+
pathRelativeToResourcesDir
)
;
}
return
onlineUrl
;
}
export
function
getResourcePath
(
pathRelativeToResourcesDir
:
string
)
{
return
baseResourcePath
+
'
/
'
+
pathRelativeToResourcesDir
;
}
export
function
setBaseResourcePath
(
path
:
string
)
{
baseResourcePath
=
path
;
}
export
function
setCrossOriginHost
(
host
:
string
)
{
crossOriginHost
=
host
;
}
|
cc8c0f513d2f18d66e579cb4cb66378e8c8e8aa7
|
TypeScript
|
Trakkasure/graphics-experiments
|
/objects/DataModel/DataStructures.ts
| 3.15625
| 3
|
import { Vector2D } from "./Physics";
export class Point2D {
// Point
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x=x;
this.y=y
}
add(v: Vector2D) {
return new Point2D(v.mx+this.x,v.my+this.y);
}
}
export interface Bounds {
x1: number;
y1: number;
x2: number;
y2: number;
}
export function isRect(obj: Rect | object): obj is Rect {
return !!(<Rect>obj).getBounds;
}
export interface Rect {
getBounds(): Bounds;
intersects(obj: Rect | Bounds): boolean;
exits(obj: Rect | Bounds): boolean;
getIntersection(obj: Rect | Bounds): Bounds;
contains(obj: Point2D): boolean;
}
export class QuadTree implements Rect {
protected _points: Array<[Point2D,any]>=[];
protected _divided: boolean=false;
protected _children: Array<QuadTree>=[];
protected _center: Point2D;
constructor(protected _bounds: Bounds, protected _capacity: number, protected _parent: QuadTree=null) {
this._center = new Point2D(this._bounds.x2-(this._bounds.x2-this._bounds.x1)/2,this._bounds.y2-(this._bounds.y2-this._bounds.y1)/2);
}
walkTrees=function*(depthFirst:boolean=false) {
if (!depthFirst)
yield this;
if (this._divided) {
yield* this._children[0].walkTrees();
yield* this._children[1].walkTrees();
yield* this._children[2].walkTrees();
yield* this._children[3].walkTrees();
}
if (depthFirst)
yield this;
}.bind(this)
walkPoints=function*(depthFirst:boolean=false) {
if (!depthFirst)
for (let i=0;i<this._points.length;i++) yield this._points[i];
if (this._divided) {
yield* this._children[0].walkPoints();
yield* this._children[1].walkPoints();
yield* this._children[2].walkPoints();
yield* this._children[3].walkPoints();
}
if (depthFirst)
for (let i=0;i<this._points.length;i++) yield this._points[i];
}.bind(this)
parent(): QuadTree {
return this._parent;
}
getPoints() {
return this._points;
}
/* Returns true if point is within the tree */
contains(p: Point2D) {
if (!p) return false;
const b = this.getBounds();
return (
(p.x<=b.x2&&p.x>b.x1)&&
(p.y<=b.y2&&p.y>b.y1)
);
}
/* Returns true if any vertex is within _bounds */
intersects(obj: Bounds | Rect): boolean {
const b = isRect(obj)?obj.getBounds():obj;
const p = this.getBounds();
return ((p.x1<=b.x1&&p.x2>b.x1)&& // p.x1 < b.x1 < p.x2 - Upper left of B is within P
((p.y1<=b.y1&&p.y2>b.y1)|| // p.y1 < b.y1 < p.y2 - Upper left of B is within P
(p.y1<=b.y2&&p.y2>b.y2)) // p.y1 < b.y2 < p.y2 - Lower left of B is within P
||((p.x1<=b.x2&&p.x2>b.x2)&& // p.x1 < b.x2 < p.x2 - Lower Right of B is within P
((p.y1<=b.y2&&p.y2>b.y2)|| // p.y1 < b.y2 < p.y2 - Lower Right of B is within P
(p.y1<=b.y1&&p.y2>b.y1))) // p.y1 < b.y2 < p.y2 - Upper Right of B is within P
);
}
exits(obj: Rect | Bounds) {
return !this.intersects(obj);
}
getIntersection(obj: Rect| Bounds) {
const b = isRect(obj)?obj.getBounds():obj;
if (!this.intersects(b))
return {
x1:0,
x2:0,
y1:0,
y2:0
};
const p = this._bounds;
const x = [p.x1,p.x2,b.x1,b.x2].sort();
const y = [p.y1,p.y2,b.y1,b.y2].sort();
return {
x1:x[1],
x2:x[2],
y1:y[1],
y2:y[2]
};
}
insert(p: Point2D, userData:any):void {
if (!this.contains(p)) return;
if (this._points.length>=this._capacity) {
this.divide();
this._points.forEach((pts:[Point2D,any])=>{
// only top
const [pt,userData]=pts;
this._children[0].insert(pt,userData);
this._children[1].insert(pt,userData);
this._children[2].insert(pt,userData);
this._children[3].insert(pt,userData);
})
this._points=[];
}
if (this._divided) {
this._children[0].insert(p,userData);
this._children[1].insert(p,userData);
this._children[2].insert(p,userData);
this._children[3].insert(p,userData);
} else {
this._points.push([p,userData]);
}
}
divide():void {
this._divided=true;
this._children[0] = new QuadTree({x1:this._bounds.x1,y1:this._bounds.y1,x2:this._center.x,y2:this._center.y},this._capacity,this);
this._children[1] = new QuadTree({x1:this._center.x,y1:this._bounds.y1,x2:this._bounds.x2,y2:this._center.y},this._capacity,this);
this._children[2] = new QuadTree({x1:this._bounds.x1,y1:this._center.y,x2:this._center.x,y2:this._bounds.y2},this._capacity,this);
this._children[3] = new QuadTree({x1:this._center.x,y1:this._center.y,x2:this._bounds.x2,y2:this._bounds.y2},this._capacity,this);
}
getBounds():Bounds {
return this._bounds;
}
find(range: Rect): Array<[Point2D,any]> {
if (!range.intersects(this.getBounds())&&!this.intersects(range)) return [];
if (this._divided) {
return this._children.reduce((a: Array<[Point2D,any]>, c:QuadTree)=>a.concat(c.find(range)),[]);
}
return this._points.filter(p=>range.contains(p[0]));
}
findTreeFromPoint(p:Point2D) {
if (!this.contains(p)) return null;
// go deep...
if (this._divided)
return this._children[0].findTreeFromPoint(p)||this._children[1].findTreeFromPoint(p)||this._children[2].findTreeFromPoint(p)||this._children[3].findTreeFromPoint(p);
// bubble up lowest tree;
return this;
}
}
|
7a5ebcf0d81d36bffe4402f82cf8a1b9dfad17d4
|
TypeScript
|
jonatasrmoura/API-NLW04
|
/src/database/index.ts
| 2.625
| 3
|
import { Connection, createConnection, getConnectionOptions } from 'typeorm';
export default async(): Promise<Connection> => {
// aqui vou verificar se é um comando de teste ou se é um comando de ambiente de desenvolvimento
// vou pegar toda as informações que tenho dentro o ormconfig.json
const defaultOptions = await getConnectionOptions();
return createConnection(
// Se a variável de ambiente é teste então você vai usar um determinado banco de teste se não vc vai usar o banco padrão
Object.assign(defaultOptions, {
database: process.env.NODE_ENV === 'test'
? './src/database/database.test.sqlite'
: defaultOptions.database,
})
);
}
|
b280a6610dfec3050623275159fed1b49c43c395
|
TypeScript
|
R0mze5/react-test-pet-project
|
/src/features/reactApi/containers/HooksReducer/reducer.ts
| 3.21875
| 3
|
import { hooksActions } from './actions';
type TNotes = any;
interface IAction {
type: string;
payload?: any;
}
interface IState {
notes?: TNotes;
}
// interface IReducer {
// state: any,
// action: IAction
// }
// export default function(state: IState, action: IAction): IState {
// switch (action.type) {
// case 'TODO->ADD': {
// return [...state, { ...action.payload, completed: false }];
// }
// case 'TODO->DELETE': {
// return [...state.filter((todo: any) => todo.id !== action.payload)];
// }
// case 'TODO->COMPLETE': {
// return [
// ...state.map((todo: any) => {
// if (todo.id === action.payload) {
// todo.completed = !todo.completed;
// }
// return todo;
// }),
// ];
// }
// default:
// return state;
// }
// }
const handlers = {
[hooksActions.fetch]: (state: IState, action: IAction) => ({
...state,
notes: [...action.payload],
}),
[hooksActions.add]: (state: IState, action: IAction) => ({
...state,
notes: [...state.notes, { ...action.payload, completed: false }],
}),
[hooksActions.delete]: (state: IState, action: IAction) => {
return { ...state, notes: [...state.notes.filter((todo: any) => todo.id !== action.payload)] };
},
[hooksActions.complete]: (state: IState, action: IAction) => ({
...state,
notes: [
...state.notes.map((todo: any) => {
if (todo.id === action.payload) {
todo.completed = !todo.completed;
}
return todo;
}),
],
}),
DEFAULT: (state: IState) => state,
};
export const reducer = (state: IState, action: IAction): IState => {
const handle = handlers[action.type] || handlers.DEFAULT;
return handle(state, action);
};
export default reducer;
|
ffcb7f6d0877dca898df612fbce414e4a995a536
|
TypeScript
|
Prough123/cards
|
/src/n1-main/m2-bll/b1-registrationReducer/actions.ts
| 3.640625
| 4
|
export enum ACTIONS_TYPE {
CREATE_USER = 'Registration/CREATE_USER',
SET_IS_LOADING = 'Registration/SET_IS_LOADING',
SET_IS_REGISTERED = 'Registration/SET_IS_REGISTERED',
SET_ERROR = 'Registration/SET_ERROR',
}
export type NewUserData = {
email: null | string,
password: null | string,
}
//func to create an action creators
const makeActions = <T extends ACTIONS_TYPE, P>(type: T) => (payload: P) => ({type, payload})
//AC
export const setNewUserData = makeActions<ACTIONS_TYPE.CREATE_USER, NewUserData>(ACTIONS_TYPE.CREATE_USER);
export const setIsLoading = makeActions<ACTIONS_TYPE.SET_IS_LOADING, boolean>(ACTIONS_TYPE.SET_IS_LOADING)
export const setIsRegistered = makeActions<ACTIONS_TYPE.SET_IS_REGISTERED, boolean>(ACTIONS_TYPE.SET_IS_REGISTERED)
export const setError = makeActions<ACTIONS_TYPE.SET_ERROR, string | null>(ACTIONS_TYPE.SET_ERROR)
//object of AC
const actions = {
setNewUserData,
setIsLoading,
setIsRegistered,
setError,
}
//A[keyof A] returns type object ({type, payload}) that returns the function T extends ((...args: any) => infer R) ? R : any
//A should have { [key:string]: (...args: any[]) => any }} this is [nameAC]:(payload)=>{type, payload}
type IActionUnion<A extends { [key: string]: (...args: any[]) => any }> = ReturnType<A[keyof A]>
//create AC Types of the object actions
//combine all types of the actions
export type ActionsType = IActionUnion<typeof actions>
|
ceccf2df8152bc3ae6d142d6851b390c1635e898
|
TypeScript
|
baochengxu/ts-cesium
|
/src/plugin/lib/utils/OperationId.ts
| 2.90625
| 3
|
/*
* @Author: wuyue
* @Date: 2021-01-11 17:01:24
* @LastEditTime: 2021-03-07 02:06:07
* @LastEditors: Please set LastEditors
* @Description: 工具类
*/
import { EntityType } from '../ast'
export default class OperationId {
/**
* @description: 获取一个新的GUID
* @param {*} OperationId
* @return {*}
*/
static GetGUID() {
const gen = (count: number) => {
let out = ''
for (let i = 0; i < count; i++) {
out += (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return out
}
return [gen(2), gen(1), gen(1), gen(1), gen(3)].join('-')
}
/**
* @description: 对实体ID进行编码
* @param {string} type 实体类型
* @param {string} id
* @return {*} 格式:'Type_ChildrenType_占位_占位_ID'
*/
static EncodeEntityId({ type, children = '', id = this.GetGUID() }: { type: EntityType; children?: EntityType | ''; id: string | number }) {
console.log(`${type}_${children}_0_0_${id}`);
return `${type}_${children}_0_0_${id}`
}
/**
* @description: 生成组件id
* @param component
* @param id
*/
static generateComponentId(component: string, id: string) {
const lastId = id ? id : OperationId.GetGUID()
return `${component}_${lastId}`
}
/**
* @description: 对实体ID进行解码
* @param {string} id
* @return {*}
*/
static DecodeEntityId(id: string) {
const ids = id.split('_')
const result = {
type: '',
children: '',
id: ''
}
if (ids.length === 5) {
Object.assign(result, {
type: ids[0],
children: ids[1],
id: ids[4]
})
}
return result
}
}
|
26826e9af24e816d678ad9fe1939e8acc9d44593
|
TypeScript
|
MrWillTurner/cloud-prvider-openstack
|
/src/models/openstack/openstack-authentication-request.model.ts
| 2.5625
| 3
|
export interface OpenStackAuthenticationRequestConfig{
applicationId: string,
applicationSecret: string,
}
export class OpenStackAuthenticationRequest {
private _model: any;
constructor(_config: OpenStackAuthenticationRequestConfig) {
this._model = {
auth: {
identity: {
methods:[
'application_credential'
],
'application_credential': {
id: _config.applicationId,
secret: _config.applicationSecret
}
}
}
};
}
get model(): any {
return this._model;
}
}
|
1f449cc3dda561e1c51342df5c38e33c48bd8807
|
TypeScript
|
relief-melone/advent-of-code-2019-typescript
|
/test/test.08.02.ts
| 2.578125
| 3
|
import { expect } from 'chai';
import { mergeLayers, layerToGrid } from '../src/08.02/exec';
describe('Day 8 - Second Puzzle', () => {
it('correctly merges layers', () => {
expect(mergeLayers([
[0,2,2,2],
[1,1,2,2],
[2,2,1,2],
[0,0,0,0]
])).to.deep.equal(
[0,1,1,0]
);
});
it('correctly converts a layer into a grid', () => {
expect(layerToGrid([1,2,3,4,5,6],3,2)).to.deep.equal([
[1,2,3],
[4,5,6]
]);
});
});
|
415d6b8e7388d8de00f353e5c7c5b49bcb19a500
|
TypeScript
|
anst9000/music-events
|
/src/app/price-range.pipe.ts
| 2.625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'priceRange'
})
export class PriceRangePipe implements PipeTransform {
transform(value: number, ...args: any[]): string {
if (value > 100) {
return 'Expensive';
} else if (value > 30) {
return 'Average';
} else {
return 'Cheap';
}
}
}
|
e2cac9056b7cb47520758bde0e046d702be162b4
|
TypeScript
|
tabwrangler/tabwrangler
|
/app/js/__tests__/settings.test.ts
| 2.671875
| 3
|
import Settings from "../settings";
let mockFunctionGet: jest.Mock;
let mockFunctionSet: jest.Mock;
beforeEach(() => {
window.chrome = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:next-line
i18n: {
getMessage() {
return "";
},
},
storage: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:next-line
local: {},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:next-line
sync: {},
},
};
mockFunctionGet = jest.fn();
mockFunctionSet = jest.fn();
window.chrome.storage.sync.get = mockFunctionGet;
window.chrome.storage.sync.set = mockFunctionSet;
Settings.init();
});
afterEach(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore:next-line
window.chrome = {};
});
test("should set maxTabs to 1000", () => {
Settings.setmaxTabs("1000");
expect(Settings.get("maxTabs")).toBe(1000);
expect(mockFunctionSet.mock.calls.length).toBe(1);
});
test("should set maxTabs to 1", () => {
Settings.setmaxTabs("1");
expect(Settings.get("maxTabs")).toBe(1);
expect(mockFunctionSet.mock.calls.length).toBe(1);
});
test("should throw an exception when maxTabs is < 1", () => {
expect(() => Settings.setmaxTabs("0")).toThrowError();
});
test("should throw an exception when maxTabs is > 1000", () => {
expect(() => Settings.setmaxTabs("1100")).toThrowError();
});
|
8ac2f39f917df75a87a701eda270d6de1062bba5
|
TypeScript
|
tkow/key2union
|
/lib/file.ts
| 2.78125
| 3
|
import { existsSync } from 'fs';
import * as path from 'path';
import { CONFIG_NAME, DEFINITION_FILE,PACKAGE_JSON, UNIONTYPE_NAME } from './constants';
import { Config, JsonObject } from './interfaces';
import { tsTransform } from './tsTrasform';
export const getConfigFromPackageJson = (dir: string): Config | Error => {
const packageJsonPath = path.join(dir, PACKAGE_JSON);
if (!existsSync(packageJsonPath)) {
return Error('package.json does not exist on root directory');
}
const config = require(packageJsonPath)[CONFIG_NAME];
if (!config) {
return Error(`\"${CONFIG_NAME}\" property does not exist on package.json`);
}
const dFileName = config.module || DEFINITION_FILE
const emitModelKey: boolean = !!config.emitModelKey
const model = Array.isArray(config.model) ? config.model.map(_model => path.resolve(dir, _model)) : [path.resolve(dir,config.model)]
return {
model,
unionTypeName: config.unionType || UNIONTYPE_NAME,
emitModelKey,
watchDirs: config.watchDirs,
module: {
dFileName: `${dFileName}.d.ts`,
},
outputDir: path.resolve(dir,config.outputDir),
};
};
export const isJson = (extname: string): boolean => {
return extname.endsWith('.json');
};
export const isTypescript = (extname: string): boolean => {
return extname.endsWith('.ts');
};
export const isJavascript = (extname: string): boolean => {
return extname.endsWith('.js');
};
const modulePath = (filePath: string) => {
const moduleResolveRule = `${filePath}/index`
const extensions = ['.ts', '.js','.json']
for(let i = 0, len = extensions.length; i < len; i++) {
const ext = extensions[i]
const _modulePath = `${moduleResolveRule}${ext}`
if(existsSync(_modulePath)){
return [_modulePath, ext]
}
}
throw Error('module entry file extension type should be either .json or .ts|.js');
}
export const getTranslationFromModel = (
filePath: string,
): JsonObject | Error => {
let pathName = filePath
let extname = path.extname(filePath);
if(!extname) {
try {
[pathName, extname] = modulePath(pathName)
} catch(e) {
return e as Error
}
}
console.log(pathName)
if (isTypescript(extname)) { return tsTransform(pathName.replace(/\.ts/,'')) }
if (isJson(extname) || isJavascript(extname)) {
return require(pathName) as JsonObject;
}
return Error('module entry file extension type should be either .json or .ts|.js');
};
|
3275186065e6814a00fc8730d8373859bf494315
|
TypeScript
|
Tohman21/js-handy-filter
|
/src/condition-parser/index.ts
| 3.171875
| 3
|
import { isArray } from 'lib/type-guards';
import { Condition, ICondition, PlainCondition, SimpleValue, StringCondition } from 'conditions/types';
import { isICondition, isPlainCondition } from 'conditions/lib/type-guards';
import { ParseError } from './errors';
import { REGEXP_CONDITIONS_MAP, SIMPLE_CONDITIONS_MAP } from './lib/constants';
/**
* The class for parsing conditions.
*/
export class ConditionParser {
parse(condition: Condition): ICondition;
parse(conditions: Condition[]): ICondition[];
/**
* The method for parsing conditions.
*/
parse(conditions: Condition | Condition[]): ICondition | ICondition[] {
if (isICondition(conditions)) {
return conditions;
}
if (isPlainCondition(conditions)) {
return this.parsePlainCondition(conditions as PlainCondition<SimpleValue>);
}
if (isArray(conditions)) {
// In order to recursion works here need use an arrow function.
// conditions.map(this.parse) does not work here.
return conditions.map((condition) => this.parse(condition));
}
throw new ParseError(`Unable to parse ${conditions}`);
}
/**
* The method for parsing a plain condition.
*/
protected parsePlainCondition = ([stringCondition, value]: PlainCondition<any>): ICondition => {
const [path, key] = this.parseStringCondition(stringCondition);
if (key in SIMPLE_CONDITIONS_MAP) {
return SIMPLE_CONDITIONS_MAP[key as keyof typeof SIMPLE_CONDITIONS_MAP](path, value);
}
if (key in REGEXP_CONDITIONS_MAP) {
return REGEXP_CONDITIONS_MAP[key as keyof typeof REGEXP_CONDITIONS_MAP](path, value);
}
throw new ParseError(`${key} is not supported`);
};
/**
* The method for parsing a string condition.
*
* @param condition - Conditions to parse;
*/
protected parseStringCondition = (condition: StringCondition): [string, string] => {
const parsed = condition.split('__', 2);
let path = '';
let key;
if (parsed.length === 2) {
([path, key] = parsed);
} else {
key = parsed[0];
}
return [path, key];
};
}
export default new ConditionParser();
|
0d24224a05789055243cd998770fec578f44361a
|
TypeScript
|
eliocapelati/lp-demo-app-connector-api
|
/web/app/shared/models/app-installation/endpoint.model.ts
| 2.859375
| 3
|
import {Deserializable} from "../deserializable.model";
export class Endpoint implements Deserializable<Endpoint>
{
endpoint: string;
headers: Array<any>;
max_retries: number;
constructor(){
this.endpoint = "";
}
deserialize(input: any): Endpoint {
Object.assign(this, input);
return this;
}
isEndpointEmpty(): boolean{
return (!this.endpoint || this.endpoint == undefined || this.endpoint == "" || this.endpoint.length == 0);
}
}
|
51d2e8279aac573de16b788cfb047b09c1497588
|
TypeScript
|
neekolas/orm-redis
|
/src/Collections/RedisLazySet.ts
| 3.015625
| 3
|
import { getEntityFullId } from "../Metadata/Metadata";
import { EntityType, RedisManager } from "../Persistence/RedisManager";
import { LazySet } from "./LazySet";
/**
* Redis-backed lazy set
*
* @export
* @class RedisLazySet
* @template T
*/
export class RedisLazySet<T> extends LazySet<T> {
/**
* Manager instance
*
* @private
*/
private manager: RedisManager;
/**
* Full set id
*
* @private
*/
private setId: string;
/**
* Entity class
*
* @private
*/
private entityClass?: Function;
/**
* Cascade insert related entities
*
* @private
*/
private cascadeInsert: boolean;
/**
* Creates an instance of RedisLazySet.
* @param setId Full set id in redis
* @param manager Manager instance
* @param [entityClass] If passed then set will be treated as entity set and will return entities
*/
public constructor(setId: string, manager: RedisManager, entityClass?: EntityType<T>, cascadeInsert: boolean = false) {
super();
this.manager = manager;
this.setId = setId;
this.entityClass = entityClass;
this.cascadeInsert = cascadeInsert;
}
/**
* Add value or entity to the set
*
* @param value
* @returns
*/
public async add(value: T): Promise<void> {
if (this.entityClass) {
// Entity
if (this.cascadeInsert) {
await this.manager.save(value as any);
}
await this.manager.connection.client.saddAsync(this.setId, getEntityFullId(value)!);
} else {
const serializedVal = this.manager.serializeSimpleValue(value);
if (serializedVal) {
await this.manager.connection.client.saddAsync(this.setId, serializedVal);
}
}
}
/**
* Remove value or entity from the set.
*
* @param value
* @param [deleteEntity=false]
* @returns
*/
public async delete(value: T, deleteEntity: boolean = false): Promise<boolean> {
let res: number;
if (this.entityClass) {
// Entity
if (deleteEntity) {
await this.manager.remove(value as any);
}
res = await this.manager.connection.client.sremAsync(this.setId, getEntityFullId(value)!);
} else {
const serializedVal = this.manager.serializeSimpleValue(value);
if (serializedVal) {
res = await this.manager.connection.client.sremAsync(this.setId, serializedVal);
} else {
res = 0;
}
}
return res > 0 ? true : false;
}
/**
* Determine if value or entity exists in the set
*
* @param value
* @returns
*/
public async has(value: T): Promise<boolean> {
const id = this.entityClass ? getEntityFullId(value)! : this.manager.serializeSimpleValue(value);
if (typeof id === "undefined") {
return false;
}
const res = await this.manager.connection.client.sismemberAsync(this.setId, id);
return !!res;
}
/**
* Get size of set
*
* @returns
*/
public async size(): Promise<number> {
return await this.manager.connection.client.scardAsync(this.setId);
}
/**
* Clear set
*
* @param [deleteEntities=false] Also delete all entities
* @returns
*/
public async clear(deleteEntities: boolean = false): Promise<void> {
if (this.entityClass && deleteEntities) {
const setVals = await this.manager.connection.client.smembersAsync(this.setId);
await this.manager.removeById(this.entityClass, setVals);
}
await this.manager.connection.client.delAsync(this.setId);
}
/**
* Convert set to array
*
* @returns
*/
public async toArray(): Promise<T[]> {
const results: T[] = [];
for await (const v of this.values()) {
results.push(v);
}
return results;
}
/**
* Iterate over values
* @param scanCount Redis SCAN's COUNT option
*/
public async * values(scanCount?: number): AsyncIterableIterator<T> {
const scanOption = scanCount ? ["COUNT", scanCount] : [];
let [cursor, results]: [string, any[]] = await this.manager.connection.client.sscanAsync(this.setId, "0", ...scanOption);
// load entities
if (this.entityClass && results.length > 0) {
results = await this.manager.load(this.entityClass, results) as any;
} else {
results = results.map(res => this.manager.unserializeSimpleValue(res));
}
for (const res of results) {
yield res;
}
while (cursor !== "0") {
[cursor, results] = await this.manager.connection.client.sscanAsync(this.setId, cursor, ...scanOption);
// load entities
if (this.entityClass && results.length > 0) {
results = await this.manager.load(this.entityClass, results) as any;
} else {
results = results.map(res => this.manager.unserializeSimpleValue(res));
}
for (const res of results) {
yield res;
}
}
}
}
|
ccede94fe4f2c99c0c91c0ea32f0953748516cbf
|
TypeScript
|
5ocjal/tanks1990
|
/src/models/player.model.ts
| 2.59375
| 3
|
import { AnimationService } from '../utils/animationService';
import { Bullet } from './bullet.model';
import { PlayerState } from './enums/playerState';
import { Speed } from './enums/speed.enum';
export class Player extends Phaser.Physics.Arcade.Sprite {
config;
animationService = new AnimationService();
inputCursor;
name = null;
state = PlayerState.isIdle;
life = 3;
score = 0;
hasTurbo = 0;
hasArmor = 0;
hasCollection = 0;
isPlayer = true;
sounds = {
idle: null,
move: null,
shot: null,
};
constructor(config) {
super(config.scene, config.x, config.y, 'playerTank');
this.config = config;
this.scene.physics.world.enable(this);
this.setCollideWorldBounds(true);
this.setAngle(0);
this.setName(config.name);
this.setVelocityX(1.0);
this.setActive(true);
this.inputCursor = config.scene.input.keyboard.createCursorKeys();
config.scene.add.existing(this);
this.create();
}
create() {
this.config.scene.playersGroup.children.set(this);
this.sounds = {
idle: this.config.scene.sound.add('idle', { volume: 0.3 }),
move: this.config.scene.sound.add('move', { volume: 0.3 }),
shot: this.config.scene.sound.add('shot', { volume: 0.3 }),
}
}
playerControl() {
let oldState = this.state;
if (this.inputCursor.up.isDown) {
if (this.state === PlayerState.isMoving) return;
this.state = PlayerState.isMoving;
this.setVelocityY(-Speed.PLAYER);
this.setAngle(0);
} else if (this.inputCursor.down.isDown) {
if (this.state === PlayerState.isMoving) return;
this.state = PlayerState.isMoving;
this.setVelocityY(Speed.PLAYER);
this.setAngle(180);
} else if (this.inputCursor.left.isDown) {
if (this.state === PlayerState.isMoving) return;
this.state = PlayerState.isMoving;
this.setVelocityX(-Speed.PLAYER);
this.setAngle(270);
} else if (this.inputCursor.right.isDown) {
if (this.state === PlayerState.isMoving) return;
this.state = PlayerState.isMoving;
this.setVelocityX(Speed.PLAYER);
this.setAngle(90);
} else {
this.state = PlayerState.isIdle;
this.setVelocity(0);
}
if (Phaser.Input.Keyboard.JustDown(this.inputCursor.space)) {
this.sounds.shot.play();
new Bullet(this.config, this);
}
if (oldState !== this.state && oldState !== PlayerState.isDestroyed) {
this.playerMonitor();
}
}
playerMonitor() {
switch (this.state) {
case PlayerState.isIdle:
this.play('idle');
this.sounds.move.stop();
this.sounds.idle.loop = true;
// this.sounds.idle.play();
break;
case PlayerState.isMoving:
this.play('move');
this.sounds.idle.stop();
this.sounds.move.play();
break;
case PlayerState.isDestroyed:
this.sounds.idle.stop();
this.sounds.move.stop();
break;
default:
break;
}
}
}
|
37c6336021425947864f5ace295d78079da73cd3
|
TypeScript
|
viksatheboss/BeelivioTestTask
|
/Beelivio FrontEnd/BeelivioTaskApp/src/app/Services/auth.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import jwt_decode from "jwt-decode";
import { JWTModel } from 'src/app/Models/JWTModel';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public isLoggedIn() {
const token = this.getAuthToken();
if (token === null || token === undefined)
return false;
if (this.isTokenExpired(token))
return false;
return true;
}
public getAuthToken(): string |null{
return localStorage.getItem("AuthToken");
}
public isTokenExpired(token: string) {
let decodedToken: JWTModel = jwt_decode(token);
//const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
const expiry = decodedToken.exp * 1000;
return (Math.floor((new Date).getTime()) >= expiry)
}
}
|
f265feffbf2aa1a9d30003ba68224749864083b3
|
TypeScript
|
MaxStenex/express-blog
|
/server/src/models/User.ts
| 2.75
| 3
|
import mongoose, { Schema, Document } from "mongoose";
export interface UserType extends Document {
firstName: string;
lastName: string;
email: string;
password: string;
}
const userSchema: Schema = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
});
export default mongoose.model<UserType>("User", userSchema);
|
51bfde5f1efbe41cf2da552dae6bcc744e333db4
|
TypeScript
|
bodgery/bodgery-member-api
|
/test/pg-set-rfid.ts
| 2.578125
| 3
|
import * as assert from "assert";
import * as pg from "../src/db-pg";
import * as shortid from "shortid";
import {
error_handler
,get_pg_connection
,test_member_data
} from "../src/util";
describe( 'Changes a member\'s RFID', function () {
let db: pg.PG;
before( () => {
db = get_pg_connection();
});
it( 'Adds member, checks RFID, changes RFID', function (done) {
let start_rfid = shortid.generate();
let change_rfid = shortid.generate();
let check_old_rfid = (member_id) => {
db.get_member_rfid(
start_rfid
,() => {
assert( false, "Old RFID should no longer exist" );
done();
}
,() => {
assert( false, "Old RFID should no longer exist" );
done();
}
,() => {
assert( true, "Old RFID should no longer exist" );
done();
}
,error_handler
);
};
let check_rfid_finish = (member_id) => {
db.get_member_rfid(
change_rfid
,() => {
throw new Error( "RFID active, when it shouldn't be" );
check_old_rfid( member_id );
}
,() => {
assert( true, "RFID was changed" );
}
,() => {
throw new Error( "RFID was not found, when it should be" )
}
,error_handler
);
};
let set_new_rfid = (member_id) => {
db.set_member_rfid(
member_id
,change_rfid
,() => {
check_rfid_finish( member_id );
}
,() => error_handler(
new Error( "Could not find member ID: " + member_id )
)
,error_handler
);
};
let check_rfid_start = (member_id) => {
db.get_member_rfid(
start_rfid
,() => {
throw new Error( "RFID " + start_rfid + " was active" );
set_new_rfid( member_id );
}
,() => {
assert( true, "RFID is inactive to start with" );
done();
}
,() => {
throw new Error( "RFID " + start_rfid + " was not found" );
done();
}
,error_handler
);
};
db.add_member(
test_member_data( start_rfid )
,check_rfid_start
,error_handler
);
});
after( () => {
db.end();
});
});
|
792b5cb9f720c12e8bbdc4ec0b2bb649cf0b2d60
|
TypeScript
|
basvdijk/domusto-philips-hue
|
/index.ts
| 2.53125
| 3
|
import config from '../../config';
// DOMUSTO
import DomustoPlugin from '../../domusto/DomustoPlugin';
// INTERFACES
import { Domusto } from '../../domusto/DomustoTypes';
import DomustoSignalHub from '../../domusto/DomustoSignalHub';
import DomustoDevicesManager from '../../domusto/DomustoDevicesManager';
// PLUGIN SPECIFIC
let hue = require('node-hue-api');
let HueApi = hue.HueApi;
let lightState = hue.lightState;
/**
* GPIO plugin for DOMUSTO
* @author Bas van Dijk
* @version 0.0.1
*
* @class DomustoPhilipsHue
* @extends {DomustoPlugin}
*/
class DomustoPhilipsHue extends DomustoPlugin {
/**
* Creates an instance of DomustoPhilipsHue.
* @param {any} Plugin configuration as defined in the config.js file
* @memberof DomustoPhilipsHue
*/
constructor(pluginConfiguration: Domusto.PluginConfiguration) {
super({
plugin: 'Philips HUE controller',
author: 'Bas van Dijk',
category: Domusto.PluginCategories.system,
version: '0.0.1',
website: 'http://domusto.com'
});
this.pluginConfiguration = pluginConfiguration;
const isConfigurationValid = this.validateConfigurationAttributes(pluginConfiguration.settings, [
{
attribute: 'ip',
type: /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/
},
{
attribute: 'username',
type: 'string'
},
]);
if (isConfigurationValid) {
// Initialize hardware plugin
const philipsHue = new HueApi(pluginConfiguration.settings.ip, pluginConfiguration.settings.username);
this.hardwareInstance = philipsHue;
// Poll current Philips HUE status
setTimeout(() => {
this.refreshPhilipsHueStatus();
}, 100);
// // Start polling Philips HUE on interval to detect changes by hardware switches
setInterval(() => this.refreshPhilipsHueStatus(), pluginConfiguration.settings.pollInterval | 10000);
this.console.header(`${pluginConfiguration.id} plugin ready for sending / receiving data`);
}
}
/**
* Fired when a signal is send to the plugin
*
* @param {Domusto.Signal} signal
* @memberof DomustoPhilipsHue
*/
onSignalReceivedForPlugin(signal: Domusto.Signal) {
if (this.isLight(signal.deviceId)) {
this.setLightStatus(signal.deviceId, signal.data['state']);
} else if (this.isGroup(signal.deviceId)) {
this.setGroupStatus(signal.deviceId, signal.data['state']);
}
}
refreshPhilipsHueStatus() {
let devices = DomustoDevicesManager.getDevicesByPluginId(this.pluginConfiguration.id);
for (let device of devices) {
if (this.isLight(device.plugin.deviceId)) {
this.getLightStatus(device.plugin.deviceId);
} else if (this.isGroup(device.plugin.deviceId)) {
this.getGroupStatus(device.plugin.deviceId);
}
}
}
setLightStatus(lightId, state) {
let hueState = lightState.create();
if (state === 'on') {
this.hardwareInstance.setLightState(lightId.substr(1), hueState.on()).then(res => {
this.broadcastSignal(lightId, {
state: 'on'
});
});
} else if (state === 'off') {
this.hardwareInstance.setLightState(lightId.substr(1), hueState.off()).then(res => {
this.broadcastSignal(lightId, {
state: 'off'
});
});
}
}
setGroupStatus(groupId, state) {
let hueState = lightState.create();
if (state === 'on') {
this.hardwareInstance.setGroupLightState(groupId.substr(1), hueState.on()).then(res => {
this.broadcastSignal(groupId, {
state: 'on'
});
});
} else if (state === 'off') {
this.hardwareInstance.setGroupLightState(groupId.substr(1), hueState.off()).then(res => {
this.broadcastSignal(groupId, {
state: 'off'
});
});
}
}
getLightStatus(lightId) {
this.console.log('Getting status for light', lightId);
this.hardwareInstance.lightStatus(lightId.substr(1)).then(displayStatus => {
this.broadcastSignal(lightId, {
state: displayStatus ? 'on' : 'off'
});
});
}
getGroupStatus(groupId) {
this.console.log('Getting status for group', groupId);
this.hardwareInstance.getGroup(groupId).then(displayResults => {
this.broadcastSignal(groupId, {
state: displayResults.lastAction.on ? 'on' : 'off'
});
});
}
private isLight(deviceId) {
return deviceId[0] === 'L';
}
private isGroup(deviceId) {
return deviceId[0] === 'G';
}
}
export default DomustoPhilipsHue;
|
2913976c5447fc2e4819b56a8252da66357b4f6d
|
TypeScript
|
whisperlab/slonik
|
/src/factories/typeParsers/createTimestampTypeParser.ts
| 2.78125
| 3
|
import type {
TypeParser,
} from '../../types';
const timestampParser = (value: string | null) => {
return value === null ? value : Date.parse(value + ' UTC');
};
export const createTimestampTypeParser = (): TypeParser => {
return {
name: 'timestamp',
parse: timestampParser,
};
};
|
991a1da572b71d0b0cf6f2fee3c4556d26286bc0
|
TypeScript
|
craigfay/simtrader
|
/services/api/src/quote-providers/marketwatch.ts
| 2.765625
| 3
|
const fetch = require('node-fetch');
import { Quote } from '../entities';
/**
* Attempt to get a quote for a given symbol from Marketwatch
*/
export async function getQuote(symbol): Promise<Quote> {
try {
// Fetch HTML
const url = `https://www.marketwatch.com/investing/stock/${symbol}`;
const response = await fetch(url);
const text = await response.text();
// Parse HTML for price string
const [,rest] = text.split("session=\"after\">");
const [priceString] = rest.split("</bg-quote>")
return {
timestamp: new Date().toISOString(),
symbol,
price: Number(priceString),
provider: "MarketWatch",
}
}
catch (e) {
return {
timestamp: new Date().toISOString(),
symbol,
price: NaN,
provider: 'MarketWatch',
}
}
}
|
6950db94d66de8469fa8b441445584316c2737d4
|
TypeScript
|
strong-config/node
|
/src/e2e/validate.ts
| 2.640625
| 3
|
import chalk from 'chalk'
import type { Schema } from '../types'
// Needed for commonjs-compatibility
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/ban-ts-comment */
// @ts-ignore
import StrongConfig = require('@strong-config/node')
/* eslint-enable @typescript-eslint/no-require-imports, @typescript-eslint/ban-ts-comment */
console.log(chalk.bold('\nE2E Test: Validate config without base config'))
const strongConfig = new StrongConfig()
const config = strongConfig.getConfig()
let schema = strongConfig.getSchema() as Schema
let validationResult, validationError
try {
validationResult = strongConfig.validate(config, schema)
} catch (error) {
if (error instanceof Error) {
validationResult = false
validationError = error.message
} else {
throw error
}
}
console.log('\nValidation result: ')
if (validationResult) {
console.log('✅', validationResult)
} else {
console.log('❌', validationResult)
console.log(validationError)
}
console.log('')
console.log(chalk.bold('E2E Test: Validate config with base config'))
const strongConfigWithBaseConfig = new StrongConfig()
const mergedConfig = strongConfigWithBaseConfig.getConfig()
schema = strongConfigWithBaseConfig.getSchema() as Schema
try {
validationResult = strongConfigWithBaseConfig.validate(mergedConfig, schema)
} catch (error) {
if (error instanceof Error) {
validationResult = false
validationError = error.message
} else {
throw error
}
}
console.log('\nValidation result: ')
if (validationResult) {
console.log('✅', validationResult)
} else {
console.log('❌', validationResult)
console.log(validationError)
}
console.log('')
|
75558b7582c842d860b2cccb9bf53ab63bbc0139
|
TypeScript
|
KaiVolland/react-geo-baseclient
|
/src/state/reducers/ActiveModulesReducer.spec.ts
| 2.625
| 3
|
/* eslint-env jest*/
import reducer from './ActiveModulesReducer';
import {
ADD_ACTIVEMODULE,
REMOVE_ACTIVEMODULE
} from '../constants/ActiveModules';
const initialState: any[] = [];
describe('ActiveModulesReducer', () => {
it('returns the initial state', () => {
expect(reducer(undefined, {})).toEqual(initialState);
});
it('handles ADD_ACTIVEMODULE', () => {
const activeModule = [{
name: 'shinjiKagawaModule'
}];
const action = {
type: ADD_ACTIVEMODULE,
activeModule
};
const expectedState = [activeModule];
expect(reducer([], action)).toEqual(expectedState);
});
it('handles REMOVE_ACTIVEMODULE', () => {
const activeModuleIdx = 0;
const activeModules: object[] = [{
name: 'shinjiKagawaModule'
}];
const action = {
type: REMOVE_ACTIVEMODULE,
activeModuleIdx
};
const expectedState: any[] = [];
expect(reducer(activeModules, action)).toEqual(expectedState);
});
});
|
44cad8e313093eb336f76fa514b99a5fcb58788d
|
TypeScript
|
dudluk/experiment
|
/src/runtime/templating/anchors.ts
| 2.71875
| 3
|
import { DOM } from "../dom";
function hasAttribute(name) {
return this._element.hasAttribute(name);
}
function getAttribute(name) {
return this._element.getAttribute(name);
}
function setAttribute(name, value) {
this._element.setAttribute(name, value);
}
export function makeElementIntoAnchor(element: Element, proxy = false) {
let anchor = <any>DOM.createComment('anchor');
if (proxy) {
anchor._element = element;
anchor.hasAttribute = hasAttribute;
anchor.getAttribute = getAttribute;
anchor.setAttribute = setAttribute;
}
DOM.replaceNode(anchor, element);
return anchor;
}
|
6a2b8c46b733e7805864a151e970fbeedbd86ab8
|
TypeScript
|
src-zone/material
|
/bundle/src/testutils/util.ts
| 3.078125
| 3
|
/**
* Like spyOnAllFunctions, but that function has a bug in the current Jasmine, leading to exception
* when trying it on a foundation class.
*/
export function spyOnAll(object: any) {
let pointer = object;
while (pointer) {
for (const prop in pointer) {
if (object[prop] && object[prop].and)
// already spied on:
continue;
if (Object.prototype.hasOwnProperty.call(pointer, prop) && pointer[prop] instanceof Function) {
const descriptor = Object.getOwnPropertyDescriptor(pointer, prop);
if ((descriptor!.writable || descriptor!.set) && descriptor!.configurable) {
spyOn(object, prop).and.callThrough();
}
}
}
pointer = Object.getPrototypeOf(pointer);
}
return object;
}
|
ad578f3c42282e7e3b3a99bcc09508dc5f43660c
|
TypeScript
|
silky/refscript
|
/include/ambient/function.ts
| 3.359375
| 3
|
/*** Function ************************************************************/
interface Function {
/**
* Calls the function, substituting the specified object for the this
* value of the function, and the specified array for the arguments of the function.
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body
* as the original function.
* The this object of the bound function is associated with the specified
* object, and has the specified initial parameters.
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
prototype: any;
length: number;
// Non-standard extensions
arguments: any;
caller: Function;
}
declare var Function: {
/**
* Creates a new function.
* @param args A list of arguments the function accepts.
*/
//new (...args: string[]): Function;
//(...args: string[]): Function;
prototype: Function;
}
|
d942498aabcaa105d6cc721845b6051e0f84a43b
|
TypeScript
|
mukteshwarpatil/ApertureTechnologyRepo
|
/angular2-primeng-example-master/client/src/app/module/parser/interface.ts
| 2.65625
| 3
|
export class CourseData {
public columns: string[] = [];
public courses: any[] = [];
}
export interface ParserInterface {
parse(data: any): CourseData;
}
|
d35475796a2253da863b1116257a19e13c02a2c4
|
TypeScript
|
Coffeekraken/coffeekraken
|
/packages/postcss/s-postcss-sugar-plugin/src/node/mixins/color/docblocks.ts
| 2.625
| 3
|
import __SInterface from '@coffeekraken/s-interface';
import __STheme from '@coffeekraken/s-theme';
class postcssSugarPluginDocblockColorsMixinInterface extends __SInterface {
static get _definition() {
return {};
}
}
export { postcssSugarPluginDocblockColorsMixinInterface as interface };
/**
* @__name docblocks
* @__namespace node.mixin.color
* @__type PostcssMixin
* @__platform postcss
* @__status wip
*
* This mixin print the documentation docblocks for the colors
* into your final css.
*
* @__param {String} query The query string like ">tablet", "<=desktop", etc...
*
* @__snippet @sugar.color.docblocks
*
* @__example css
* \@sugar.color.docblocks;
*
* @__since 2.0.0
* @__author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
export default function ({ params, atRule, CssVars, replaceWith }) {
const vars = new CssVars();
const colorsObj = __STheme.get('color');
const colors = Object.keys(colorsObj);
colors.forEach((colorName) => {
const colorObj = colorsObj[colorName];
Object.keys(colorObj).forEach((modifier) => {
const colorValue = colorObj[modifier];
vars.comment(() =>
[
`/**`,
` * @name ${colorName}`,
` * @modifier ${modifier}`,
` * @namespace sugar.style.theme.${__STheme.name}.colors`,
` * @type color`,
` * @platform css`,
` * @status stable`,
` *`,
` * This is the "${colorName}${
modifier !== 'default' ? `-${modifier}` : ''
}" registered color`,
` *`,
` * @color ${colorValue}`,
` */`,
].join('\n'),
);
});
});
return vars;
}
|
f2d8cb3ed99728c10e147e60c91a36e2453438aa
|
TypeScript
|
Militao36/AppMaster
|
/src/controllers/Hero.ts
| 2.640625
| 3
|
import { NextFunction, Request, Response } from "express";
import heros from "../services/heros";
class HeroController {
async search(req: Request, res: Response, next: NextFunction) {
try {
const { q } = req.query
const data = await heros.search(q as string)
return res.status(200).json(data)
} catch (error) {
next(error)
}
}
async slug(req: Request, res: Response, next: NextFunction) {
try {
const { slug } = req.params
const data = await heros.slug(slug)
return res.status(200).json(data)
} catch (error) {
next(error)
}
}
}
export default new HeroController()
|
03fb99506939f1b858b5d72952ec105679b98264
|
TypeScript
|
tic40/chat-bots
|
/gas-fightclub-slackbot/src/services.ts
| 2.515625
| 3
|
const postToSlack = (
text: string,
channelName: string = SLACK_CHANNEL,
imageUrl = null
): void => {
const payload = {
text,
channel: channelName,
icon_emoji: SLACK_BOT_ICON_EMOJI,
username: SLACK_BOT_USERNAME,
}
if (imageUrl) {
payload.attachments = [
{
image_url: imageUrl,
},
]
}
UrlFetchApp.fetch(SLACK_WEBHOOK_URL, {
contentType: 'application/json',
method: 'post',
payload: JSON.stringify(payload),
})
}
const postToSlackDmChannel = (message: string) => {
UrlFetchApp.fetch('https://slack.com/api/chat.postMessage', {
method: 'post',
headers: { contentType: 'application/json' },
payload: {
token: DM_FROM_CHATBOT_APP_TOKEN,
channel: DM_FROM_CHATBOT_APP_DM_CHANNEL_ID,
text: message,
},
})
}
const getRate = () => {
const url = 'https://finance.yahoo.co.jp/quote/USDJPY=FX'
const contentText: string = UrlFetchApp.fetch(url).getContentText()
const matched = contentText.match(
new RegExp(
/{"countryCode":"USDJPY","name":"米ドル\/円","bid":{"value":"[\d|\.]+"},"ask":{"value":"([\d|\.]+)"}/
)
)
return !matched ? '' : matched[1]
if (!matched) {
return ''
}
return matched[1]
}
const getUserLocalMessage = (text: string): string => {
const url: string = `https://chatbot-api.userlocal.jp/api/chat?key=${USER_LOCAL_API_KEY}&message=${text}&bot_name=${SLACK_BOT_USERNAME}`
const res = UrlFetchApp.fetch(url)
return JSON.parse(res.getContentText()).result
}
const getTwitterTrends = (locationId: number): any[] => {
const url: string = `https://api.twitter.com/1.1/trends/place.json?id=${locationId}`
const res = UrlFetchApp.fetch(url, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${TWITTER_BEARER_TOKEN}`,
},
})
return JSON.parse(res.getContentText())[0].trends
}
const getTwitterTrendsMessage = (trends: any[], limit = 10): string => {
return trends
.slice(0, limit)
.map((t, i) => `${i + 1}. <${t.url}|${t.name}>`)
.join('\n')
}
const getWikipediaUrlAndBody = (q: string): { url: string; body: string } => {
const simpleWikipediaApi: string = 'http://wikipedia.simpleapi.net/api'
const url: string = `${simpleWikipediaApi}?keyword=${encodeURIComponent(
q
)}&output=json`
const res: any = JSON.parse(UrlFetchApp.fetch(url))
if (!res) {
return
}
return {
url: res[0].url,
body: res[0].body,
}
}
|
1471f18bd3349273e705e3881d9143e62d231d5c
|
TypeScript
|
Yeon22/TopCredu-Study-Angular
|
/angular-di-demo/src/app/factory/animal-factory.ts
| 3.21875
| 3
|
import { Animal, Config } from './animal';
//팩토리패턴
abstract class Factory {
// 객체 생성방법 결정
create() {
return this.createAnimal(new Config());
}
abstract createAnimal(Config): Animal;
}
export class AnimalFactory extends Factory {
// 객체 설정방법 결정
createAnimal(config: Config) {
config.bark = "야옹야옹";
config.name = "고양이";
return new Animal(config);
}
}
export function mainFactory() {
let myAnimal: Animal = (new AnimalFactory()).create();
return myAnimal;
}
|
dcfe1c3922b4772f0fa6bcf14a4c3039b31b712c
|
TypeScript
|
K24limiantao/cangku01
|
/src/routes/index.ts
| 2.8125
| 3
|
//定义路由 就是发送请求打开页面和接收请求返回页面
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var ListRoles = require('../models/ListRoles');
var Post = require("../post01");
var router = express.Router();
//获取登录后的名字
let login_name = "";
var allRoles : String[] = [];
let RoleNumber : number = 0;
let RoleNumberText = "";
//验证是否登录
const isAuthenticated = (req:any,res:any,next:any) => {
if(req.user == null){
res.status(403);
return res.send("You need to sign in");
}
next();
//return passport.authenticate('local')
}
//验证权限:是管理员还是普通用户
const validateRole = (req:any,res:any,next:any) => {
var whereStr = {"username":req.body.username}; // 查询条件
login_name = req.body.username;
Account.find(whereStr,function(err:any, result:any) {
if (err) throw err;
//console.log(result);
RoleNumber = result[0].role;
console.log(RoleNumber);
});
next();
}
//权限:管理员显示权限列表
const validateListRole = async (req:any,res:any,next:any) => {
//login_name = req.body.username;
console.log(login_name);
await Account.find({}, function(err:any, result:any) {
console.log("刚运行没有进来!!!")
if (err) throw err;
console.log("123",RoleNumber);
//判断登录人的role值
if(RoleNumber === 2){
//输出登录人的全部信息
console.log('kkkk', result.map((item: any) => item.role));
allRoles = result.map((item: any) => item.role);
console.log("123",allRoles);
return allRoles;
} else {
allRoles = result.filter((item: any) => item.role === RoleNumber);
//输出登录人的全部信息
console.log(allRoles[0]);
return RoleNumber;
}
});
next();
}
//显示管理员登录后界面
router.get('/admin',validateListRole ,function(req:any,res:any){
//第一次运行allRoles返回一个[]
console.log("456",allRoles);
res.render('admin',{ RoleList : allRoles });
});
router.post('/admin', function(req:any, res:any) {
passport.authenticate('local')(req, res, function () {
console.log("in");
res.redirect('/admin');
console.log("ont");
});
});
//显示登录页面
router.get('/login', function(req:any, res:any) {
res.render('login', { user : req.user });
});
router.post('/login', validateRole, function(req:any, res:any) {
//登陆成功后
passport.authenticate('local')(req,res,function(){
console.log(RoleNumber);
if(RoleNumber === 2){
res.redirect('/admin');
}else{
res.redirect('/user');
}
});
});
//显示普通用户登录后界面
router.get('/user',validateListRole,(req:any,res:any) => {
if(RoleNumber === 3){
res.render('user',{text:"普通用户"});
}
if(RoleNumber === 4){
res.render('user',{text:"游客"});
}
});
router.post('/user',(req:any, res:any) => {
/*const UpdatePost = MongoClient.connect(url, function(err:any, db:any) {
if (err) throw err;
var dbo = db.db("test01");
var whereStr = { "username" : login_name }; // 查询条件
var updateStr = {$set: { "username" : req.body.newusername }};
dbo.collection("users").updateOne(whereStr, updateStr, function(err:any, res:any) {
if (err) throw err;
console.log(login_name);
db.close();
});
});*/
//信息修改成功后
/*passport.authenticate('local')(req,res,function(){
res.redirect('/user');
});*/
});
router.get('/', function (req:any, res:any) {
res.render('index', { user : req.user });
});
//显示注册页面
router.get('/register', function(req:any, res:any) {
res.render('register', { });
});
router.post('/register', function(req:any, res:any) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err:any, account:any) {
if (err) {
return res.render('register', { account : account });
}
//注册成功后
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
//管理员权限:查询所有用户信息
router.get('/selectuser', function(req:any,res:any){
/*var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";*/
const GetAllPost = MongoClient.connect(url,function(err:any,db:any){
if(err) throw err;
var dbo = db.db("test01");
dbo.collection("users").find({}).toArray(function(err:any,result:any){
if(err) throw err;
//console.log(allUsers == result);
//console.log(allUsers === result);
//allUsers = result
res.render('selectuser',{ result });
db.close();
});
});
//res.render('selectuser',{ allUsers });
});
router.post('/selectuser', function(req:any, res:any) {
passport.authenticate('local')(req, res, function () {
res.redirect('/selectuser');
});
});
//管理员权限:删除用户
//isAuthenticated(), validateRole([]),
router.get('/deleteuser',function(req:any,res:any){
res.render('deleteuser',{ user:req.user })
});
router.post('/deleteuser',passport.authenticate('local'), function(req:any, res:any) {
res.render('deleteuser',{});
});
//普通用户权限:修改自己信息
router.get('/modify_information',function(req:any,res:any){
res.render('modify_information',{})
});
router.get('/logout', function(req:any, res:any) {
req.logout();
res.redirect('/');
});
router.get('/ping', function(req:any, res:any){
res.status(200).send("pong!");
});
module.exports = router;
function req(req: any, arg1: string): any {
throw new Error("Function not implemented.");
}
|
eb9e61c419b5ecc463f53b2b3e4da6c72b62b241
|
TypeScript
|
lqqokim/healthMonitoringPrediction
|
/frontend/pdm-web/src/client/sdk/pipes/match-name.pipe.ts
| 2.546875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'matchName' })
export class MatchNamePipe implements PipeTransform {
transform(list: any[], labelfield: string, searchText: string): any {
if (searchText && list && list.length > 0) {
searchText = searchText.toUpperCase();
return list.filter((item: any) => item[labelfield].toUpperCase().match(searchText));
} else {
return list;
}
}
}
|
10d3a5bf0d9396e6e1fcbfc12379337069dc439f
|
TypeScript
|
omarsagoo/sentry
|
/src/commands/moderation/unmute.ts
| 2.6875
| 3
|
import { Command } from 'discord-akairo';
import { Message, Permissions, GuildMember } from 'discord.js';
import { Mutes } from '../../models/mutes';
import { Servers } from '../../models/server';
import { unmute } from '../../structures/muteManager';
import { logUnmute } from '../../structures/logManager';
import { checkHigherOrEqualPermissions } from '../../utils/permissions';
export default class UnmuteCommand extends Command {
public constructor() {
super('unmute', {
aliases: ['unmute', 'unsilence'],
description: {
content: 'Unmute a user in the discord server.',
usage: 'unmute <user>',
examples: ['@temporis#6402', 'temporis', '111901076520767488', 'temp'],
},
category: 'moderation',
channel: 'guild',
clientPermissions: [
Permissions.FLAGS.MUTE_MEMBERS,
Permissions.FLAGS.MANAGE_ROLES,
Permissions.FLAGS.MANAGE_MESSAGES,
],
userPermissions: [
Permissions.FLAGS.MUTE_MEMBERS,
Permissions.FLAGS.MANAGE_ROLES,
Permissions.FLAGS.MANAGE_MESSAGES,
],
args: [
{
id: 'member',
type: 'member',
},
],
});
}
public async exec(msg: Message, { member }: { member: GuildMember }) {
// If they did not specify a member.
if (!member) {
return msg.util?.send('Please specify a user to unmute.');
}
// Check to make sure that we are not muting someone with an equal or higher role
if (await checkHigherOrEqualPermissions(msg, member))
return msg.util?.send(
'This member has a higher or equal role to you. You are unable to unmute them.'
);
let mutesRepos = this.client.db.getRepository(Mutes);
let serverRepo = this.client.db.getRepository(Servers);
let server = await serverRepo.findOne({
where: { server: msg.guild!.id },
});
// TODO: Could just swap this over to checking user roles later if we need to optimize DB
let mute = await mutesRepos.findOne({
where: { server: msg.guild!.id, user: member.id },
});
if (!mute) {
return msg.util?.send('That user is not muted.');
}
// TODO: Do not assume that the server has a muted role - could error
await unmute(mutesRepos, member, server!.mutedRole);
logUnmute(serverRepo, member, msg.member!);
return msg.util?.send(`Unmuted ${member.user}.`);
}
}
|
f510f30b0e11bce185816b531ebcbbf1669e05cf
|
TypeScript
|
tosbaha/editions
|
/projects/Mallard/src/authentication/services/apple-oauth.ts
| 2.765625
| 3
|
import invariant from 'invariant';
import qs from 'query-string';
import { authWithDeepRedirect } from '../deep-link-auth';
const appleRedirectURI =
'https://idapi.theguardian.com/auth/apple/auth-redirect-editions?redirect-for=editions';
const appleDeepLinkRedirectURI =
'theguardianeditions://auth/apple/auth-redirect';
const getAppleOAuthURL = (validatorString: string) =>
`https://appleid.apple.com/auth/authorize?${qs.stringify(
{
client_id: 'com.theguardian.editions',
response_type: 'code id_token',
redirect_uri: appleRedirectURI,
scope: ['name', 'email'].join(' '),
state: validatorString,
response_mode: 'form_post',
},
{ encode: true },
)}`;
/**
* Attempts to login with apple OAuth
*
* This flow is slightly different from google/facebook as we tell apple to redirect to identity,
* which then redirects back to an app deep link.
*
* Due to its dependency on `authWithDeepRedirect` it expects that auth to be completed
* with a deep link back into the app. The `invariant` calls will throw if they fail.
*
* They have been written here with strings that currently are ok to show in the UI.
*/
const appleAuthWithDeepRedirect = (validatorString: string): Promise<string> =>
authWithDeepRedirect(
getAppleOAuthURL(validatorString),
appleDeepLinkRedirectURI,
async (url) => {
invariant(
url.startsWith(appleDeepLinkRedirectURI),
'Sign-in cancelled',
);
const params = qs.parse(url.split('?')[1]);
invariant(params['apple-sign-in-token'], 'Something went wrong');
return params['apple-sign-in-token'] as string;
},
);
export { appleAuthWithDeepRedirect };
|
f94a5cbb96fbfc464b0133f7875750a064f95d77
|
TypeScript
|
mikeludemann/helperFunctions_TypeScript
|
/src/Math/Other/roundIndex.ts
| 2.640625
| 3
|
function roundIndex(value: number, index: number) {
result = 0;
if ((typeof value !== 'number')) {
return false;
}
if (index == null || index == "" || typeof index !== 'number') {
result = parseFloat(a.toFixed(1));
} else {
result = parseFloat(a.toFixed(index));
}
return result;
}
|