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
|
|---|---|---|---|---|---|---|
995eef1cacb70226671b326f5d600cef2d219d00
|
TypeScript
|
blink1073/phosphor-tabs
|
/test/src/tabpanel.ts
| 2.515625
| 3
|
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
'use strict';
import expect = require('expect.js');
import {
Property
} from 'phosphor-properties';
import {
Signal
} from 'phosphor-signaling';
import {
StackedPanel
} from 'phosphor-stackedpanel';
import {
Widget
} from 'phosphor-widget';
import {
Tab, TabBar, TabPanel
} from '../../lib/index';
function createContent(title: string): Widget {
var widget = new Widget();
TabPanel.setTab(widget, new Tab(title));
return widget;
}
describe('phosphor-tabs', () => {
describe('TabPanel', () => {
describe('.currentChangedSignal', () => {
it('should be a Signal', () => {
expect(TabPanel.currentChangedSignal instanceof Signal).to.be(true);
});
});
describe('.tabProperty', () => {
it('should be a Property', () => {
expect(TabPanel.tabProperty instanceof Property).to.be(true);
});
it('should default to `null`', () => {
var tabPanel = new TabPanel();
expect(TabPanel.tabProperty.get(tabPanel)).to.be(null);
});
});
describe('.getTab', () => {
it('should get the tab for the given widget', () => {
var tabPanel = new TabPanel();
var tab = new Tab('1');
TabPanel.setTab(tabPanel, tab);
expect(TabPanel.getTab(tabPanel)).to.eql(tab);
});
it('should be a pure delegate to `tabProperty`', () => {
var tabPanel = new TabPanel();
var tab = new Tab('1');
TabPanel.tabProperty.set(tabPanel, tab);
expect(TabPanel.getTab(tabPanel)).to.eql(tab);
expect(TabPanel.tabProperty.get(tabPanel)).to.eql(tab);
});
});
describe('.setTab', () => {
it('should set the tab for the given widget', () => {
var tabPanel = new TabPanel();
var tab = new Tab('1');
expect(TabPanel.getTab(tabPanel)).to.be(null);
TabPanel.setTab(tabPanel, tab);
expect(TabPanel.getTab(tabPanel)).to.eql(tab);
});
it('should be a pure delegate to `tabProperty`', () => {
var tabPanel = new TabPanel();
var tab0 = new Tab('0');
var tab1 = new Tab('1');
TabPanel.setTab(tabPanel, tab0);
expect(TabPanel.tabProperty.get(tabPanel)).to.eql(tab0);
});
});
describe('#constructor()', () => {
it('should accept no arguments', () => {
var tabPanel = new TabPanel();
expect(tabPanel instanceof TabPanel).to.be(true);
});
it('should add the `p-TabPanel` class', () => {
var tabPanel = new TabPanel();
expect(tabPanel.hasClass('p-TabPanel')).to.be(true);
});
it('should add a TabBar and a StackPanel', () => {
var tabPanel = new TabPanel();
expect(tabPanel.childAt(0) instanceof TabBar).to.be(true);
expect(tabPanel.childAt(1) instanceof StackedPanel).to.be(true);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the widget', () => {
var widget = createContent('red');
var tabPanel = new TabPanel();
tabPanel.addWidget(widget);
tabPanel.dispose();
expect(() => { tabPanel.widgets.length; } ).to.throwError();
});
});
describe('#currentChanged', () => {
it('should be emitted when the current widget is changed', () => {
var called = false;
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1]
tabPanel.currentChanged.connect(() => { called = true; });
tabPanel.currentWidget = widget1;
expect(called).to.be(true);
});
});
describe('#currentWidget', () => {
it('should get the currently selected widget', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1]
expect(tabPanel.currentWidget).to.eql(widget0);
});
it('should set the currently selected widget', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1]
tabPanel.currentWidget = widget1;
expect(tabPanel.currentWidget).to.eql(widget1);
});
});
describe('#tabsMovable', () => {
it('should get whether the tabs are movable by the user', () => {
var tabPanel = new TabPanel();
expect(tabPanel.tabsMovable).to.be(true);
});
it('should set whether the tabs are movable by the user', () => {
var tabPanel = new TabPanel();
tabPanel.tabsMovable = false;
expect(tabPanel.tabsMovable).to.be(false);
});
});
describe('#widgets', () => {
it('should get a shallow copy of the array of widgets', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
expect(tabPanel.widgets).to.eql([widget0, widget1]);
});
it('should set the widgets for the tab panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
tabPanel.widgets = [widget1, widget0]
expect(tabPanel.widgets).to.eql([widget1, widget0]);
});
});
describe('#widgetCount', () => {
it('should get the number of widgets in the tab panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
expect(tabPanel.widgetCount).to.be(2);
});
it('should be ready-only', () => {
var tabPanel = new TabPanel();
expect(() => { tabPanel.widgetCount = 0; }).to.throwError();
});
});
describe('#widgetAt()', () => {
it('should get the widget at a specific index', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
expect(tabPanel.widgetAt(0)).to.eql(widget0);
expect(tabPanel.widgetAt(1)).to.eql(widget1);
});
it('should return `undefined` if the index is out of range', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
expect(tabPanel.widgetAt(-1)).to.be(void 0);
expect(tabPanel.widgetAt(3)).to.be(void 0);
});
});
describe('#widgetIndex()', () => {
it('should get the index of a specific widget', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
expect(tabPanel.widgetIndex(widget0)).to.be(0);
expect(tabPanel.widgetIndex(widget1)).to.be(1);
});
it('should return `-1` if the widget is not contained in the tab panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0];
expect(tabPanel.widgetIndex(widget1)).to.be(-1);
});
});
describe('#addWidget()', () => {
it('should add a widget to the end of the panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0];
tabPanel.addWidget(widget1);
expect(tabPanel.widgetIndex(widget1)).to.be(1);
});
it('should move an existing widget to the end of the panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1];
tabPanel.addWidget(widget0);
expect(tabPanel.widgetIndex(widget0)).to.be(1);
expect(tabPanel.widgets.length).to.be(2);
});
});
describe('#insertWidget()', () => {
it('should insert a widget into the panel at the given index', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget2];
tabPanel.insertWidget(1, widget1);
expect(tabPanel.widgetIndex(widget1)).to.be(1);
});
it('should be clamped to the bounds of the widgets', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget2];
tabPanel.insertWidget(3, widget1);
expect(tabPanel.widgetIndex(widget1)).to.be(2);
tabPanel.insertWidget(-1, widget1);
expect(tabPanel.widgetIndex(widget1)).to.be(0);
});
it('should fail if the `TabPanel.tab` property as not been set', () => {
var widget = new Widget();
var tabPanel = new TabPanel();
expect(() => { tabPanel.insertWidget(0, widget); }).to.throwError();
});
});
describe('#moveWidget()', () => {
it('should move a widget from one index to another', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
tabPanel.moveWidget(0, 2);
expect(tabPanel.widgetIndex(widget0)).to.be(2);
});
it('should return `false` if index out of range', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
expect(tabPanel.moveWidget(1, 3)).to.be(false);
expect(tabPanel.moveWidget(-1, 1)).to.be(false);
});
});
describe('#removeWidgetAt()', () => {
it('should remove the widget at a specific index', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
expect(tabPanel.removeWidgetAt(0)).to.eql(widget0);
expect(tabPanel.widgets.length).to.be(2);
});
it('should return `undefined` if index out of range', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
expect(tabPanel.removeWidgetAt(-1)).to.be(void 0);
expect(tabPanel.removeWidgetAt(3)).to.be(void 0);
expect(tabPanel.widgets.length).to.be(3);
});
});
describe('#removeWidget()', () => {
it('should remove the widget from the panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
expect(tabPanel.removeWidget(widget1)).to.eql(1);
expect(tabPanel.widgets.length).to.be(2);
});
it('should return `-1` if not contained in the panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget2];
expect(tabPanel.removeWidget(widget1)).to.be(-1);
});
});
describe('#clearWidgets()', () => {
it('should remove all widgets from the panel', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
tabPanel.widgets = [widget0, widget1, widget2];
tabPanel.clearWidgets();
expect(tabPanel.widgets.length).to.be(0);
});
});
context('when the `tabCloseRequested` signal is emitted', () => {
it('should close the targeted widget', () => {
var widget0 = createContent('red');
var widget1 = createContent('green');
var widget2 = createContent('blue');
var tabPanel = new TabPanel();
var tab = TabPanel.getTab(widget1);
var tabBar = tabPanel.childAt(0) as TabBar;
tabPanel.widgets = [widget0, widget1, widget2];
tabBar.tabCloseRequested.emit({ index: 1, tab: tab });
requestAnimationFrame(() => {
expect(tabPanel.widgets).to.eql([widget0, widget2]);
});
});
});
});
});
|
032f4b666e8f05427f7f9bced3d633e028f6bd0e
|
TypeScript
|
ManiaciaChao/lab-asm
|
/lab4/task2/utils/obfuscator.ts
| 3
| 3
|
import { processByLine } from "./utils";
const shuffle = (src: Array<any>) => {
const res = Array.from(src);
for (let i = res.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[res[i], res[j]] = [res[j], res[i]];
}
return res;
};
const regex = {
blank: /^\s*$/,
label: /^.+:\s*;?.*$/,
comment: /^\s*;.+$/,
};
const file = "./input.txt";
const startFrom = 89;
(async () => {
const codes = [] as string[];
let codeBuffer = "";
let dingling = false;
await processByLine(file, (line, lineNum) => {
if (regex.blank.test(line)) {
return;
}
if (regex.label.test(line) || regex.comment.test(line)) {
codeBuffer += line + "\n";
dingling = true;
return;
}
if (dingling) {
codeBuffer += line;
dingling = false;
codes.push(codeBuffer);
codeBuffer = "";
} else {
codes.push(line);
}
});
let i = 0;
const mark = [] as number[];
const codesWithJmp = codes.map((code, index) => {
if (code.includes("proc") || code.includes("endp")) {
mark.push(index);
return code;
}
let res = `obfs_${i + startFrom} label far\n${code}`;
if (
index + 2 !== codes.length &&
!codes[index + 1].includes("proc") &&
!codes[index + 1].includes("endp")
) {
res += `\njmp far ptr obfs_${i + startFrom + 1}`;
}
i++;
return res;
});
let n = mark.length;
let res = [] as string[];
while (mark.length) {
const start = mark.shift();
const end = mark.shift();
const part = codesWithJmp.slice(start + 2, end);
res = [
...res,
codesWithJmp[start],
codesWithJmp[start + 1],
...shuffle(part),
codesWithJmp[end],
];
}
console.log(res.join("\n"));
})();
// (async () => {
// const codes = [] as string[];
// let codeBuffer = "";
// let dingling = false;
// await processByLine(file, (line, lineNum) => {
// if (regex.label.test(line) || regex.comment.test(line)) {
// codeBuffer += line + "\n";
// dingling = true;
// return;
// }
// if (dingling) {
// codeBuffer += line;
// dingling = false;
// codes.push(codeBuffer);
// codeBuffer = "";
// } else {
// codes.push(line);
// }
// });
// const codesWithJmp = codes.map((code, i) => {
// let res = `obfs_${i + startFrom} label far\n${code}`;
// if (i !== codes.length - 1) {
// res += `\njmp far ptr obfs_${i + startFrom + 1}`;
// }
// return res;
// });
// console.log(shuffle(codesWithJmp).join("\n"));
// console.log(codes.length + startFrom);
// })();
|
1e4530dd60dd8e60c277bc7c42f32aad2cd3aa6e
|
TypeScript
|
koreanwglasses/musaic
|
/src/core/TriGrid.ts
| 3.234375
| 3
|
import { Point, Color } from './Pixel';
import { Grid } from './Grid';
import { HashMap } from './HashMap';
export class TriGrid implements Grid {
private width: number;
private height: number;
private pixels: HashMap<Point, Color>;
private allPoints: Array<Point>;
private static readonly h = Math.sqrt(3) / 2;
public constructor(width: number, height: number) {
this.width = width;
this.height = height;
this.pixels = new HashMap<Point, Color>();
this.allPoints = new Array<Point>();
for(let i = 0; i < height / TriGrid.h; i++) {
for(let j = 0; j < width; j++) {
let x = i % 2 ? j + 0.5 : j;
let y = i * TriGrid.h;
let point = new Point(x, y);
this.pixels.set(point, Color.blank);
this.allPoints.push(point);
}
}
}
setColorAt(x: number, y: number, color: Color): void {
this.pixels.set(new Point(x, y), color);
}
getColorAt(x: number, y: number): Color {
return this.pixels.get(new Point(x, y));
}
isSet(x: number, y: number): boolean {
return !this.pixels.get(new Point(x, y)).equals(Color.blank);
}
getNeighborsOf(x: number, y: number): Iterable<Point> {
let neighbors = new Array<Point>();
neighbors.push(new Point(x - 1, y));
neighbors.push(new Point(x - 0.5, y + TriGrid.h));
neighbors.push(new Point(x + 0.5, y + TriGrid.h));
neighbors.push(new Point(x + 1, y));
neighbors.push(new Point(x + 0.5, y - TriGrid.h));
neighbors.push(new Point(x - 0.5, y - TriGrid.h));
let self_ = this;
return neighbors.filter((point) => {
return 0 <= point.getX() && point.getX() < self_.width
&& 0 <= point.getY() && point.getY() < self_.height;
});
}
getAllPoints(): Iterable<Point> {
return this.allPoints;
}
getWidth(): number {
return this.width;
}
getHeight(): number {
return this.height;
}
getCenter(): Point {
return this.allPoints[Math.floor(this.allPoints.length / 2 + this.width / 2)];
}
}
|
dbe1be7df61a97912140cef88de6cd1dd67bb81f
|
TypeScript
|
elfrog/json-express
|
/src/build-type.ts
| 2.75
| 3
|
import parse from './type-parser';
interface BuildTypeRecord {
[key: string]: BuildType;
}
class BuildType {
type: string;
record: BuildTypeRecord = null;
children: BuildType[] = null;
optional: boolean = false;
constructor(value: string) {
const parsed = parse(value, {}) as BuildType;
this.type = parsed.type;
this.record = parsed.record;
this.children = parsed.children;
}
}
export default BuildType;
export {
BuildTypeRecord
};
|
777a0c0faa30efa03b2209db8af7309c30bcfed6
|
TypeScript
|
thevtm/walidate
|
/src/message/standard-validator-error-message.ts
| 2.609375
| 3
|
import { ValidationErrorMessageFn } from "./validator-error-message";
export function stdErrorMsgFn(sufixFn: ValidationErrorMessageFn): ValidationErrorMessageFn {
return (args) => {
const { propertyPath } = args;
const sufix = sufixFn(args);
return propertyPath != null
? `Invalid property "${propertyPath}" value, expected ${sufix}`
: `Invalid value, expected ${sufix}`;
};
}
|
567dbb7c09dafbffd4a8e75dfbf81c7cbd15e022
|
TypeScript
|
tmdgusya/effective-typescript
|
/ch02/07/05.ts
| 3.21875
| 3
|
type AB_0705 = 'A' | 'B'
type AB12_0705 = 'A' | 'B' | 12
// OK, {"A", "B"} is a subset of {"A", "B"}:
const ab: AB_0705 = Math.random() < 0.5 ? 'A' : 'B'
const ab12: AB12_0705 = ab // OK, {"A", "B"} is a subset of {"A", "B", 12}
declare let twelve_0705: AB12_0705
const back_0705: AB_0705 = twelve_0705
// ~~~~ Type 'AB12' is not assignable to type 'AB'
// Type '12' is not assignable to type 'AB'
|
2f777e23f88e567de0096b82c13f0ee783633c08
|
TypeScript
|
yzw7489757/ceval
|
/src/utils/regExp.ts
| 2.6875
| 3
|
/**
* @desc : desc
* @author : ziwen
* @date : 2020-6-2 10:55:30
*/
import system from '../systemMap';
import { contains } from './index';
const BLACK_LIST_OPERATORS = []
const supportOperator = Array.from(new Set(
[].concat(
Object.keys(system.unaryOps).filter(item => !/\b\w+\b/.test(item)),
Object.keys(system.binaryOps),
Object.keys(system.ternaryOps),
Object.keys(system.syntaxOperator)
)
.filter(op => !contains(BLACK_LIST_OPERATORS, op))
.sort((a, b) => b.length - a.length)
))
export const whitespaceReg = /(\t|\n|\r|\s+)/;
export const commentReg = /^\/\*(.*?)\*\//;
export const stringReg = /^\'(.*?)\'|^\"(.*?)\"/;
export const stringGreedyReg = /^\'(.*)\'|^\"(.*)\"/;
// export const regExpReg = /^ExecReg\((.*)\)/;
export const number2bitReg = /^(0b[0|1]{1,})$/;
export const number8bitReg = /^(0[0-7]{1,})$/;
export const number010bitReg = /^(0\d*[8-9]{1,}\d*(\.\d+)?)$/; // 0开头的十进制 019 038 078
export const number10bitReg = /(^([1-9]\d*(\.\d+)|(\d*(\.\d+)?)))/; // 1-9 或者.开头的十进制
export const number16bitReg = /^(0x[0-9a-fA-F]{1,})$/;
export const numberEbitReg = /^((\d*\.?\d*)[e|E]((\-|\+)?\d+))/; // 科学计数法
export const variableReg = /^((_|$)?[0-9a-zA-Z|$|_]{1,})/;
export const operatorReg = new RegExp(`^(${supportOperator.map(r => `(\\${/\b\w+\b/.test(r) ? `${r}\\s+` : r.split('').join('\\')})`).join('|')})`);
export const unaryMapReg = new RegExp(`^(${Object.keys(system.unaryOps).filter(item => /\b\w+\b/.test(item)).join('|')})`);
export const unarySymbolMapReg = new RegExp(`^(${Object.keys(system.unaryOps).filter(item => !(/\b\w+\b/.test(item))).map(r => `\\s*\\${r}\\s*`).join('|')})`);
export const constsMapReg = new RegExp(`^(${Object.keys(system.consts).map(k=>`${k}`).join('|')})`)
export const execFactoryReg = (reg: RegExp, expr: string, cb: <T>(v: T) => T = (v => v)): string | undefined => {
reg.lastIndex = 0;
const result = reg.exec(expr);
if (result === null || result[0] === '') {
return cb(undefined)
} else {
return cb(result[1])
}
}
export const isUnaryOpeator = ({ value }) => Object.prototype.hasOwnProperty.call(system.unaryOps, value)
export const isBinaryOpeator = ({ value }) => Object.prototype.hasOwnProperty.call(system.binaryOps, value)
export const isTernaryOpeator = ({ value }) => Object.prototype.hasOwnProperty.call(system.ternaryOps, value)
|
bb891c98d4d6256e63b45dae7878953a5b2687e0
|
TypeScript
|
arthurTemporim/Rocket.Chat.js.SDK
|
/src/config/messageInterfaces.ts
| 2.53125
| 3
|
/** @todo contribute these to @types/rocketchat and require */
export interface IMessage {
rid: string | null // room ID
_id?: string // generated by Random.id()
t?: string // type e.g. rm
msg?: string // text content
alias?: string // ??
emoji?: string // emoji code
avatar?: string // url
groupable?: boolean // ?
bot?: any // integration details
urls?: string[] // ?
mentions?: string[] // ?
reactions?: { [emoji: string]: string[] } // emoji: [usernames]
location?: {
type: string // e.g. Point
coordinates: string[] // longitude latitude
}
attachments?: IAttachment[]
editedAt?: Date
editedBy?: {
_id: string
username: string
}
u?: { // the user who sent the message
_id: string
username: string
name: string
}
}
export interface IAttachment {
fields: IAttachmentField[]
color?: string
text?: string
ts?: string
thumb_url?: string
message_link?: string
collapsed?: boolean
author_name?: string
author_link?: string
author_icon?: string
title?: string
title_link?: string
title_link_download?: string
image_url?: string
audio_url?: string
video_url?: string
}
export interface IAttachmentField {
short?: boolean
title: 'string'
value: 'string'
}
|
c904cbde0ec62df6f5c1cc05a465522c2e7fb4bf
|
TypeScript
|
mikaelhadler/akpoho-invoicing-software
|
/frontend/src/store/auth/state.ts
| 2.609375
| 3
|
import { UserCompany, UserProfileSummary, UserSummary } from '../types';
export type LoginData = {
username: string;
password: string;
remember_me: boolean;
};
export type CurrentCompany = {
name: string;
id: string;
};
export interface AuthStateInterface {
token: string;
authFormMessage: {
message?: string;
type?: string;
};
loginData: LoginData;
userSummary: UserSummary | null;
userCompanies: UserCompany[] | null;
userProfile: UserProfileSummary | null;
currentCompany: CurrentCompany | null;
}
function state(): AuthStateInterface {
return {
token: '',
authFormMessage: { message: '', type: '' },
loginData: {
username: '',
password: '',
remember_me: false,
},
userCompanies: null,
userProfile: null,
userSummary: null,
currentCompany: null,
};
}
export default state;
|
e0c6e0d2c43a9d705700218abf79e6ed8617667f
|
TypeScript
|
kivilahtio/skicker-video-player
|
/test/helpers/testutils.ts
| 2.8125
| 3
|
import * as $ from "jquery";
import { LoggerManager } from "skicker-logger-manager";
import { VideoPlayer } from "../../src/VideoPlayer";
import * as dom from "./dom";
import { IVideoAPIOptions, VideoAPI, VideoPlayerStatus } from "../../src/VideoAPI";
const logger = LoggerManager.getLogger("Skicker.testutils");
/**
* Set this global module-level root Vue instance when starting to use this utility suite for a test case.
* This helps cut parameter passing to test wrappers and makes reading the tests cases smooth as ice.
*/
let vp: VideoPlayer;
/**
* Call this before using this test utility suite
* @param root instance to be the basis of css selector lookups and othe tests
*/
export const init = (vipa: VideoPlayer) => {
vp = vipa;
};
/**
* Used to wrap a nonError-based error notifications to proper Exceptions so the testing framework can properly detect Promise failures.
* @param err
*/
export const errorize = (err: any) => {
if (err instanceof Error) {
throw err;
} else {
throw new Error(err);
}
};
/**
*
* @param url Automatically create a test VideoPlayer and init the testutils-package with it.
* @param opts
* @param elementId
*/
export const createPlayer = (url: string|URL, opts?: IVideoAPIOptions, elementId?: string): VideoPlayer => {
try {
if (!elementId) {
elementId = "0";
}
if (!(url instanceof URL)) {
url = new URL(url);
}
if (!opts) {
opts = {};
}
const vpElement: HTMLElement = dom.appendBodyElement("div", `youtube-video-player${elementId}`, "video-player");
const videoPlayer = new VideoPlayer(vpElement, opts, url);
expect(videoPlayer)
.toEqual(jasmine.any(VideoPlayer)); //videoPlayer is a VideoPlayer
init(videoPlayer);
//VideoPlayer not yet injected into the given HTML element
const htmlElementsCreated: number =
$(vpElement)
.find("*")
.length;
expect(htmlElementsCreated)
.toEqual(0);
return videoPlayer;
} catch (err) {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
}
};
/**
* Seek the VideoPlayer to given position and assert we are within the given tolerance of the position
* @param pos seconds as a number, or a h:m:s || m:s notation as string
* @param tolerance
*/
export const seek = (pos: number | string, tolerance: number): Promise<VideoPlayer> => {
if (typeof(pos) === "string") { //This is a position like 1:05:22
let seconds: number = 0;
const hms: string[] = pos.split(":");
if (hms.length === 3) { //hms
seconds = Number(hms[0]) * 3600;
seconds += Number(hms[1]) * 60;
seconds += Number(hms[2]);
} else if (hms.length === 2) { //hms
seconds = Number(hms[0]) * 60;
seconds += Number(hms[1]);
} else if (hms.length === 1) { //hms
seconds = Number(hms[0]);
}
pos = seconds;
}
return vp
.seekVideo(pos)
.then((vapi: VideoPlayer) => {
const pos: number = (vp as any).videoAPI.getPosition();
expect(pos).toBeGreaterThanOrEqual(pos - tolerance, "Then video is seeked");
expect(pos).toBeLessThanOrEqual(pos + tolerance, "Then video is seeked");
return vapi;
})
.catch((err) => {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
});
};
export const start = (): Promise<VideoPlayer> =>
vp.startVideo()
.then((vapi: VideoPlayer) => {
expect(vp.getStatus())
.toBe(VideoPlayerStatus.started, "Then Video is started");
return vapi;
})
.catch((err) => {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
});
export const pause = (): Promise<VideoPlayer> =>
vp.pauseVideo()
.then((vapi: VideoPlayer) => {
expect(vp.getStatus()).toBe(VideoPlayerStatus.paused, "Then Video is paused");
return vapi;
})
.catch((err) => {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
});
export const stop = (): Promise<VideoPlayer> =>
vp.stopVideo()
.then((vapi: VideoPlayer) => {
expect(vp.getStatus()).toBe(VideoPlayerStatus.stopped, "Then Video is 'stopped'");
return vapi;
})
.catch((err) => {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
});
export const destroy = (vipa?: VideoPlayer): void => {
if (vipa === undefined) {
vipa = vp;
}
try {
const el = vipa.getRootElement();
vipa.destroy();
expect($("body").find(el)[0]).toBe(undefined);
expect((vipa as any).videoAPI).toBe(undefined);
vp = undefined;
} catch (err) {
err = errorize(err);
logger.fatal(err, err.stack);
throw err;
}
};
|
5c387943f0389ca68323c36fb6dec33e6396b3fc
|
TypeScript
|
ALuizGomes/Prova_POOII
|
/numero_1.ts
| 3.859375
| 4
|
// 1- Crie uma classe com os atributos produto, preço, quantidade, os métodos
// getters e setters. Crie validação para não aceitar nome em branco, preco e
// quantidade com valor 0 (zero). Considerando que são oferecidos descontos pelo
// número de quantidade comprada, seguindo a tabela abaixo:
// a) Até 10 unidades: não tem desconto;
// b) de 11 a 20 unidades: 10% de desconto;
// c) de 21 a 50 unidades: 20% de desconto;
// d) acima de 50 unidades: 25% de desconto.
// Imprima a seguinte mensagem: O produto xxx de preço 999, quantidade comprada
// de 999 teve o desconto de 999 e o valor pago foi de 99999.
class Compras{
constructor(
private _produtos: string,
private _preco: number,
private _quantidade: number,
) {}
get produtos(){
return this._produtos
}
get preco(){
return this._preco
}
get quantidade(){
return this._quantidade
}
set produtos(produtos: string){
if(produtos.length == 0){
throw new Error("Produto Sem Identificação")
}
this._produtos = produtos
}
set preco(preco: number){
if(preco == 0){
throw new Error("Preço de Produto Inválido")
}
this._preco = preco
}
set quantidade(quantidade: number){
if(quantidade == 0){
throw new Error("Quantidade do Pruduto Inválida")
}
}
precoTotal(){
return this.preco * this.quantidade
}
desconto(){
if(this.quantidade <= 10){
return 0
}else if(this.quantidade > 10 || this.quantidade <= 20){
return this.precoTotal() * 0.1
}else if(this.quantidade > 20 || this.quantidade <= 50){
return this.precoTotal() * 0.2
}else{
return this.precoTotal() * 0.25
}
}
valorFinal(){
if(this.quantidade <= 10){
return this.precoTotal()
} else{
return this.precoTotal() + this.desconto()
}
}
}
const compras = new Compras('Nescau', 2, 7)
console.log(compras)
// try{
// compras.produtos = 'Celular',
// compras.quantidade = 11,
// compras.preco = 2500
// }catch(err:any){
// console.log(err.message)
// }
console.log('O produto ', compras.produtos, ' de preço ', compras.preco, ' e quantidade comprada de ', compras.quantidade, ' teve o desconto de ', compras.desconto(),
' e o valor pago foi de ', compras.valorFinal())
|
02ffeb3913bac1ce1fa206bad4f9d96a2aeeb692
|
TypeScript
|
MaRu999/ReactCards
|
/src/game/Card.ts
| 3.578125
| 4
|
export default class Card {
value: number;
numberLiteral: string;
suite: string;
color: string;
constructor(value: number, suiteString: string) {
this.value = value;
this.numberLiteral = Card.getLiteral(value);
this.suite = suiteString;
if (this.suite === "♥" || this.suite === "♦") {
this.color = "red";
} else {
this.color = "black";
}
}
private static getLiteral(value: number): string {
if (value >= 2 && value <= 10) {
return value.toString();
} else if (value === 11) {
return "B";
} else if (value === 12) {
return "D";
} else if (value === 13) {
return "K";
} else if (value === 14) {
return "A";
} else {
throw new RangeError("Value is not in valid range (between 2 and 14)!");
}
}
}
|
b82f4f5f1745ea5a933bf4e8925b6f6e21161941
|
TypeScript
|
zeromq/zeromq.js
|
/src/util.ts
| 3.609375
| 4
|
// A union type of possible socket method names to leave available from the native Socket.prototype
type SocketMethods = "send" | "receive" | "join" | "leave"
/**
* This function is used to remove the given methods from the given socket_prototype
* to make the relevant socket types have only their relevant methods.
* @param socketPrototype
* @param methods
*/
export function allowMethods(socketPrototype: any, methods: SocketMethods[]) {
const toDelete = ["send", "receive", "join", "leave"] as SocketMethods[]
for (const method of toDelete) {
if (methods.includes(method)) {
delete socketPrototype[method]
}
}
}
|
6ee16ca8ac44a63887c8abf759632ddda5159c56
|
TypeScript
|
YiZhang-Paul/Focused_UI
|
/src/core/utilities/time-utility/time-utility.spec.ts
| 3.078125
| 3
|
import { TimeUtility } from './time-utility';
describe('time utility unit test', () => {
describe('isLeapYear', () => {
test('should return false for non leap years', () => {
const years = [1700, 1800, 1900, 2100];
for (const year of years) {
expect(TimeUtility.isLeapYear(year)).toBeFalsy();
}
});
test('should return true for leap years', () => {
const years = [1992, 2000, 2016, 2020, 2024];
for (const year of years) {
expect(TimeUtility.isLeapYear(year)).toBeTruthy();
}
});
});
describe('getMonthName', () => {
test('should return empty string for invalid month', () => {
expect(TimeUtility.getMonthName(-1)).toEqual('');
expect(TimeUtility.getMonthName(12)).toEqual('');
});
test('should return correct month names', () => {
expect(TimeUtility.getMonthName(0)).toEqual('January');
expect(TimeUtility.getMonthName(1)).toEqual('February');
expect(TimeUtility.getMonthName(2)).toEqual('March');
expect(TimeUtility.getMonthName(3)).toEqual('April');
expect(TimeUtility.getMonthName(4)).toEqual('May');
expect(TimeUtility.getMonthName(5)).toEqual('June');
expect(TimeUtility.getMonthName(6)).toEqual('July');
expect(TimeUtility.getMonthName(7)).toEqual('August');
expect(TimeUtility.getMonthName(8)).toEqual('September');
expect(TimeUtility.getMonthName(9)).toEqual('October');
expect(TimeUtility.getMonthName(10)).toEqual('November');
expect(TimeUtility.getMonthName(11)).toEqual('December');
});
});
describe('getDateSuffix', () => {
test('should return correct suffix', () => {
expect(TimeUtility.getDateSuffix(1)).toEqual('st');
expect(TimeUtility.getDateSuffix(2)).toEqual('nd');
expect(TimeUtility.getDateSuffix(3)).toEqual('rd');
expect(TimeUtility.getDateSuffix(4)).toEqual('th');
expect(TimeUtility.getDateSuffix(11)).toEqual('th');
expect(TimeUtility.getDateSuffix(12)).toEqual('th');
expect(TimeUtility.getDateSuffix(13)).toEqual('th');
expect(TimeUtility.getDateSuffix(14)).toEqual('th');
expect(TimeUtility.getDateSuffix(21)).toEqual('st');
expect(TimeUtility.getDateSuffix(22)).toEqual('nd');
expect(TimeUtility.getDateSuffix(23)).toEqual('rd');
expect(TimeUtility.getDateSuffix(24)).toEqual('th');
expect(TimeUtility.getDateSuffix(31)).toEqual('st');
});
});
});
|
b8d2fb837800f6cb51c8cf49b715b1508b0a0932
|
TypeScript
|
cjosue15/time-track
|
/src/utils/utils.ts
| 2.671875
| 3
|
import { Menu, MenuEnum, TitleEnum } from '../models/menu.constant';
export const transformTitleToClassName = (text: string): string => {
return text.toLowerCase().replaceAll(' ', '-');
};
export const capitalizeFirstLetter = (text: string): string => {
return text.charAt(0).toUpperCase() + text.slice(1);
};
export const changeTimeText = (text: Menu) =>
text === MenuEnum.WEEKLY ? TitleEnum.WEEK : text === MenuEnum.DAILY ? TitleEnum.DAY : TitleEnum.MONTH;
|
c37df1e85223441f9221beeff09ad816505376fe
|
TypeScript
|
xXD4rkC0d3rXx/task-manager
|
/client/src/states/selectors.ts
| 2.515625
| 3
|
import { createSelector } from '@reduxjs/toolkit'
import { AppState } from './store'
export const getGroupedTasks = createSelector(
(state: AppState) => state.tasks,
(state: AppState) => state.columns,
(state: AppState) => state.tags,
(tasks, columns, tags) => {
const selectedTags = tags.items.filter((tag) => tags.selectedTags?.includes(tag.id))
return columns.map((column) => ({
column,
columnTasks: tasks
.filter((task) => column.items.includes(task.id))
.filter((task) => (selectedTags.length ? selectedTags.some((tag) => tag.items.includes(task.id)) : true)),
}))
},
)
export const getTaskById = (taskId?: string) =>
createSelector(
(state: AppState) => state.tasks,
(state: AppState) => state.columns,
(state: AppState) => state.tags,
(tasks, columns, tags) => {
if (!taskId) {
return {}
}
const task = tasks.find((task) => task.id === taskId)
const column = columns.find((column) => column.items.includes(taskId))
const taskTags = tags.items.filter((tag) => tag.items.includes(taskId))
return {
...task,
columnId: column?.id,
tags: taskTags.map((tag) => tag.id),
}
},
)
|
d2eade5165e8d1f60827fcde3ebcbc774d163171
|
TypeScript
|
Xzya/easy-models
|
/__tests__/Example.spec.ts
| 2.90625
| 3
|
import { Model, KeyPaths, ValueTransformer } from "../lib";
describe("Example model using GitHub issues", () => {
enum GHIssueState {
Open = 0,
Closed,
}
class GHUser extends Model {
public readonly username: string;
public readonly url: string;
public readonly htmlUrl: string;
public static JSONKeyPaths(): KeyPaths<GHUser> {
return {
username: "login",
url: "url",
htmlUrl: "html_url",
};
}
}
class GHIssue extends Model {
public readonly url: string;
public readonly htmlUrl: string;
public readonly number: number;
public readonly state: GHIssueState;
public readonly reporterLogin: string;
public readonly assignee: GHUser;
public readonly assignees: GHUser[];
public readonly updatedAt: Date;
public title: string;
public body: string;
public retrievedAt: Date;
constructor() {
super();
this.retrievedAt = new Date();
}
public static JSONKeyPaths(): KeyPaths<GHIssue> {
return {
url: "url",
htmlUrl: "html_url",
number: "number",
state: "state",
reporterLogin: "user.login",
assignee: "assignee",
assignees: "assignees",
updatedAt: "updated_at",
title: "title",
body: "body",
};
}
public static updatedAtJSONTransformer(): ValueTransformer {
return ValueTransformer.forwardAndReversible(
(value: string) => {
return new Date(value);
},
(value: Date) => {
return value.toISOString();
},
);
}
public static stateJSONTransformer(): ValueTransformer {
return ValueTransformer.valueMappingTransformer({
"open": GHIssueState.Open,
"closed": GHIssueState.Closed,
});
}
public static assigneeJSONTransformer(): ValueTransformer {
return ValueTransformer.objectTransformer(GHUser);
}
public static assigneesJSONTransformer(): ValueTransformer {
return ValueTransformer.arrayTransformer(GHUser);
}
}
it("Should work", () => {
const values = {
"url": "https://api.github.com/repos/octocat/Hello-World/issues/1347",
"html_url": "https://github.com/octocat/Hello-World/issues/1347",
"number": 1347,
"state": "open",
"title": "Found a bug",
"body": "I'm having a problem with this.",
"user": {
"login": "octocat",
},
"assignee": {
"login": "octocat",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
},
"assignees": [
{
"login": "octocat",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
},
],
"updated_at": "2011-04-22T13:33:48.000Z",
};
let model: GHIssue;
let error: Error;
try {
model = GHIssue.from(values);
} catch (err) {
error = err;
}
expect(error).toBeUndefined();
expect(model).toBeDefined();
expect(model.url).toEqual("https://api.github.com/repos/octocat/Hello-World/issues/1347");
expect(model.htmlUrl).toEqual("https://github.com/octocat/Hello-World/issues/1347");
expect(model.number).toEqual(1347);
expect(model.state).toEqual(GHIssueState.Open);
expect(model.reporterLogin).toEqual("octocat");
expect(model.assignee).toBeDefined();
expect(model.assignee.username).toEqual("octocat");
expect(model.assignee.url).toEqual("https://api.github.com/users/octocat");
expect(model.assignee.htmlUrl).toEqual("https://github.com/octocat");
expect(model.assignees).toBeDefined();
expect(model.assignees.length).toEqual(1);
expect(model.assignees[0].username).toEqual("octocat");
expect(model.assignees[0].url).toEqual("https://api.github.com/users/octocat");
expect(model.assignees[0].htmlUrl).toEqual("https://github.com/octocat");
expect(model.updatedAt).toEqual(new Date("2011-04-22T13:33:48.000Z"));
expect(model.title).toEqual("Found a bug");
expect(model.body).toEqual("I'm having a problem with this.");
expect(model.retrievedAt).toBeDefined();
expect(model.retrievedAt).not.toBeNull();
expect(model.toJSON()).toEqual(values);
});
});
|
c196752aa3ee854a8b9dee980a5b00c83a20fff5
|
TypeScript
|
fhnaseer/printer-management
|
/src/app/models.ts
| 2.6875
| 3
|
export class Printer {
id: number;
name: string;
available: string;
reserved: boolean;
}
export class SensorData {
timestamp: number;
values: Values[];
}
export class Values {
value: number;
unit: string;
name: string;
}
export const MockedPrinters: Printer[] = [
{ id: 1, name: 'Pro01', available: 'No', reserved: true },
{ id: 2, name: 'Pro02', available: 'No', reserved: true },
{ id: 3, name: 'Pro03', available: 'Yes', reserved: false },
{ id: 5, name: 'Pro04', available: 'Yes', reserved: false },
{ id: 4, name: 'Pro05', available: 'No', reserved: true },
];
export const MockedPrinters2: Printer[] = [
{ id: 5, name: 'Pro05', available: 'Yes', reserved: false },
{ id: 3, name: 'Pro03', available: 'Yes', reserved: true },
{ id: 4, name: 'Pro04', available: 'No', reserved: true },
{ id: 1, name: 'Pro01', available: 'No', reserved: true },
{ id: 2, name: 'Pro02', available: 'No', reserved: true },
];
export const MockedPrinters3: Printer[] = [
{ id: 5, name: 'Pro05', available: 'Yes', reserved: false },
{ id: 3, name: 'Pro03', available: 'No', reserved: true },
{ id: 4, name: 'Pro04', available: 'No', reserved: true },
{ id: 1, name: 'Pro01', available: 'No', reserved: true },
{ id: 2, name: 'Pro02', available: 'No', reserved: true },
];
export const MockedPrinters4: Printer[] = [
{ id: 5, name: 'Pro05', available: 'Yes', reserved: false },
{ id: 1, name: 'Pro01', available: 'Yes', reserved: false },
{ id: 3, name: 'Pro03', available: 'No', reserved: true },
{ id: 4, name: 'Pro04', available: 'No', reserved: true },
{ id: 2, name: 'Pro02', available: 'No', reserved: true },
];
|
d423b07840f595256b5576c69cce6bd068287341
|
TypeScript
|
yuriity/color-scheme-editor
|
/src/app/core/models/theme-color-rule.spec.ts
| 2.71875
| 3
|
import * as tinycolor from 'tinycolor2';
import { ThemeColorRule } from './theme-color-rule';
describe('ThemeColorRule', () => {
describe('constructor', () => {
describe('"name" initialization', () => {
it('should take "tokenColor.name" if it modified', () => {
const tokenColor = { name: 'test_name' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.name).toBe('test_name');
});
it('should take "tokenColor.originalName" if it is not modified', () => {
const tokenColor = { originalName: 'test_name' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.name).toBe('test_name');
});
});
describe('"scope" initialization', () => {
it('should take "tokenColor.scope" if it modified', () => {
const tokenColor = { scope: 'test_scope' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.scope).toBe('test_scope');
});
it('should take "tokenColor.originalScope" if it is not modified', () => {
const tokenColor = { originalScope: 'test_scope' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.scope).toBe('test_scope');
});
});
describe('"fontStyle" initialization', () => {
it('should take "tokenColor.fontStyle" if it modified', () => {
const tokenColor = { fontStyle: 'test_bold' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.fontStyle).toBe('test_bold');
});
it('should take "tokenColor.originalFontStyle" if it is not modified', () => {
const tokenColor = { originalFontStyle: 'test_bold' } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.fontStyle).toBe('test_bold');
});
});
describe('"foreground" initialization', () => {
it('should take "tokenColor.color" if it modified', () => {
const color = tinycolor('#00ff00');
const tokenColor = { color } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.foreground).toBe('#00ff00');
});
it('should take "tokenColor.originalColor" if it is not modified', () => {
const color = tinycolor('#00ff00');
const tokenColor = { originalColor: color } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.foreground).toBe('#00ff00');
});
it('should properly take "tokenColor.color" if it tranparent', () => {
const color = tinycolor('#00ff0042');
const tokenColor = { color } as any;
const actual = new ThemeColorRule(tokenColor);
expect(actual.foreground).toBe('#00ff0042');
});
});
});
describe('toJSON()', () => {
it('should properly return JSON', () => {
const color = tinycolor('#00ff00');
const tokenColor = {
name: 'test_name',
scope: 'test_scope',
color,
fontStyle: 'test_bold'
} as any;
const themeColorRule = new ThemeColorRule(tokenColor);
const actual = JSON.stringify(themeColorRule);
expect(actual).toBe(
'{"name":"test_name","scope":"test_scope","settings":{"foreground":"#00ff00","fontStyle":"test_bold"}}'
);
});
});
});
|
2d8ed16f4c67de85391e8d6d6c217079949c35d5
|
TypeScript
|
Dipakgavhale/FrontEnd
|
/Typescript/Basic/Array/Array_methods/Insert_Delete_Replace_Splice.ts
| 4.03125
| 4
|
/*
splice method
Insert
splice(start: number, deleteCount: number, ...items: T[]): T[];
you want to add element in array then you call this method and pass the start index position, deleteCount is zero,then items.
ex arr.splice(1,0,10)
you can add multipale element but its add in sequencely like index of 1,2,3. Not add elements random index posission in array.
*/
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(2,0,6);
console.log("After Add one element in array : "+arr4);
var arr5:string[]=['a','b','c'];
console.log("\nOriginal array : "+arr5);
arr5.splice(2,0,'Dip','E','F');
console.log("After Add three elements in array : "+arr5);
/*
Delete
splice(start: number, deleteCount: number, ...items: T[]): T[];
you want to delete element in array then you call this method and pass the start index position, deleteCount is index posission.
ex arr.splice(1,2)
you can delete multipale element but its delete in sequencely like index of 1,2,3. Not delete elements random index posission in array.
*/
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(3,1);
console.log("After delete one elements in array : "+arr4);
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(1,2);
console.log("After delete two elements in array : "+arr4);
/*
replace
splice(start: number, deleteCount: number, ...items: T[]): T[];
you want to replace element in array then you call this method and pass the start index position, deleteCount is index posission and items.
ex arr.splice(2,1,100)
in this case first delete the 1 item of index posission 2 then add 100 of that posission.
you can replace multipale element but its replace in sequencely like index of 1,2,3. Not replace elements random index posission in array.
*/
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(2,1,100);
console.log("After replace one elements in array : "+arr4);
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(1,3,100,50,20);
console.log("After replace three elements in array : "+arr4);
var arr4:number[]=[11,5,7,9];
console.log("\nOriginal array : "+arr4);
arr4.splice(2,1,100,50,20);
console.log("After replace array : "+arr4);
|
a147786092b1a3d7b474928680a4f035a645dd8e
|
TypeScript
|
PBL-SPS/Student-Companion-APP
|
/redux/reducers/contactsSlice.ts
| 2.890625
| 3
|
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Contact } from "../../screens/ContactScreen";
// Define a type for the slice state
interface ContactsState {
contacts: Contact[];
}
// Define the initial state using that type
const initialState: ContactsState = {
contacts: [],
};
export const contactSlice = createSlice({
name: "contact",
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
addContacts: (state, action: PayloadAction<Contact[]>) => {
state.contacts = action.payload;
return state;
},
},
});
export const { addContacts } = contactSlice.actions;
export default contactSlice.reducer;
|
1e7b70d4e78ce42f5a7d39206b5ed56a823f1f5d
|
TypeScript
|
htuna07/food-delivery
|
/src/app/service/user.service.ts
| 2.75
| 3
|
import { Injectable } from "@angular/core";
import { of, Observable } from "rxjs";
@Injectable({
providedIn: "root",
})
export class UserService {
users: any[] = [
{
_id: "1",
name: "Kayne",
surname: " Scott",
phone: "123123",
email: "kayne20",
password: "12345",
},
{
_id: "2",
name: "Hareem",
surname: "Curry",
phone: "123123",
email: "Hareem50",
password: "54321",
},
{
_id: "3",
name: "",
surname: "",
phone: "",
email: "",
password: "",
},
];
constructor() {}
find(username: string, password: string): Observable<any> {
return of(
this.users.find(
(user) => user.email == username && user.password == password
)
);
}
get(userId: string): Observable<any> {
return of(this.users.find((user) => user._id == userId));
}
update(updated: any) {
this.users = this.users.map((user) => {
if (user._id == updated._id) {
return updated;
} else {
return user;
}
});
return of(updated);
}
register(user: any) {
user._id = (this.users.length + 1).toString();
this.users.push(user);
}
}
|
fa81f14bf613fac54ee4352be3affb950128bbc0
|
TypeScript
|
nionis99/JSCore
|
/02_oop_part_1/code/src/Bow.ts
| 3.125
| 3
|
import Weapon from "./Weapon";
export default class Bow extends Weapon {
constructor(value: number, weight: number, baseDamage: number, baseDurability: number) {
super("bow", value, weight, baseDamage, baseDurability);
}
polish() {
const polishedDurabilityModifier = this.getDurabilityModifier() + Weapon.MODIFIER_CHANGE_RATE;
const newDurabilityModifier = polishedDurabilityModifier >= Weapon.MAXIMUM_DURABILITY_MODIFIER
? Weapon.MAXIMUM_DURABILITY_MODIFIER
: polishedDurabilityModifier;
this.setDurabilityModifier(newDurabilityModifier);
}
}
|
b95218078a6f6dabc191ad0cc5d27e943b1d191c
|
TypeScript
|
AndreaNovelli1999/registrazione
|
/src/providers/auth-service/auth-service.ts
| 2.8125
| 3
|
import { Injectable } from '@angular/core';
//utilizzo md5 per eseguire hash della password
import * as md5 from "md5";
import {Observable} from 'rxjs/Observable';
//utilizzo classe storage per salvare e controllare la password dal login
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';
export class User {
name: string;
email: string;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}
@Injectable()
export class AuthService {
constructor(private storage: Storage){}
currentUser: User;
public login(credentials) { //controllo email e password per accesso
if (credentials.email === null || credentials.password === null) { //nel caso in cui non siano ancora state inserite le credenziali verrà mostrato il messaggio seguente
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
this.storage.get(credentials.email).then(password => {
if(md5(password) == md5(credentials.password)){ //confronto l'hash delle due password
observer.next(true);
observer.complete();
} else{
observer.next(false);
observer.complete();
}
});
});
}
}
public register(credentials) { //registrazione per nuovo utente utilizzando md5 per l'hash
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
this.storage.set(credentials.email, md5(credentials.password)); //criptazione della password tramite md5
observer.next(true);
observer.complete();
});
}
}
public getUserInfo() : User {
return this.currentUser;
}
public logout() { //logout dell'utente impostando l'user come null
return Observable.create(observer => {
this.currentUser = null;
observer.next(true);
observer.complete();
});
}
}
|
1efeafff541b69a9360e9203c50da5e3e1ad8a95
|
TypeScript
|
sobiemir/resistor
|
/src/app/toolbox/base/builder-operations.ts
| 2.546875
| 3
|
import { Renderer2 } from '@angular/core';
import { Point2D } from 'src/app/math/point2d';
import { DiagramService } from 'src/app/pages/diagram/diagram.service';
export abstract class BuilderOperations {
protected static _snapToGrid = true;
protected static _snapToGridSize = 10;
public constructor(
protected _renderer: Renderer2,
protected _diagramService: DiagramService
) { }
public static setSnapToGrid(snap: boolean, size: number): void {
this._snapToGrid = snap;
this._snapToGridSize = size;
}
public getMousePosition(event: MouseEvent): Point2D {
const ctm = this._diagramService.getViewbox().getScreenCTM();
if (ctm == null) {
throw new Error('There was an undefined error while executing getMousePosition function.');
}
let mx = (event.clientX - ctm.e) / ctm.a;
let my = (event.clientY - ctm.f) / ctm.d;
if (BuilderOperations._snapToGrid) {
const snapSize = BuilderOperations._snapToGridSize;
const halfSnap = snapSize / 2;
mx = ~~((mx + halfSnap) / snapSize) * snapSize;
my = ~~((my + halfSnap) / snapSize) * snapSize;
}
return new Point2D(mx, my);
}
}
|
c678b61f44e2a78823ef5750c1c2d5e58f4ba350
|
TypeScript
|
ByDSA/datune
|
/packages/strings/src/strings/scales/chromatic/spec/Cases.ts
| 2.609375
| 3
|
/* eslint-disable camelcase */
import { LangId } from "lang";
import { AEOLIAN_b1, COMMON, MAJOR, MINOR, Scale } from "scales/chromatic";
import stringify from "..";
type Case = [LangId, Scale, string];
export function getManualCases(): Case[] {
return [
[LangId.ES, MAJOR, "Mayor"],
[LangId.ES, MINOR, "Menor"],
[LangId.ES, AEOLIAN_b1, "Lidia Aumentada ♯2"],
[LangId.EN, MAJOR, "Major"],
[LangId.EN, MINOR, "Minor"],
[LangId.EN, AEOLIAN_b1, "Lydian Augmented ♯2"],
];
}
export function getAllCases(): Case[] {
const ALL_LANGS = [LangId.ES, LangId.EN];
const cartesian = (...z: any) => z.reduce(
(a: any, b: any) => a.flatMap((d: any) => b.map((e: any) => [d, e].flat())),
);
const cases: [LangId, Scale, string][] = cartesian(ALL_LANGS, [...COMMON]);
for (const tuple of cases) {
tuple.push(stringify(tuple[1], {
langId: tuple[0],
} ));
}
return cases;
}
|
fdb274dece44a4b8f8a0976a9a463258928bc167
|
TypeScript
|
niilante/egret-core
|
/src/extension/gui/managers/IPopUpManager.ts
| 2.71875
| 3
|
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
namespace egret.gui {
/**
* @class egret.gui.IPopUpManager
* @interface
* @classdesc
* 窗口弹出管理器接口。若项目需要自定义弹出框管理器,请实现此接口
*/
export interface IPopUpManager extends IEventDispatcher{
/**
* 模态遮罩的填充颜色
* @member egret.gui.IPopUpManager#modalColor
*/
modalColor:number;
/**
* 模态遮罩的透明度
* @member egret.gui.IPopUpManager#modalAlpha
*/
modalAlpha:number;
/**
* 弹出一个窗口。<br/>
* @method egret.gui.IPopUpManager#addPopUp
* @param popUp {IVisualElement} 要弹出的窗口
* @param modal? {boolean} 是否启用模态。即禁用弹出窗口所在层以下的鼠标事件。默认false。
* @param center? {boolean} 是否居中窗口。等效于在外部调用centerPopUp()来居中。默认true。
*/
addPopUp(popUp:IVisualElement,modal?:boolean,center?:boolean):void;
/**
* 移除由addPopUp()方法弹出的窗口。
* @method egret.gui.IPopUpManager#removePopUp
* @param popUp {IVisualElement} 要移除的窗口
*/
removePopUp(popUp:IVisualElement):void;
/**
* 将指定窗口居中显示
* @method egret.gui.IPopUpManager#centerPopUp
* @param popUp {IVisualElement} 要居中显示的窗口
*/
centerPopUp(popUp:IVisualElement):void;
/**
* 将指定窗口的层级调至最前
* @method egret.gui.IPopUpManager#bringToFront
* @param popUp {IVisualElement} 要最前显示的窗口
*/
bringToFront(popUp:IVisualElement):void;
/**
* 已经弹出的窗口列表
* @member egret.gui.IPopUpManager#popUpList
*/
popUpList:any[];
}
}
|
e6d5ea79f1ffeaa0969ba5340162b7c003d74949
|
TypeScript
|
IronOnet/codebases
|
/codebases/bestbuy.ca/src(1)/client/utils/imageUtils/index.ts
| 2.6875
| 3
|
import {objectFlattener} from "../../utils/flatteners";
import {ResponsiveImageType, ImageResType} from "models";
import {IBrowser as ScreenSize} from "redux-responsive";
import {ProductVideo} from "models";
/**
* getIncorrectlyMappedImageProps.
*
* Note: this function will return the incorrect image size and should
* be replaced with the global getImageProps utility. This needs to be done
* gradually as it will impact all CMS entries that use this component.
*
*/
export const getIncorrectlyMappedImageProps = (
image: Partial<ResponsiveImageType>,
screenSize: ScreenSize,
): ImageResType | null => {
if (screenSize.lessThan.small) {
return image.small || null;
} else if (screenSize.lessThan.medium) {
return image.medium || image.small || null;
}
return image.large || image.medium || image.small || null;
};
/** ----------------------------------------------------------------- */
export const getImageSize = (images: Partial<ResponsiveImageType>, screenSize: ScreenSize) => {
if (screenSize && screenSize.lessThan) {
if (screenSize.lessThan.small) {
return images.extraSmall;
} else if (screenSize.lessThan.medium) {
return images.small;
} else {
return images.medium;
}
}
// Return default image size
return images.small;
};
export const getImageProps = (
imageData: {
image: ResponsiveImageType;
description: string;
preferHigherResolution?: boolean;
},
screenSize: ScreenSize,
imgSizeGetter: (images: ResponsiveImageType, screenSize: ScreenSize) => ImageResType = getImageSize,
) => {
const {image, description, preferHigherResolution} = imageData;
if (!image) {
return;
}
const imageByScreen = imgSizeGetter(image, screenSize);
return {
alt: description,
src:
imageByScreen &&
(preferHigherResolution ? imageByScreen.x3 || imageByScreen.x2 || imageByScreen.x1 : imageByScreen.x1),
srcSet: objectFlattener(imageByScreen)
.map((res, index) => `${res} ${index + 1}x`)
.join(", "),
};
};
type GetProductVideosArgs = Array<Pick<ProductVideo, "id" | "source">>;
export const getProductVideos = (videos: GetProductVideosArgs): ProductVideo[] => {
if (!Array.isArray(videos)) {
return [];
}
return videos
.filter((video) => video.id && video.source)
.map((video) => ({
id: video.id,
source: video.source,
thumbnail: `https://i1.ytimg.com/vi/${video.id}/default.jpg`,
}));
};
|
7bab5a87aa5dcd5d089b2b9ad3c8a9231a4b5480
|
TypeScript
|
jaredwolff/nativescript-sse-fail
|
/app/main-view-model.ts
| 2.609375
| 3
|
import { Observable } from "tns-core-modules/data/observable";
import { ObservableArray } from 'tns-core-modules/data/observable-array';
import { SSE } from 'nativescript-sse';
export class HelloWorldModel extends Observable {
private _list: ObservableArray<any>;
private _sse: any;
private _counter: number;
private _message: string;
constructor() {
super();
this._list = new ObservableArray();
this._sse = new SSE('https://api.particle.io/v1/events/blob', {'Authentication': 'Bearer '});
this._sse.events.on('onConnect', data => {
console.log(data.object.connected);
});
this._sse.events.on('onMessage', data => {
this._list.push(JSON.parse(data.object.message.data));
console.dir(JSON.parse(data.object.message.data));
});
this._sse.events.on('onError', data => {
console.log(data.object.error);
});
// Initialize default values.
this._counter = 42;
this.updateMessage();
}
get message(): string {
return this._message;
}
set message(value: string) {
if (this._message !== value) {
this._message = value;
this.notifyPropertyChange("message", value);
}
}
onTap() {
this._counter--;
this.updateMessage();
}
private updateMessage() {
if (this._counter <= 0) {
this.message = "Hoorraaay! You unlocked the NativeScript clicker achievement!";
} else {
this.message = `${this._counter} taps left`;
}
}
}
|
77b199f571460bfb5da00ec177ad31f37686490f
|
TypeScript
|
LuizValdiero/lf-web
|
/src/app/services/lexical-analyzer.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import { AF, compute, copyAf, determineAf, joinAf, renameAf, StateAF } from '../models/automato';
import { LA, TokenAF, TokenDefinition, validTokenDefinition } from '../models/er';
import { ConvertErToAfService } from './convert-er-to-af.service';
@Injectable({
providedIn: 'root'
})
export class LexicalAnalyzerService {
constructor(
private convertErToAFD: ConvertErToAfService
) { }
public create = (definitions: TokenDefinition[]): LA => {
const tokenAfList: TokenDefinition[] = []
let afJoin: AF | undefined = undefined;
definitions.forEach((tokenDefinition: TokenDefinition) => {
validTokenDefinition(tokenDefinition)
const afdFromEr: AF = this.convertErToAFD.convertToAFD(tokenDefinition.expression)
const prefixName = `${tokenAfList.length}q`
const afdRenamed = renameAf(afdFromEr, prefixName)
tokenAfList.push(tokenDefinition)
if (afJoin) {
afJoin = joinAf(copyAf(afJoin), copyAf(afdRenamed))
afJoin = determineAf(afJoin)
} else {
afJoin = afdRenamed
}
})
if (afJoin !== undefined) {
const afd: AF = determineAf(afJoin)
const laMap = this.mountLexicalAnalizerMap(afd.final)
return {
definitions: tokenAfList,
map: laMap,
af: afd
}
}
throw new Error('Error to join definitions')
}
private mountLexicalAnalizerMap = (finals: StateAF[]): Map<StateAF, number[]> => {
const la: Map<StateAF, number[]> = new Map()
finals.forEach((final: StateAF) => {
const tokens = final.split('_').filter((key: string) => key !== 'f').map((key: string) => +key.split('q')[0])
la.set(final, tokens)
})
return la
}
// retornar a TS e lista de tokens
analize = (la: LA, code: string): [Map<string, string[]>, string[]] => {
let output = ''
const ts: Map<string, string[]> = new Map()
const ls: string[] = []
const lexemes = this.getLexemesFromStr(code)
lexemes.forEach((lex: string) => {
if(!ts.has(lex)) {
const definitionsMatch = la.map.get(compute(la.af, lex))
if (definitionsMatch) {
ts.set(lex, definitionsMatch.map((index: number) => la.definitions[index].id))
} else {
throw new Error(`analise: ${lex}`)
}
}
// posso usar a propria lista de tokens
ls.push(lex)
output = output.concat(`${lex}: ${ts.get(lex)}\n`)
})
console.log('ts', ts)
console.log('ls', ls)
return [ts, ls]
}
private getLexemesFromStr = (input: string): string[] => input.replace(/\s\s*/g, ' ').trim().split(' ')
}
|
6441362611827b2f88eaab2c5268e076266ebf65
|
TypeScript
|
mongodb-js/mongosh
|
/packages/async-rewriter2/src/error-codes.ts
| 2.78125
| 3
|
// Note: Codes are shared with the old async rewriter for now, hence starting at 10012
/**
* @mongoshErrors
*/
enum AsyncRewriterErrors {
/**
* Signals the use of a Mongosh API call in a place where it is not supported.
* This occurs inside of constructors and (non-async) generator functions.
*
* Examples causing error:
* ```javascript
* class SomeClass {
* constructor() {
* this.list = db.coll.find().toArray();
* }
* }
*
* function*() {
* yield* db.coll.find().toArray();
* }
* ```
*
* **Solution: Do not use calls directly in such functions. If necessary, place these calls in an inner 'async' function.**
*/
SyntheticPromiseInAlwaysSyncContext = 'ASYNC-10012',
}
export { AsyncRewriterErrors };
|
fb48dec24abe60a9790183126880dbaa4583b7e4
|
TypeScript
|
Oyelowo/coding_practice
|
/sol/anchor/tic-tac-toe/tests/tic-tac-toe.ts
| 2.5625
| 3
|
import * as anchor from "@project-serum/anchor";
import { Program } from "@project-serum/anchor";
import { TicTacToe } from "../target/types/tic_tac_toe";
import { expect } from "chai";
describe("tic-tac-toe", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.TicTacToe as Program<TicTacToe>;
it("setup game!", async () => {
const gameKeypair = anchor.web3.Keypair.generate();
const playerOne = program.provider.wallet;
const playerTwo = anchor.web3.Keypair.generate();
await program.rpc.setupGame(playerTwo.publicKey, {
accounts: {
game: gameKeypair.publicKey,
playerOne: playerOne.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [gameKeypair],
});
let gameState = await program.account.game.fetch(gameKeypair.publicKey);
expect(gameState.turn).to.equal(1);
expect(gameState.players).to.eql([
playerOne.publicKey,
playerTwo.publicKey,
]);
expect(gameState.state).to.eql({ active: {} });
expect(gameState.board).to.eql([
[null, null, null],
[null, null, null],
[null, null, null],
]);
});
it("player one wins", async () => {
const gameKeypair = anchor.web3.Keypair.generate();
const playerOne = program.provider.wallet;
const playerTwo = anchor.web3.Keypair.generate();
debugger;
await program.rpc.setupGame(playerTwo.publicKey, {
accounts: {
game: gameKeypair.publicKey,
playerOne: playerOne.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [gameKeypair],
});
let gameState = await program.account.game.fetch(gameKeypair.publicKey);
expect(gameState.turn).to.equal(1);
expect(gameState.players).to.eql([
playerOne.publicKey,
playerTwo.publicKey,
]);
expect(gameState.state).to.eql({ active: {} });
expect(gameState.board).to.eql([
[null, null, null],
[null, null, null],
[null, null, null],
]);
await play(
program,
gameKeypair.publicKey,
playerOne,
{ row: 0, column: 0 },
2,
{ active: {} },
[
[{ x: {} }, null, null],
[null, null, null],
[null, null, null],
]
);
});
it("Test exploits", async () => {
const gameKeypair = anchor.web3.Keypair.generate();
const playerOne = program.provider.wallet;
const playerTwo = anchor.web3.Keypair.generate();
debugger;
await program.rpc.setupGame(playerTwo.publicKey, {
accounts: {
game: gameKeypair.publicKey,
playerOne: playerOne.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [gameKeypair],
});
// Player two should not play first. Player one, the creator, should play first
// Hence, throwing an error
try {
await play(
program,
gameKeypair.publicKey,
playerTwo, // should be player 1 first
{ row: 3, column: 1 }, // out of bounds row
4,
{ active: {} },
[
[{ x: {} }, { x: {} }, null],
[{ o: {} }, null, null],
[null, null, null],
]
);
// we use this to make sure we definitely throw an error
chai.assert(false, "should've failed but didn't ");
} catch (error) {
// These errors are indexed from custom enum error from my rust backend starting from
// 6000, 6001, 6002 ...6xxx
expect(error.code).to.equal(6003); // 6003 stands for NotYetPlayersTurn created as custom error in my program in rust
}
// Player one now playing first
await play(
program,
gameKeypair.publicKey,
playerOne,
{ row: 0, column: 1 },
2,
{ active: {} },
[
[null, { x: {} }, null],
[null, null, null],
[null, null, null],
]
);
// Out of bound error will be thrown. Row ends at 3
try {
await play(
program,
gameKeypair.publicKey,
playerTwo,
{ row: 5, column: 1 }, // out of bounds row
4,
{ active: {} },
[
[{ x: {} }, { x: {} }, null],
[{ o: {} }, null, null],
[null, null, null],
]
);
// we use this to make sure we definitely throw an error
chai.assert(false, "should've failed but didn't");
} catch (error) {
expect(error.code).to.equal(6002); // 6002 stands for OutOfBoundError
}
// Cant play on already existing tiles
try {
await play(
program,
gameKeypair.publicKey,
playerTwo,
{ row: 0, column: 1 }, // out of bounds row
4,
{ active: {} },
[
[null, { x: {} }, null],
[{ o: {} }, null, null],
[null, null, null],
]
);
// we use this to make sure we definitely throw an error
chai.assert(false, "should've failed but didn't");
} catch (error) {
expect(error.code).to.equal(6001); // 6002 stands for OutOfBoundError
}
});
});
async function play(
program: anchor.Program<TicTacToe>,
game,
player,
tile,
expectedTurn,
expectedGameState,
expectedBoard
) {
await program.rpc.play(tile, {
accounts: {
player: player.publicKey,
game,
},
signers: player instanceof (anchor.Wallet as any) ? [] : [player],
});
const gameState = await program.account.game.fetch(game);
expect(gameState.turn).to.equal(expectedTurn);
expect(gameState.state).to.eql(expectedGameState);
expect(gameState.board).to.eql(expectedBoard);
}
|
f6b2176d1fde427d5428f4b0dcf1f6e18f62db3f
|
TypeScript
|
VirtoCommerce/vc-cms-page-designer
|
/cms-designer/src/app/modules/theme/state/theme.reducer.spec.ts
| 2.5625
| 3
|
import { BlockSchema, ColorControlDescriptor } from 'src/app/modules/shared/models';
import * as fromTheme from './theme.reducer';
import * as themeActions from './theme.actions';
describe('Theme reducer', () => {
describe('undefined action', () => {
it('should return the default state', () => {
const { initialState } = fromTheme;
const action = {} as any;
const state = fromTheme.reducer(undefined, action);
expect(state).toBe(initialState);
});
});
describe('LoadSchema action', () => {
it('should set schemaLoading to true', () => {
// arrange
const { initialState } = fromTheme;
const action = new themeActions.LoadSchema();
// act
const state = fromTheme.reducer(initialState, action);
// assert
expect(state.schemaLoading).toEqual(true);
expect(state.schema).toEqual([]);
});
});
describe('LoadSchemaSuccess action', () => {
// arrange
const schema = <BlockSchema[]>[
{
name: 'Colors',
icon: 'colors',
settings: [
<ColorControlDescriptor>{
type: 'color',
id: 'text-color',
value: 'black'
}
]
},
{
name: 'Values',
icon: 'values',
settings: [
{
type: 'value',
id: 'text-value',
value: 'OK'
}
]
}
];
const { initialState } = fromTheme;
const loadingState = { ...initialState, schemaLoading: true };
const action = new themeActions.LoadSchemaSuccess(schema);
// act
const state = fromTheme.reducer(loadingState, action);
// assert
it('should populate array', () => {
expect(state.schema).toBe(schema);
});
it('should loading flag to false', () => {
expect(state.schemaLoading).toEqual(false);
});
});
describe('LoadSchemaFail action', () => {
const { initialState } = fromTheme;
const loadingState = { ...initialState, schemaLoading: true };
const message = 'Something went wrong';
const action = new themeActions.LoadSchemaFail(message);
const state = fromTheme.reducer(loadingState, action);
it('should set the given error message', () => {
expect(state.schema).toEqual([]);
});
it('should reset loading flag to false', () => {
expect(state.schemaLoading).toEqual(false);
});
});
describe('SaveTheme action', () => {
const editableTheme = {
property1: 'value 1',
property2: 'value 2',
property3: 'value 3'
};
const presets = {
current: 'top',
presets: {
top: {
property1: 'top value 1',
property2: 'top value 2',
property3: 'top value 3'
},
other: {
property1: 'other value 1',
property2: 'other value 2',
property3: 'other value 3'
}
}
};
const themeToSave = {
current: editableTheme,
presets: presets.presets
};
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets };
const action = new themeActions.SaveTheme();
const state = fromTheme.reducer(currentState, action);
it('should set current theme from editableTheme', () => {
expect(state.presets).toEqual(themeToSave);
});
it('should create new theme object', () => {
expect(state.presets.current).not.toBe(editableTheme);
expect(state.presets).not.toBe(presets);
});
});
describe('SaveThemesSuccess action', () => {
const presets = {
current: 'top',
presets: {
top: {
property1: 'top value 1',
property2: 'top value 2',
property3: 'top value 3'
},
other: {
property1: 'other value 1',
property2: 'other value 2',
property3: 'other value 3'
}
}
};
const { initialState } = fromTheme;
const currentState = { ...initialState, presets, dirty: true };
const action = new themeActions.SaveThemeSuccess();
const state = fromTheme.reducer(currentState, action);
it('should serialize current themes to initialPresets', () => {
const serializedPresets = JSON.stringify(presets);
expect(state.initialPresets).toEqual(serializedPresets);
});
it('should reset dirty flag', () => {
expect(state.dirty).toEqual(false);
});
});
describe('LoadThemes action', () => {
const { initialState } = fromTheme;
const action = new themeActions.LoadThemes();
const state = fromTheme.reducer(initialState, action);
it('should set theme loading to true', () => {
expect(state.presetsLoading).toEqual(true);
});
});
describe('LoadThemesSuccess action', () => {
describe('when current theme is a preset property', () => {
const presets = {
current: 'top',
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const { initialState } = fromTheme;
const currentState = { ...initialState, presetsLoading: true };
const action = new themeActions.LoadThemesSuccess(presets);
const state = fromTheme.reducer(currentState, action);
it('should set editableTheme to correct presets in other object', () => {
expect(state.editableTheme).toEqual(presets.presets.top);
expect(state.editableTheme).not.toBe(presets.presets.top);
});
it('should set presets current property to current preset', () => {
const workingPresets = { ...presets, current: presets.presets.top };
expect(state.presets).toEqual(workingPresets);
expect(state.presets.current).toEqual(presets.presets.top);
expect(state.presets.current).not.toBe(presets.presets.top);
expect(state.presets.current).not.toBe(state.editableTheme);
});
it('should store presets for restoring', () => {
const serialized = JSON.stringify(presets);
expect(state.initialPresets).toEqual(serialized);
});
it('should reset loading flag', () => {
expect(state.presetsLoading).toEqual(false);
});
});
describe('when current theme is an object', () => {
const presets = {
current: {
property1: 'current value 1',
property2: 'current value 2'
},
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const { initialState } = fromTheme;
const currentState = { ...initialState, presetsLoading: true };
const action = new themeActions.LoadThemesSuccess(presets);
const state = fromTheme.reducer(currentState, action);
it('should set editable object from given current theme', () => {
expect(state.editableTheme).toEqual(presets.current);
expect(state.editableTheme).not.toBe(presets.current);
});
it('should not change a given presets', () => {
expect(state.presets).toEqual(presets);
});
it('should store presets for restoring', () => {
const serialized = JSON.stringify(presets);
expect(state.initialPresets).toEqual(serialized);
});
it('should reset loading flag', () => {
expect(state.presetsLoading).toEqual(false);
});
});
});
describe('LoadThemesFail action', () => {
const { initialState } = fromTheme;
const currentState = { ...initialState, presetsLoading: true };
const message = 'something went wrong';
const action = new themeActions.LoadThemesFail(message);
const state = fromTheme.reducer(currentState, action);
it('should reset loading flag and set correct error value', () => {
expect(state.presetsLoading).toEqual(false);
});
});
describe('SelectSchemaItem action', () => {
const { initialState } = fromTheme;
const item = { name: 'item', icon: 'item', settings: [] };
const action = new themeActions.SelectSchemaItem(item);
const state = fromTheme.reducer(initialState, action);
it('should set current schema item to a given', () => {
expect(state.selectedSchemaItem).toBe(item);
});
});
describe('ShowPresetsPane action', () => {
const { initialState } = fromTheme;
const action = new themeActions.ShowPresetsPane();
const state = fromTheme.reducer(initialState, action);
it('should set showPresetsEditor to true', () => {
expect(state.showPresetsEditor).toEqual(true);
});
});
describe('CancelPreset action', () => {
const presets = {
current: null,
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const editableTheme = {
property1: 'current value 1',
property2: 'current value 2'
};
presets.current = presets.presets.top;
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets, showPresetsEditor: true };
const action = new themeActions.CancelPreset();
const state = fromTheme.reducer(currentState, action);
it('should revert presets.current', () => {
expect(state.presets.current).toEqual(editableTheme);
expect(state.presets).not.toBe(presets);
});
it('should hide presets editor', () => {
expect(state.showPresetsEditor).toEqual(false);
});
});
describe('ApplyPreset action', () => {
const presets = {
current: null,
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const editableTheme = {
property1: 'current value 1',
property2: 'current value 2'
};
presets.current = { ...editableTheme };
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets, showPresetsEditor: true, dirty: false };
const action = new themeActions.ApplyPreset('top');
const state = fromTheme.reducer(currentState, action);
it('should apply previewed preset to editableTheme', () => {
expect(state.editableTheme).toEqual(presets.presets.top);
expect(state.editableTheme).not.toBe(presets.presets.top);
expect(state.editableTheme).not.toBe(presets.current);
});
it('should set presets.current to given preset', () => {
expect(state.presets.current).toEqual(presets.presets.top);
expect(state.presets.current).not.toBe(presets.presets.top);
});
it('should hide presets editor', () => {
expect(state.showPresetsEditor).toEqual(false);
});
it('should set dirty flag to true', () => {
expect(state.dirty).toEqual(true);
});
});
describe('UpdateTheme action', () => {
const presets = {
current: null,
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const editableTheme = {
property1: 'current value 1',
property2: 'current value 2'
};
presets.current = { ...editableTheme };
const updatePart = {
newProperty1: 'new property 1',
newProperty2: 'new property 2'
};
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets, dirty: false };
const action = new themeActions.UpdateTheme(updatePart);
const state = fromTheme.reducer(currentState, action);
it('should update the editable theme', () => {
const newValue = { ...editableTheme, ...updatePart };
expect(state.editableTheme).toEqual(newValue);
expect(state.editableTheme).not.toBe(editableTheme);
});
it('should update the preset\'s current property', () => {
const newValue = { ...editableTheme, ...updatePart };
expect(state.presets.current).toEqual(newValue);
expect(state.presets).not.toBe(presets);
expect(state.presets.current).not.toBe(state.editableTheme);
});
it('should set dirty property to true', () => {
expect(state.dirty).toEqual(true);
});
});
describe('ClearThemeChanges action', () => {
describe('when current is an object', () => {
const presets = {
current: {
property1: 'current value 1',
property2: 'current value 2'
},
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const { initialState } = fromTheme;
const currentState = {
...initialState,
initialPresets: JSON.stringify(presets),
dirty: true
};
const action = new themeActions.ClearThemeChanges();
const state = fromTheme.reducer(currentState, action);
it('should set presets as initial', () => {
expect(state.presets).toEqual(presets);
});
it('should set editableTheme as presets.current', () => {
expect(state.editableTheme).toEqual(<any>state.presets.current);
expect(state.editableTheme).not.toBe(<any>state.presets.current);
});
it('should reset dirty flag', () => {
expect(state.dirty).toEqual(false);
});
});
describe('when current is a preset property name', () => {
const presets = {
current: 'top',
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const { initialState } = fromTheme;
const currentState = {
...initialState,
initialPresets: JSON.stringify(presets),
dirty: true
};
const action = new themeActions.ClearThemeChanges();
const state = fromTheme.reducer(currentState, action);
it('should set presets as prepared initial', () => {
const preparedPresets = { ...presets, current: presets.presets[presets.current] };
expect(state.presets).toEqual(preparedPresets);
});
it('should set editableTheme as presets.current', () => {
expect(state.editableTheme).toEqual(<any>state.presets.current);
expect(state.editableTheme).not.toBe(<any>state.presets.current);
});
it('should reset dirty flag', () => {
expect(state.dirty).toEqual(false);
});
});
});
describe('RemovePreset action', () => {
const presets = {
current: {
property1: 'current value 1',
property2: 'current value 2'
},
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
},
other: {
property1: 'other value 1',
property2: 'other value 2'
}
}
};
const { initialState } = fromTheme;
const currentState = { ...initialState, presets, dirty: false };
const action = new themeActions.RemovePreset('other');
const state = fromTheme.reducer(currentState, action);
it('should remove the \'other\' preset', () => {
expect(state.presets.presets.other).toBeUndefined();
expect(state.presets).not.toBe(presets);
});
it('should set dirty to true', () => {
expect(state.dirty).toEqual(true);
});
});
describe('CreatePreset action', () => {
const presets = {
current: {
property1: 'current value 1',
property2: 'current value 2'
},
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const editableTheme = {
property1: 'new value 1',
property2: 'new value 2'
};
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets, dirty: false };
const action = new themeActions.CreatePreset('other');
const state = fromTheme.reducer(currentState, action);
it('should create the \'other\' preset', () => {
expect(state.presets.presets.other).toEqual(editableTheme);
expect(state.editableTheme).not.toBe(state.presets.presets.other);
expect(state.presets).not.toBe(presets);
});
it('should set dirty to true', () => {
expect(state.dirty).toEqual(true);
});
});
describe('SelectPreset action', () => {
const presets = {
current: {
property1: 'current value 1',
property2: 'current value 2'
},
presets: {
top: {
property1: 'value 1',
property2: 'value 2'
}
}
};
const editableTheme = {
property1: 'new value 1',
property2: 'new value 2'
};
const { initialState } = fromTheme;
const currentState = { ...initialState, editableTheme, presets, dirty: false };
const action = new themeActions.SelectPreset('top');
const state = fromTheme.reducer(currentState, action);
it('should set the current theme to given preset', () => {
expect(state.presets.current).toEqual(presets.presets.top);
expect(state.presets).not.toBe(presets);
});
it('should not change theme under edit', () => {
expect(state.editableTheme).toEqual(editableTheme);
});
it('should not touch the dirty flag', () => {
expect(state.dirty).toEqual(false);
});
});
});
|
542bd8303d2f71ba6db04fd683e1ee4072a74b83
|
TypeScript
|
panthe/saga-login-firebase-rest
|
/src/utils/fetch/types.ts
| 2.71875
| 3
|
export enum EHTTPMethodsTypes {
GET= 'GET',
POST= 'POST',
PUT= 'PUT',
PATCH= 'PATCH',
DELETE= 'DELETE'
}
export interface FetchParams {
url: string;
params?: string;
}
//TODO: Substitute the generics Types in the fetch Functions
export interface IHttpResponse<T> extends Response {
parsedBody?: T;
}
|
93f533e5394cfcd49b3b11944f00c69457854f30
|
TypeScript
|
kennysama/reactAtomic
|
/src/helpers/order-items.ts
| 2.6875
| 3
|
import { TOrderItemCode, TPartsNumber, ISubCategory } from '../types/order-items';
import { getSubCategories } from '../lookups/sub-categories';
import { getOrderCatalog } from '../lookups/order-items';
export function getOrderItem(
category: string,
pieces: string[],
isDouble = false,
brand: string = '',
): TOrderItemCode | undefined {
const orderItem = getOrderCatalog().filter(
row =>
row.category === category &&
row.pieces.sort().join() === pieces.sort().join() &&
row.isDouble === isDouble &&
row.availableBrand(brand) === true,
)[0];
return orderItem ? orderItem.itemCode : undefined;
}
export function getSubCategoryPieces(subCategory: string): TPartsNumber[] {
return getSubCategories().filter((item: ISubCategory) => item.code === subCategory)[0].initialParts;
}
|
585a72f5328f14c7c99a111ddb6489295c1e4c1d
|
TypeScript
|
bekeeeee/clean-code-architecture-TS
|
/src/web/lib/abstract-application.ts
| 2.609375
| 3
|
import { Container, interfaces } from 'inversify'
export enum MorganMode {
DEV = 'dev',
COMMON = 'common',
TINY = 'tiny',
SHORT = 'short',
COMBINED = 'combined',
}
export interface IAbstractApplicationOptions {
containerOpts: interfaces.ContainerOptions
morgan: {
mode: MorganMode
}
}
export abstract class Application {
protected readonly container: Container
constructor(options: IAbstractApplicationOptions) {
this.container = new Container(options.containerOpts)
console.clear()
this.configureServices(this.container)
this.setup(options)
}
abstract configureServices(container: Container): void
abstract setup(options: IAbstractApplicationOptions): Promise<void> | void
}
|
8985d5289505cafc63a5ccdd15f9134e22de07f8
|
TypeScript
|
emil14/reaflow
|
/src/helpers/crudHelpers.ts
| 2.9375
| 3
|
import { EdgeData, NodeData, PortData } from '../types';
/**
* Helper function for upserting a node in a edge.
*/
export function upsertNode(
nodes: NodeData[],
edges: EdgeData[],
edge: EdgeData,
newNode: NodeData
) {
const oldEdgeIndex = edges.findIndex(e => e.id === edge.id);
const edgeBeforeNewNode = {
...edge,
id: `${edge.from}-${newNode.id}`,
to: newNode.id
};
const edgeAfterNewNode = {
...edge,
id: `${newNode.id}-${edge.to}`,
from: newNode.id
};
if (edge.fromPort && edge.toPort) {
edgeBeforeNewNode.fromPort = edge.fromPort;
edgeBeforeNewNode.toPort = `${newNode.id}-to`;
edgeAfterNewNode.fromPort = `${newNode.id}-from`;
edgeAfterNewNode.toPort = edge.toPort;
}
edges.splice(oldEdgeIndex, 1, edgeBeforeNewNode, edgeAfterNewNode);
return {
nodes: [...nodes, newNode],
edges: [...edges]
};
}
/**
* Helper function for removing a node between edges and
* linking the children.
*/
export function removeAndUpsertNodes(
nodes: NodeData[],
edges: EdgeData[],
removeNodes: NodeData | NodeData[],
onNodeLinkCheck?: (
newNodes: NodeData[],
newEdges: EdgeData[],
from: NodeData,
to: NodeData,
port?: PortData
) => undefined | boolean
) {
if (!Array.isArray(removeNodes)) {
removeNodes = [removeNodes];
}
const nodeIds = removeNodes.map((n) => n.id);
const newNodes = nodes.filter((n) => !nodeIds.includes(n.id));
const newEdges = edges.filter(
(e) => !nodeIds.includes(e.from) && !nodeIds.includes(e.to)
);
for (const nodeId of nodeIds) {
const sourceEdges = edges.filter((e) => e.to === nodeId);
const targetEdges = edges.filter((e) => e.from === nodeId);
for (const sourceEdge of sourceEdges) {
for (const targetEdge of targetEdges) {
const sourceNode = nodes.find((n) => n.id === sourceEdge.from);
const targetNode = nodes.find((n) => n.id === targetEdge.to);
if (sourceNode && targetNode) {
const canLink = onNodeLinkCheck?.(
newNodes,
newEdges,
sourceNode,
targetNode
);
if (canLink === undefined || canLink) {
newEdges.push({
id: `${sourceNode.id}-${targetNode.id}`,
from: sourceNode.id,
to: targetNode.id,
parent: sourceNode?.parent
});
}
}
}
}
}
return {
edges: newEdges,
nodes: newNodes
};
}
/**
* Helper function to remove a node and its related edges.
*/
export function removeNode(
nodes: NodeData[],
edges: EdgeData[],
removeNodes: string | string[]
) {
if (!Array.isArray(removeNodes)) {
removeNodes = [removeNodes];
}
const newNodes = [];
const newEdges = [];
for (const node of nodes) {
const has = removeNodes.some((n) => n === node.id);
if (!has) {
newNodes.push(node);
}
}
for (const edge of edges) {
const has = removeNodes.some((n) => n === edge.from || n === edge.to);
if (!has) {
newEdges.push(edge);
}
}
return {
nodes: newNodes,
edges: newEdges
};
}
/**
* Helper function to remove a node's related edges.
*/
export function removeEdgesFromNode(nodeId: string, edges: EdgeData[]) {
return edges.filter(edge => !(edge.to === nodeId || edge.from === nodeId));
}
/**
* Remove edge(s)
*/
export function removeEdge(edges: EdgeData[], edge: EdgeData | EdgeData[]) {
const deletions: EdgeData[] = !Array.isArray(edge) ? [edge] : edge;
const edgeIds = deletions.map((e) => e.id);
return edges.filter((e) => !edgeIds.includes(e.id));
}
/**
* Create an edge given 2 nodes.
*/
export function createEdgeFromNodes(fromNode: NodeData, toNode: NodeData) {
return {
id: `${fromNode.id}-${toNode.id}`,
from: fromNode.id,
to: toNode.id,
parent: toNode.parent
};
}
/**
* Add a node and optional edge.
*/
export function addNodeAndEdge(
nodes: NodeData[],
edges: EdgeData[],
node: NodeData,
toNode?: NodeData
) {
return {
nodes: [...nodes, node],
edges: [
...edges,
...(toNode
? [createEdgeFromNodes(toNode, node)]
: [])
]
};
}
|
7b5a225c46c4caf1fb9a312be6516c31b3837334
|
TypeScript
|
umairmustafa753/restaurant-managment-system
|
/client/store/Reducers/menu.ts
| 2.6875
| 3
|
import ActionTypes from "../Actions/ActionTypes";
const INITIAL_STATE = {
menu: []
};
const menuList = (state = INITIAL_STATE, action) => {
switch (action.type) {
case ActionTypes.GET_MENU: {
return {
...state,
menu: action.payload
};
}
default:
return state;
}
};
export default menuList;
|
ce4a070ce51784e707b8e45710296e7941da5391
|
TypeScript
|
donaldducky/advent-of-code
|
/2020/src/day1/day1.ts
| 3.375
| 3
|
import * as fs from 'fs';
import * as path from 'path';
const nums = fs
.readFileSync(path.join(__dirname, 'input.txt'), 'utf8')
.toString()
.trim()
.split('\n')
.map(i => parseInt(i, 10));
console.log('Part 1:', part1(nums));
console.log('Part 2:', part2(nums));
function part1(nums) {
const numMap = nums.reduce((acc, n) => acc.add(n), new Set());
const entry = nums.find(n => {
return numMap.has(2020 - n);
});
return entry * (2020 - entry);
}
function part2(nums) {
let list = [];
nums.sort((n1, n2) => n1 - n2);
for (let i = 0; i < nums.length && list.length === 0; i++) {
for (let j = 0; j < nums.length && list.length === 0; j++) {
if (nums[i] + nums[j] < 2020) {
for (let k = 0; k < nums.length && list.length === 0; k++) {
if (nums[i] + nums[j] + nums[k] === 2020) {
list = [nums[i], nums[j], nums[k]];
}
}
}
}
}
return list.reduce((n, m) => n * m);
}
|
799cdcab4f0fb8515adfb5f27cf027c1acf1d557
|
TypeScript
|
itsrainingmani/yass
|
/src/string.extensions.ts
| 3.796875
| 4
|
interface String {
center(maxLength: number, fillString?: string): string;
}
String.prototype.center = function (maxLength: number, fillString?: string): string {
fillString = fillString || " "; // If fillString is undefined, use space as default
return this.length >= maxLength ? this.toString() : this.padStart((this.length + maxLength) / 2,
fillString).padEnd(maxLength, fillString);
}
|
807731697383dbbd193f5fcfc6e1eee8ca665ff5
|
TypeScript
|
JKCamus/Q-S
|
/算法/review/796.旋转字符串.ts
| 3.171875
| 3
|
/*
* @lc app=leetcode.cn id=796 lang=typescript
*
* [796] 旋转字符串
*/
// @lc code=start
function rotateString(s: string, goal: string): boolean {
if (s.length !== goal.length) return false
let SGoal = s + s
if (SGoal.includes(goal)) {
return true
} else {
return false
}
};
// @lc code=end
|
02942fb3b159cbd7c9a5d280d53a45d3e4d07629
|
TypeScript
|
esentri/js-transformer-functions
|
/test/StringTo.test.ts
| 2.96875
| 3
|
import {ArrayBufferEqual} from './helper/ArrayBufferFunctions'
import {StringToArrayBuffer, StringToBase64, StringToHexString, StringWithBinaryDataToBase64} from '../src/transformer-functions'
import {ArrayBufferHelloWorld, Uint8ArrayHelloWorld} from './testData/ArrayBuffers'
import {BinaryString, HelloWorldString} from './testData/Strings'
import {BinaryStringBase64, HelloWorldBase64} from './testData/Base64Strings'
import {HelloWorldHex} from './testData/HexStrings'
import {StringToUint8Array} from '../src/StringTo'
describe('string to', () => {
it('ArrayBuffer', () => {
const str = 'hello world'
const arrayBuffer = StringToArrayBuffer(str)
expect(ArrayBufferEqual(ArrayBufferHelloWorld, arrayBuffer)).toBeTruthy()
})
it('Uint8Array', () => {
const str = 'hello world'
const array = StringToUint8Array(str)
expect(array).toEqual(Uint8ArrayHelloWorld)
})
it('base64', () => {
const base64 = StringToBase64(HelloWorldString)
expect(base64).toEqual(HelloWorldBase64)
})
it('base64 (binary)', () => {
const base64 = StringWithBinaryDataToBase64(BinaryString)
expect(base64).toEqual(BinaryStringBase64)
})
it('base64 (without btoa)', () => {
const bufferedBtoA = btoa
delete window.btoa
const base64 = StringToBase64(HelloWorldString)
expect(base64).toEqual(HelloWorldBase64)
window.btoa = bufferedBtoA
})
it('hex string', () => {
const hexString = StringToHexString(HelloWorldString)
expect(hexString).toEqual(HelloWorldHex)
})
})
|
92e61cc2821f7f44f385bf0aac0db5d560614782
|
TypeScript
|
redmagebr/redpgBeta
|
/app/Kinds/Classes/SheetInstance.ts
| 2.71875
| 3
|
class SheetInstance {
public id : number = 0;
public gameid : number = 0;
public folder : string = "";
public name : string = "";
public values : Object = {};
public lastValues : string = "{}";
public creator : number = null;
public creatorNickname : string = "???#???";
public styleId : number = 0;
public styleName : string = "?";
public styleCreator : number = 0;
public styleCreatorNickname : string = "???#???";
public styleSafe : boolean = false;
public view : boolean = true;
public edit : boolean = false;
public delete : boolean = false;
public promote : boolean = false;
public isPublic : boolean = false;
public changed : boolean = false;
private changeTrigger = new Trigger();
public addChangeListener (list : Listener | Function) {
this.changeTrigger.addListener(list);
}
public triggerChanged () {
this.changeTrigger.trigger(this);
DB.SheetDB.triggerChanged(this);
}
public getMemoryId() {
return "sheetBackup_" + this.id;
}
public setSaved () {
this.changed = false;
Application.LocalMemory.unsetMemory(this.getMemoryId());
}
public setName (name : string) {
if (name !== this.name) {
this.changed = true;
this.name = name;
this.triggerChanged();
}
}
public setValues (values : Object, local : boolean) {
// Local values = user changed them NOW.
// Not local = saved on server.
var newJson = JSON.stringify(values);
if (newJson !== this.lastValues) {
this.values = values;
this.lastValues = newJson;
this.changed = true;
}
if (this.changed) {
if (local) {
// Store in localStorage
Application.LocalMemory.setMemory(this.getMemoryId(), newJson);
} else {
// Since these are the server values, even though the current instance changed, it's not changed in the way users see it.
this.changed = false;
}
this.triggerChanged();
}
}
public updateFromObject (obj : Object) {
if (typeof obj['id'] !== 'undefined') this.id = obj['id'];
if (typeof obj['gameid'] !== 'undefined') this.gameid = obj['gameid'];
if (typeof obj['nome'] !== 'undefined') this.name = obj['nome'];
if (typeof obj['criadorNick'] !== 'undefined' && typeof obj['criadorNickSufix'] !== 'undefined') this.creatorNickname = obj['criadorNick'] + "#" + obj['criadorNickSufix'];
if (typeof obj['criador'] !== 'undefined') this.creator = obj['criador'];
if (typeof obj['folder'] !== 'undefined') this.folder = obj['folder'];
if (typeof obj['publica'] !== 'undefined') this.isPublic = obj['publica'];
if (typeof obj['visualizar'] !== 'undefined') this.view = obj['visualizar'];
if (typeof obj['deletar'] !== 'undefined') this.delete = obj['deletar'];
if (typeof obj['editar'] !== 'undefined') this.edit = obj['editar'];
if (typeof obj['promote'] !== 'undefined') this.promote = obj['promote'];
if (typeof obj['nickStyleCreator'] !== 'undefined' && typeof obj['nicksufixStyleCreator'] !== 'undefined') this.styleCreatorNickname = obj['nickStyleCreator'] + "#" + obj['nicksufixStyleCreator'];
if (typeof obj['idStyleCreator'] !== 'undefined') this.styleCreator = obj['idStyleCreator'];
if (typeof obj['idstyle'] !== 'undefined') this.styleId = obj['idstyle'];
if (typeof obj['styleName'] !== 'undefined') this.styleName = obj['styleName'];
if (typeof obj['segura'] !== 'undefined') this.styleSafe = obj['segura'];
if (typeof obj['values'] !== 'undefined') this.setValues(obj['values'], false);
}
}
|
d1e70badbffd7b25de5fda868d7de8d38a09a190
|
TypeScript
|
MateuszMaslanka1/Organizations
|
/src/app/core/organizations-dialog/check-elements.service.ts
| 2.828125
| 3
|
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CheckElementsService {
constructor() { }
alphabeticallyGoupedNames = {};
lenghtOfColumn(alphabet) {
return Math.ceil(alphabet.length / 4);
}
sortElement(nameList: string[]) {
nameList.sort();
return nameList;
}
groupAlphabetically(alphabet: string[] , nameList: string[]) {
this.alphabeticallyGoupedNames = {};
alphabet.forEach(letter => {
const alphabeticGroup = [];
nameList.forEach(el2 => {
if (letter.toLocaleLowerCase() === el2.charAt(0)) {
alphabeticGroup.push(el2);
this.alphabeticallyGoupedNames[letter] = {listWithName: alphabeticGroup};
}
});
});
return this.alphabeticallyGoupedNames;
}
findWords(wordsToFind: string, nameList: string[]) {
const listForFindName: string[] = [];
nameList.forEach(word => {
if (word.includes(wordsToFind)) {
listForFindName.push(word);
}
});
return listForFindName;
}
}
|
1e58409254d2869eefefeb3e964ce3ba942a346f
|
TypeScript
|
toucheqt/Remote-API-Web-Reference-for-Java-Enterprise-Applications
|
/restty-app/frontend/src/main/frontend/src/app/model/endpoint.ts
| 2.609375
| 3
|
import { Log } from './log';
import { Parameter } from './parameter';
import { Response } from './response';
/**
* Entity that contains information about endpoints.
* @author Ondrej Krpec
*/
export class Endpoint {
id: number;
path: string;
method: string;
description: string;
lastRun: string;
lastRunSuccess: boolean;
lastRunMessage: string;
parameters: Parameter[];
responses: Response[];
log: Log[];
}
|
424c987e8b58a2bb8e15875dcf5112acfb8a3aab
|
TypeScript
|
Rohan-Deshamudre/Smart-traffic-management-system
|
/frontend-web/src/helper/auth.ts
| 2.859375
| 3
|
const jwt = require('jwt-decode');
export module Auth {
export var role: string = '';
export function saveToken(token) {
sessionStorage.setItem('token', token)
}
export function getToken(): string {
return sessionStorage.getItem('token')
}
export function eraseToken(): void {
sessionStorage.removeItem('token')
}
export function isEngineer(): boolean {
if (getToken() && getToken().length > 0) {
const decoded = jwt(getToken());
return decoded.groups.map((x) => +x.id).includes(1);
} else {
return false;
}
}
export function isOperator(): boolean {
if (getToken() && getToken().length > 0) {
const decoded = jwt(getToken());
return decoded.groups.map((x) => +x.id).includes(2);
} else {
return false;
}
}
export function getName(): string {
if (getToken() && getToken().length > 0) {
const decoded = jwt(getToken());
return decoded.username;
}
}
/**
* Check if user is authenticated.
*/
export function hasValidToken(): boolean {
if (getToken() && getToken().length > 0) {
const decoded = jwt(getToken());
const expiryDate = toDateTime(decoded.exp);
return expiryDate > new Date();
} else {
return false;
}
}
/**
* Convert seconds to UTC date time.
* @param secs
*/
export function toDateTime(secs) {
// Be careful.
const t = new Date(Date.UTC(1970, 0, 1, 0, 50)); // Epoch
t.setSeconds(secs);
return t;
}
}
|
708006ebc0ce7b44abef7e8e452de23157a3f16a
|
TypeScript
|
solidity-by-example/solidity-by-example.github.io
|
/src/pages/function-selector/index.html.ts
| 2.8125
| 3
|
// metadata
export const version = "0.8.20"
export const title = "Function Selector"
export const description = "Example of how function selectors are computed"
export const keywords = ["function", "functions", "selector", "selectors"]
export const codes = [
{
fileName: "FunctionSelector.sol",
code: "Ly8gU1BEWC1MaWNlbnNlLUlkZW50aWZpZXI6IE1JVApwcmFnbWEgc29saWRpdHkgXjAuOC4yMDsKCmNvbnRyYWN0IEZ1bmN0aW9uU2VsZWN0b3IgewogICAgLyoKICAgICJ0cmFuc2ZlcihhZGRyZXNzLHVpbnQyNTYpIgogICAgMHhhOTA1OWNiYgogICAgInRyYW5zZmVyRnJvbShhZGRyZXNzLGFkZHJlc3MsdWludDI1NikiCiAgICAweDIzYjg3MmRkCiAgICAqLwogICAgZnVuY3Rpb24gZ2V0U2VsZWN0b3Ioc3RyaW5nIGNhbGxkYXRhIF9mdW5jKSBleHRlcm5hbCBwdXJlIHJldHVybnMgKGJ5dGVzNCkgewogICAgICAgIHJldHVybiBieXRlczQoa2VjY2FrMjU2KGJ5dGVzKF9mdW5jKSkpOwogICAgfQp9Cg==",
},
]
const html = `<p>When a function is called, the first 4 bytes of <code>calldata</code> specifies which function to call.</p>
<p>This 4 bytes is called a function selector.</p>
<p>Take for example, this code below. It uses <code>call</code> to execute <code>transfer</code> on a contract at the address <code>addr</code>.</p>
<pre><code class="language-solidity">addr.<span class="hljs-built_in">call</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"transfer(address,uint256)"</span>, 0xSomeAddress, <span class="hljs-number">123</span>))
</code></pre><p>The first 4 bytes returned from <code>abi.encodeWithSignature(....)</code> is the function selector.</p>
<p>Perhaps you can save a tiny amount of gas if you precompute and inline the function selector in your code?</p>
<p>Here is how the function selector is computed.</p>
<pre><code class="language-solidity"><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.8.20;</span>
<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">FunctionSelector</span> </span>{
<span class="hljs-comment">/*
"transfer(address,uint256)"
0xa9059cbb
"transferFrom(address,address,uint256)"
0x23b872dd
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getSelector</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> <span class="hljs-keyword">calldata</span> _func</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">pure</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bytes4</span></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">bytes4</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-keyword">bytes</span>(_func)));
}
}
</code></pre>`
export default html
|
abb0432662b55d37bcc0ab6ca4cc45630b9e1089
|
TypeScript
|
RaduMatees/EmployeesWorkManager
|
/Frontend/src/api/ApiClient.ts
| 2.5625
| 3
|
import axios, { AxiosInstance } from 'axios'
import { TypeRegister, TypeLogin } from '@/interfaces/type-auth'
export default class ApiClient {
public restClient: AxiosInstance
private static _instance: ApiClient
constructor() {
this.restClient = axios.create({
baseURL: `http://localhost:5000`,
headers: { 'content-type': 'application/json', 'Access-Control-Allow-Origin': "*" }
})
}
public static getInstance() {
return this._instance || (this._instance = new this())
}
public setTokenFromStorage() {
const token = localStorage.getItem('token')
if (token) {
this.restClient.defaults.headers.common['x-auth-token'] = token
return true
}
return false
}
public async loadUser() {
const user = await this.restClient.get('/api/users')
return user
}
public clearToken() {
localStorage.removeItem('token')
delete this.restClient.defaults.headers.common['x-auth-token']
}
private setToken(token: string) {
localStorage.setItem('token', token)
this.restClient.defaults.headers.common['x-auth-token'] = token
}
async registerUser(formData: TypeRegister) {
const { name, email, password, role } = formData
const newUser = { name, email, password }
try {
const body = JSON.stringify(newUser)
const res = await this.restClient.post(`/api/users/register-${role}`, body)
console.log('Succesfully registered the user')
this.setToken(res.data.token)
return { success: res.data.success, status: res.data.status, user: res.data.user }
} catch (err) {
console.error('Error registering a user', err.response.data)
this.clearToken()
return err.response.data.success
}
}
async loginUser(formData: TypeLogin) {
const { email, password, role } = formData
const user = { email, password, role }
try {
const body = JSON.stringify(user)
const res = await this.restClient.post(`/api/users/login-${role}`, body)
console.log('Succesfully logged in')
this.setToken(res.data.token)
return { success: res.data.success, status: res.status, user: res.data.user }
} catch (err) {
console.error('Error loggin in', err.response.data)
this.clearToken()
return { success: err.response.data.success, status: err.response.status }
}
}
async getAccessTokenFromGithub(code: string) {
try {
const response = await this.restClient.post(`/api/oauth/github-token/${code}`)
return response.data.token
} catch (err) {
console.error('Error retreiving the access token from Github', err)
}
}
async getRepositories(token: string) {
try {
return await this.restClient.get(`/api/oauth/github/repositories/${token}`)
} catch (err) {
console.error('Error fetching repositories, ', err)
}
}
async getMembers(token: string) {
try {
// return await this.restClient.get(`/api/oauth/github/members/${token}`)
return await this.restClient.get(`/api/oauth/github/repositories/${token}`)
} catch (err) {
console.error('Error fetching members, ', err)
}
}
}
|
1fc347d119b791c6e0d2a9ef51da1a08db42cc50
|
TypeScript
|
jdforsythe/bloch
|
/src/chain/chain.ts
| 3.015625
| 3
|
import { getGenesisBlock, hashBlock } from './block';
import { getCurrentBalance } from './wallet';
import { Blockchain, Block, SignedTransaction } from './interface';
/**
* Genesis of the blockchain
*/
export function getInitialBlockchain(address: string): Blockchain {
const chain: Blockchain = {
blocks: [getGenesisBlock()],
mempool: [],
wallet: {
address,
balance: 0,
},
};
chain.wallet.balance = getCurrentBalance(chain.wallet.address, chain.blocks);
return chain;
}
/**
* Utility to get the last block in a chain
*/
export function getLastBlockHash(chain: Blockchain): string {
return chain.blocks[chain.blocks.length - 1].hash;
}
/**
* Given a new potential chain, return the new blockchain state
* by replacing our chain if the new one is valid and longer
* or keeping our existing chain if the new one is invalid
*/
export function getBestChain(chain: Blockchain, newChain: Blockchain): Blockchain {
// if chain is not longer than ours or it's invalid, keep our chain
if (newChain.blocks.length <= chain.blocks.length || !isValidChain(newChain.blocks)) {
return chain;
}
return newChain;
}
/**
* When a new block is mined, get the new blockchain state to send to peers
* and continue working from
*/
export function getChainWithNewBlock(chain: Blockchain, block: Block): Blockchain {
// filter transactions from the new block out of the mempool
const transactionIds = block.data.map((tx: SignedTransaction) => tx.id);
const blocks = [...chain.blocks, block];
const mempool = chain.mempool.filter((tx: SignedTransaction) => {
return !transactionIds.includes(tx.id);
});
return { ...chain, blocks, mempool };
}
/**
* Determine if the provided chain is valid
*/
function isValidChain(newChain: Block[]): boolean {
// verify first block is genesis block
if (JSON.stringify(newChain[0]) !== JSON.stringify(getGenesisBlock())) {
return false;
}
for (let i = 1; i < newChain.length; i += 1) {
const current: Block = newChain[i];
const last: Block = newChain[i - 1];
// verify provenance of each block
if (current.lastHash !== last.hash) {
return false;
}
// verify current hash
if (current.hash !== hashBlock(current)) {
return false;
}
}
return true;
}
|
fcb70f721f11bf8b1a9d606167bf950e45e44115
|
TypeScript
|
freewind-demos/typescript-jest-test-async-callback-demo
|
/add.ts
| 2.78125
| 3
|
export default function asyncAdd(a: number, b: number, callback: (result: number) => void): void {
new Promise<number>(resolve => {
resolve(a + b);
}).then(result => callback(result));
};
|
c15c461239c1b6bc7eeeb4733ca16200a10ecc30
|
TypeScript
|
dmlaziuk/ylf-di-workshop
|
/example5/locator.ts
| 2.671875
| 3
|
export class Locator {
private static dictionary: Map<string, any> = new Map();
static getService<T>(token: string): T {
return this.dictionary.get(token);
}
static register(token, instance) {
this.dictionary.set(token, instance);
}
}
|
88751bc266978ec9bc81a241ac99377c0a949f9c
|
TypeScript
|
tetious/LarkyPrintWeb
|
/custom_typings/eventSource.d.ts
| 2.78125
| 3
|
interface EventSourceMap {
"error": Event;
"message": MessageEvent;
"open": Event;
}
interface EventSourceConfig {
withCredentials?: boolean;
}
interface EventSource extends EventTarget {
readonly readyState: number;
readonly url: string;
readonly withCredentials: boolean;
readonly CONNECTING: number;
readonly OPEN: number;
readonly CLOSED: number;
onopen: (this: EventSource, ev: Event) => any;
onmessage: (this: EventSource, ev: MessageEvent) => any;
onerror: (this: EventSource, ev: Event) => any;
close: () => void;
addEventListener<K extends keyof EventSourceMap>(type: K, listener: (this: WebSocket, ev: EventSourceMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var EventSource: {
prototype: EventSource;
new(url: string, configuration?: EventSourceConfig): EventSource;
readonly CONNECTING: number;
readonly OPEN: number;
readonly CLOSED: number;
}
|
3699947a36e4aa5dba4b8a2d8786a2f916c327f5
|
TypeScript
|
Dave9819/few100-lab-DAH
|
/src/utils.ts
| 2.765625
| 3
|
export interface IBillData {
billBeforeTip: number,
tipPercentageTxt: string,
tipPercentage: number,
tipAmount: number,
totalBill: number
}
export const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
export function getSelectionStart(element) {
return element.selectionStart
}
export function getTipPercentage(tipBtnClickedId: string) {
let tipPercent = 0;
switch (tipBtnClickedId) {
case '10':
tipPercent = 10;
break;
case '15':
tipPercent = 15;
break;
case '20':
tipPercent = 20;
break;
default:
tipPercent = 0;
}
return tipPercent;
}
export function updateBillData(billAmount: number, tipPercentage: number) {
let billNoTip = 0;
let tipPrctTxt = '';
let tipPrct = 0;
let tipAmt = 0;
let totBill = 0;
if (!isNaN(billAmount)) {
billNoTip = billAmount;
}
else {
billNoTip = 0;
}
if (!isNaN(tipPercentage)) {
tipPrctTxt = tipPercentage.toString() + '%';
tipPrct = (tipPercentage / 100);
}
else {
tipPrctTxt = '0%';
tipPrct = 0;
}
tipAmt = tipPrct * billNoTip;
totBill = tipAmt + billNoTip;
let newBillData = { billBeforeTip: billNoTip, tipPercentageTxt: tipPrctTxt, tipPercentage: tipPrct, tipAmount: tipAmt, totalBill: totBill };
return newBillData;
}
|
6424214373a9a46e7162ba46c36cbf32d64aa411
|
TypeScript
|
ChristineH122/ITSecurity3
|
/webserver/src/entity/Sensor.ts
| 2.5625
| 3
|
import {Entity, Column, PrimaryGeneratedColumn} from 'typeorm';
@Entity({name: "Sensor"})
export class Sensor {
@PrimaryGeneratedColumn({name: "Id"})
public id: number;
@Column({name: "Name"})
public name: string;
@Column({name: "Value"})
public value: string;
}
|
bdfc88d4f1e3de5fac7c7dc7b41fb8225f9f143f
|
TypeScript
|
seba-ban/simple-movie-api
|
/src/routes/movies.ts
| 2.578125
| 3
|
import express, { Request, Response, NextFunction } from 'express';
import { Op } from 'sequelize';
import { celebrate, Joi, Segments, isCelebrateError } from 'celebrate';
import { Movie } from '../models/Movie';
import { fetchMovieDetails } from '../helpers/movieApi';
import { authenticate } from '../middlewares/authenticate';
import { User } from '../models/User';
import moment from 'moment';
const router = express.Router();
// Added to have properly typed user on the req.body
declare module 'express-serve-static-core' {
interface Request {
user?: User;
}
}
router.get('/', authenticate(), async (req: Request, res) => {
const user = req.user;
// This is added just to ensure Typescript that user is not undefined
// the authenticate middleware makes sure user is set now on req
if (!user) return res.sendStatus(500);
const movies = await Movie.findAll({ where: { UserId: user.getKey('id') } });
const response = movies.map((movie) => movie.extractInterfaceKeys());
res.json(response);
});
/**
* A small middleware to make sure we have the proper body object
* @returns middleware
*/
const checkBody = () =>
celebrate({
[Segments.BODY]: Joi.object({
title: Joi.string().required().max(500),
}),
});
router.post(
'/',
express.json(),
authenticate(),
checkBody(),
async (req: Request<{}, {}, { title: string }>, res) => {
const user = req.user;
// same comment as in get path
if (!user) return res.sendStatus(500);
const userRole = user.getKey('role');
// if basic user, check registrations for this month
if (userRole === 'basic') {
const startOfMonth = moment().startOf('month').hour(0).minute(0).toDate();
const monthlyLimit = 5;
const movies = await Movie.findAll({
where: {
createdAt: {
[Op.gte]: startOfMonth,
},
UserId: user.getKey('id'),
},
});
// going off limits is a no-no
if (movies.length >= monthlyLimit)
return res
.status(403)
.json({ error: 'Limit of 5 created movies reached for this month.' });
}
// at this point we're sure we can go ahead with
// creating a new movie
const { title } = req.body;
const movieData = await fetchMovieDetails(title);
if (!movieData) return res.sendStatus(503);
const movie = await Movie.create({
...movieData,
UserId: user.getKey('id'),
});
res.status(201).send(movie.extractInterfaceKeys());
}
);
// we need to catch the `celebrate` error to send correct message
router.use((err: Error, req: Request, res: Response, done: NextFunction) => {
if (!isCelebrateError(err)) return done(err);
return res.sendStatus(400);
});
export default router;
|
d87a0cbbe8a373a6a76dbbd66a477dc29fe5062c
|
TypeScript
|
noahlange/superjucks
|
/packages/superjucks/src/tests/nodes/Import.ts
| 2.625
| 3
|
import test from 'ava';
import { lex } from '../../Lexer';
import * as Nodes from '../../nodes/index';
import { parse } from '../../Parser';
import { parse as p } from '../helpers/parse';
test('should throw on unnamed wildcards', t => {
t.throws(() => p("{% import * from 'bar.sjk' %}"));
});
test('should throw on imports without "from"', t => {
t.throws(() => p("{% import * as bar 'bar.sjk' %}"));
});
test('should throw on imports with wildcards and commas', t => {
t.throws(() => p("{% import * as bar, baz from 'bar.sjk' %}"));
});
test('should allow multiple imports, so long as the first is a default one', t => {
t.notThrows(() => p("{% import bar, { baz } from 'bar.sjk' %}"));
});
test('should parse an Import node', t => {
const str = "{% import * as foo from 'bar.sjk' %}";
t.deepEqual(p(str), [
Nodes.Root,
[
Nodes.Import,
[Nodes.Literal, 'bar.sjk'],
[Nodes.Array, [Nodes.Symbol, 'foo']],
true
]
]);
});
test('should parse an Import node', t => {
const str = "{% import { foo, bar } from 'bar.sjk' %}";
t.deepEqual(p(str), [
Nodes.Root,
[
Nodes.Import,
[Nodes.Literal, 'bar.sjk'],
[Nodes.Array, [Nodes.Dict, [Nodes.Symbol, 'foo'], [Nodes.Symbol, 'bar']]],
false
]
]);
});
test('should parse an Import node', t => {
const str = "{% import { foo, bar, baz, bat } from 'bar.sjk' %}";
t.deepEqual(p(str), [
Nodes.Root,
[
Nodes.Import,
[Nodes.Literal, 'bar.sjk'],
[
Nodes.Array,
[
Nodes.Dict,
[Nodes.Symbol, 'foo'],
[Nodes.Symbol, 'bar'],
[Nodes.Symbol, 'baz'],
[Nodes.Symbol, 'bat']
]
],
false
]
]);
});
|
e0e0db62961189d25cf6c42a7ae55fba6c85a4bd
|
TypeScript
|
sanwu/Wonder.js
|
/converter/common/Vector2.ts
| 3.4375
| 3
|
export = class Vector2 {
public static create(x, y):Vector2 ;
public static create():Vector2 ;
public static create():Vector2 {
var m = null;
if (arguments.length === 0) {
m = new this();
}
else {
m = new this(arguments[0], arguments[1]);
}
return m;
}
constructor(x, y);
constructor();
constructor() {
this.values = new Float32Array(2);
if (arguments.length > 0) {
this.values[0] = arguments[0];
this.values[1] = arguments[1];
}
}
get x() {
return this.values[0];
}
set x(x:number) {
this.values[0] = x;
}
get y() {
return this.values[1];
}
set y(y:number) {
this.values[1] = y;
}
public values:Float32Array;
public set(x:number, y:number) {
this.x = x;
this.y = y;
}
}
|
2d0f0068f48de5a4fe8ae089180ff904b86b9d5b
|
TypeScript
|
cmprog/web-sandbox
|
/Beez/Hive.ts
| 2.5625
| 3
|
import { Property } from '../Framework/Property.js';
import { FixedUpdatable } from '../Framework/Updatable.js';
import { TickCountdownGenerator } from '../Framework/Generators.js';
import { Collection } from '../Framework/Collection.js';
import { TemplateComponent, TemplateContext } from '../Framework/Bindings.js';
import { Formatters } from '../Framework/Formatters.js';
import { State } from './State.js';
import { TimedAction } from './Actions.js';
export class HiveSuper implements TemplateComponent {
readonly pollen = new Property(0);
readonly honey = new Property(0);
readonly pollenCapacity = new Property(10);
readonly isInactive = new Property<boolean>(false);
attachTemplateBindings(context: TemplateContext) {
context.propertyBinding('.pollen .value', this.pollen, Formatters.Fixed_0);
context.propertyBinding('.honey .value', this.honey, Formatters.Fixed_0);
context.propertyBinding('.resource-capacity .value', this.pollenCapacity, Formatters.Fixed_0);
const dualProgress = context.dualProgressBar('.dual-progress', this.pollen, this.honey, this.pollenCapacity);
if (dualProgress) {
dualProgress.defaultTitle = 'Remaining capacity';
dualProgress.primaryTitle = 'Amount of pollen collected.';
dualProgress.secondaryTitle = 'Amount of pollen converted to honey.';
}
context.bindCommand('.collect', this._onCollect.bind(this));
context.bindCommand('.load', this._onLoadExtractor.bind(this));
context.bindCommand('.store', this._onStore.bind(this));
context.classBinding(null, this.isInactive, 'inactive');
}
private _findHive(state: State): Hive {
if (state.hive.supers.contains(this)) {
return state.hive;
}
return null;
}
private _onCollect() {
const state = State.current;
const hive = this._findHive(state);
if (!hive) return;
state.enqueueAction(new HiveSuperTransportAction(this,
hive.supers,
state.beeKeeper.supers,
state.beeKeeper.superCapacity,
state.beeKeeper.collectionSpeed
));
}
private _onStore() {
const state = State.current;
state.enqueueAction(new HiveSuperTransportAction(this,
state.beeKeeper.supers,
state.honeyHouse.supers,
state.honeyHouse.superCapacity,
state.beeKeeper.storeSuperSpeed
));
}
private _onLoadExtractor() {
const state = State.current;
// This super may be on the bee keeper or the honey house storage.
let sourceCollection: Collection<HiveSuper> = null;
if (state.honeyHouse.supers.contains(this)) {
sourceCollection = state.honeyHouse.supers;
}
if (state.beeKeeper.supers.contains(this)) {
sourceCollection = state.beeKeeper.supers;
}
state.enqueueAction(new HiveSuperTransportAction(this,
sourceCollection,
state.extractor.supers,
state.extractor.superCapacity,
state.beeKeeper.extractorLoadingSpeed
));
}
}
class HiveSuperTransportAction extends TimedAction {
constructor(
private readonly _hiveSuper: HiveSuper,
private readonly _sourceCollection: Collection<HiveSuper>,
private readonly _targetCollection: Collection<HiveSuper>,
private readonly _targetCapacity: Property,
private readonly _duration: Property) {
super();
}
protected _getDuraction(): number {
if (this._targetCollection.count.value >= this._targetCapacity.value) {
return null;
}
// Make sure the super is still part of the source collection
if (this._sourceCollection.contains(this._hiveSuper)) {
this._hiveSuper.isInactive.value = true;
return this._duration.value;
}
return null;
}
protected _execute(): void {
if (this._sourceCollection.remove(this._hiveSuper)) {
this._hiveSuper.isInactive.value = false;
this._targetCollection.add(this._hiveSuper);
}
}
}
export class Hive implements FixedUpdatable {
constructor() {
this.supers.add(new HiveSuper());
}
readonly supers = new Collection<HiveSuper>();
readonly superCount = new Property(0);
readonly superCapacity = new Property(0);
readonly workerCount = new Property(1);
readonly workerRate = new Property(0.1);
readonly foragerCount = new Property(1);
readonly forageAmount = new Property(1);
readonly forageSpeed = new Property(1);
readonly forageRemainingDistance = new Property(2);
readonly forageDistance = new Property(2);
readonly beeCapacity = new Property(3);
createForagerGenerator(): TickCountdownGenerator {
return new TickCountdownGenerator(this.forageRemainingDistance, this.forageDistance, this._collectPollen.bind(this));
}
addSuper() {
this.supers.add(new HiveSuper());
}
private _collectPollen() {
let pollenCollected = this.foragerCount.value * this.forageAmount.value;
for (const hiveSuper of this.supers) {
if (hiveSuper.isInactive.value) continue;
if (pollenCollected <= 0) break;
const remainingCapacity = hiveSuper.pollenCapacity.value - (hiveSuper.pollen.value + hiveSuper.honey.value);
const pollenDelta = Math.min(remainingCapacity, pollenCollected);
hiveSuper.pollen.value += pollenDelta;
pollenCollected -= pollenDelta;
}
}
private _processPollen() {
let generatedHoney = this.workerCount.value * this.workerRate.value;
for (const hiveSuper of this.supers) {
if (hiveSuper.isInactive.value) continue;
if (generatedHoney <= 0) break;
const honeyDelta = Math.min(hiveSuper.pollen.value, generatedHoney);
hiveSuper.honey.value += honeyDelta;
hiveSuper.pollen.value -= honeyDelta;
generatedHoney -= honeyDelta;
}
}
fixedUpdate() {
this._processPollen();
}
}
|
c35f9baa2048975152cca7c440accfc52848fe4e
|
TypeScript
|
future4code/Joao-Meira
|
/logic-exercises/src/exercicio6.ts
| 2.703125
| 3
|
export function revertString(string : string) {
return string.split("").reverse().join("");
}
console.log(revertString("escola"));
|
43e7ac460e1beed0aae4bceb5eedf389a934541e
|
TypeScript
|
nivinjoseph/n-defensive
|
/test/general.test.ts
| 3.15625
| 3
|
import { ArgumentNullException } from "@nivinjoseph/n-exception";
import * as assert from "assert";
import { given } from "../src/index";
suite("General", () =>
{
// let arg: any;
// let argName: any;
let exceptionHappened: boolean;
let exceptionType: string;
let reason: any;
setup(() =>
{
// arg = null;
// argName = null;
exceptionHappened = false;
reason = null;
});
suite("given", () =>
{
test("should throw an ArgumentNullException if argName (second arg) is null", () =>
{
assert.throws(() =>
{
given(null, null as any);
}, ArgumentNullException);
});
test("should throw an ArgumentNullException if argName (second arg) is undefined", () =>
{
assert.throws(() =>
{
given(null, undefined as any);
}, ArgumentNullException);
});
test("should throw an ArgumentNullException if argName (second arg) is an empty string", () =>
{
assert.throws(() =>
{
given(null, "");
}, ArgumentNullException);
});
test("should throw an ArgumentNullException if argName (second arg) is an whitespace string", () =>
{
assert.throws(() =>
{
given(null, " ");
}, ArgumentNullException);
});
test("given should return an Ensurer object", () =>
{
const ensurer = given({}, "argName");
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
assert.ok(ensurer != null);
});
});
suite("ensureHasValue", () =>
{
test("should throw ArgumentNullException if arg is null", () =>
{
try
{
given(null as any, "argName").ensureHasValue();
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentNullException");
});
test("should throw ArgumentNullException if arg is undefined", () =>
{
// arg = undefined;
try
{
given(undefined as any, "argName").ensureHasValue();
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentNullException");
});
test("should throw ArgumentException if arg is empty string", () =>
{
// arg = "";
// argName = "argName";
try
{
given("", "argName").ensureHasValue();
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentException");
});
test("should throw ArgumentException if arg is whitespace string", () =>
{
// arg = " ";
// argName = "argName";
try
{
given(" ", "argName").ensureHasValue();
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentException");
});
test("should not throw any exceptions if arg has value", () =>
{
// arg = "arg";
// argName = "argName";
try
{
given("arg", "argName").ensureHasValue();
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, false);
});
});
suite("ensure", () =>
{
const arg = "arg";
const argName = "argName";
setup(() =>
{
// arg = "arg";
// argName = "argName";
});
test("should throw ArgumentNullException if func is null", () =>
{
try
{
given(arg, argName).ensure(null as any, "reason");
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentNullException");
});
test("should throw ArgumentNullException if func is undefined", () =>
{
try
{
given(arg, argName).ensure(undefined as any, "reason");
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentNullException");
});
test("should throw InvalidArgumentException if func returns false", () =>
{
try
{
given(arg, argName)
.ensure(_arg => false);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "InvalidArgumentException");
});
test("should not throw any exceptions if the func returns true", () =>
{
try
{
given(arg, argName)
.ensure(_arg => true, "reason");
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, false);
});
});
suite("ensure with reason", () =>
{
const arg = "arg";
const argName = "argName";
// setup(() =>
// {
// });
test("should throw InvalidArgumentException if func returns false and reason is null", () =>
{
try
{
given(arg, argName).ensure(_arg => false, reason);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "InvalidArgumentException");
});
test("should throw InvalidArgumentException if func returns false and reason is undefined", () =>
{
reason = undefined;
try
{
given(arg, argName).ensure(_arg => false, reason);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "InvalidArgumentException");
});
test("should throw InvalidArgumentException if func returns false and reason is empty string", () =>
{
reason = "";
try
{
given(arg, argName).ensure(_arg => false, reason);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "InvalidArgumentException");
});
test("should throw InvalidArgumentException if func returns false and reason is whitespace string", () =>
{
reason = " ";
try
{
given(arg, argName).ensure(_arg => false, reason);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "InvalidArgumentException");
});
test("should throw ArgumentException if func returns false and reason is a valid string", () =>
{
reason = "reason";
try
{
given(arg, argName).ensure(_ => false, reason);
}
catch (exp)
{
exceptionHappened = true;
exceptionType = (<Object>exp).getTypeName();
}
assert.strictEqual(exceptionHappened, true);
assert.strictEqual(exceptionType, "ArgumentException");
});
});
});
|
3e53d184e97cb06c5783676cf31acc8b10411b5c
|
TypeScript
|
joyned/hiremeweb-angular
|
/src/app/services/alert-message/alert-message.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'any'
})
export class AlertMessageService {
constructor() { }
private loaderSubject = new Subject<MessageState>();
loaderState = this.loaderSubject.asObservable();
public infoMessage(message: string, detail: string) {
this.message('info', message, detail);
}
public errorMessage(message: string, detail: string) {
this.message('error', message, detail);
}
public successMessage(message: string, detail: string) {
this.message('success', message, detail);
}
private message(severityMessage: string, messageText: string, detailText: string) {
this.loaderSubject.next({
severity: severityMessage,
message: messageText,
detail: detailText
} as MessageState);
}
}
export interface MessageState {
severity: string;
message: string;
detail: string;
}
|
e7b68afa1c207ef1df81530ec06baa0d21c889ff
|
TypeScript
|
githbq/hbq-koa2-base
|
/src/common/ftpHelper.ts
| 2.578125
| 3
|
import * as FtpHelper from 'ftp-helper'
import ioHelper from './ioHelper'
let { pathTool } = ioHelper
function getPrefix() {
let prefix = appUtils.isDev() ? '/' : '/'
return prefix
}
/**
* ftp操作辅助
*/
export default {
FtpHelper,
async uploaDistFiles() {
return await this.uploadFiles(getPrefix(), APP_CONFIG.staticPath)
},
async uploadUploadFiles() {
return await this.uploadFiles(getPrefix(), APP_CONFIG.uploadPath, {
onGetRelativePath(path) {
return ioHelper.join(pathTool.basename(APP_CONFIG.uploadPath), path)
}
})
},
async uploadFiles(prefix, cwd, options = { onGetRelativePath: null }) {
const ftp = new FtpHelper(APP_CONFIG.staticFtp, { prefix, isShowLog: false, isOnce: false })
await ftp.getConnection()//主动连接
//得到的是相对路径
let paths = await ioHelper.globby(['**/*.*'], { cwd: cwd, nodir: true })
appUtils.log(`共找到${paths.length}个文件`)
let pathData = paths.map((path) => {
let relativePath = options.onGetRelativePath ? options.onGetRelativePath(path) : path
appUtils.log('ioHelper.resolve(path)', pathTool.resolve(relativePath))
appUtils.log('relativePath', relativePath)
return { localPath: ioHelper.resolve(cwd, path), remotePath: relativePath }
})
let count = 0
await Promise.map(pathData, ({ localPath, remotePath }, i) => {
appUtils.log(`正在上传第${i}个文件 path:${localPath}`)
return ftp.upload(localPath, remotePath).then(() => {
count++
appUtils.log(`剩余:${paths.length - count}个文件`)
}).catch((e) => {
count++
appUtils.error(e.message)
})
}, { concurrency: 5 })
appUtils.log(`所有文件上传结束`)
await ftp.closeConnection()
return { count: paths.length, files: paths }
}
}
|
553e78994f5153996b9bc7dc6439206671639efd
|
TypeScript
|
PastaBolo/strovo
|
/strovo-api/src/users/users.service.ts
| 2.546875
| 3
|
import { Injectable, Inject } from '@nestjs/common';
import { Model } from 'mongoose';
import { User } from './user';
@Injectable()
export class UsersService {
constructor(@Inject('UsersModelToken') private readonly UserModel: Model<User>) { }
async findAll(): Promise<User[]> {
const users = await this.UserModel.find();
return users.map(user => user.toJSON()).map(({ password, ...result }) => result);
}
async find(id: number): Promise<User> {
const user = await this.UserModel.findOne({ id });
if (user) {
const { password, ...result } = user.toJSON();
return result;
} else throw new Error('Run not found');
}
async findByUsername(username: string) {
return await this.UserModel.findOne({ username });
}
}
|
90e766c2dde45c443c1f5fc45efbd61ca1bd7536
|
TypeScript
|
sony/mapray-js
|
/packages/mapray/src/animation/ComboVectorCurve.ts
| 3.140625
| 3
|
import Time from "./Time";
import Curve from "./Curve";
import Interval from "./Interval";
import Invariance from "./Invariance";
import Type from "./Type";
import ConstantCurve from "./ConstantCurve";
import TypeMismatchError from "./TypeMismatchError";
import AnimUtil from "./AnimUtil";
/**
* 複合ベクトル関数
*
* 複数の数値関数から構成されるベクトル関数である。
*
* 関数値の型は構築子のパラメータにより vector2, vector3 または vector4 を指定する。
*
* 子関数は number または number へ変換可能な型でなければならない。
*/
class ComboVectorCurve extends Curve
{
private _vector_type: Type;
/** 2〜4 */
private _dimension: number;
/** 子関数の配列 */
private _children: Curve[];
/** 子関数に対応した */
private _listeners: Curve.ValueChangeListener[];
/**
* type 型のベクトル関数を生成する。ベクトルの各要素の値は子関数の値になる。
*
* children を省略したときは、ベクトルの全要素が 0 となる定数関数と同等になる。children の形式に関しては
* [[ComboVectorCurve.setChildren setChildren()]] を参照のこと。
*
* @param type 関数値の型 (ベクトル型)
* @param children 初期の全子関数
*
* @throws [[TypeMismatchError]] type または children に非対応の型が存在するとき
*/
constructor( type: Type, children?: Curve[] )
{
super();
const dimension = AnimUtil.getDimension( type );
if ( dimension < 2 && dimension > 4 ) {
// type はベクトル型ではない
throw new TypeMismatchError( "unexpected type" );
}
this._vector_type = type;
this._dimension = dimension;
this._children = new Array( dimension );
this._listeners = new Array( dimension );
this._setupInitialChildren();
// 初期値が指定されているときは設定
if ( children !== undefined ) {
this.setChildren( children );
}
}
/**
* 子関数を設定 (個別)
*
* index の要素のみの子関数を設定する。その他の要素は変更されない。
*
* @param index 要素インデックス
* @param curve 子関数
*
* @throws [[TypeMismatchError]] curve が非対応の型のとき
*/
setChild( index: number, curve: Curve )
{
this._setChildCommon( index, curve );
// curve が未知なので全時刻の値が変化したことにする
this.notifyValueChange( Interval.UNIVERSAL );
}
/**
* 子関数を設定 (一括)
*
* curves にすべての子関数を指定する。curves の要素数はベクトルの次数と同数である。
*
* @param curves 全子関数
*
* @throws [[TypeMismatchError]] curves に非対応の型が存在するとき
*/
setChildren( curves: Curve[] )
{
for ( let i = 0; i < this._dimension; ++i ) {
this._setChildCommon( i, curves[i] );
}
// curves が未知なので全時刻の値が変化したことにする
this.notifyValueChange( Interval.UNIVERSAL );
}
override isTypeSupported( type: Type )
{
let from_type = this._vector_type;
return type.isConvertible( from_type );
}
override getValue( time: Time, type: Type )
{
let from_type = this._vector_type;
let from_value = this._getCompoundValue( time );
return type.convertValue( from_type, from_value );
}
override getInvariance( interval: Interval ): Invariance
{
// すべての子関数の不変性情報の交差
const invariances = this._children.map( child => child.getInvariance( interval ) );
// @ts-ignore
return Invariance.merge( invariances );
}
/**
* 初期の子関数とリスナーを設定
*/
private _setupInitialChildren()
{
const init_child = new ConstantCurve( vec_compo_type );
for ( let i = 0; i < this._dimension; ++i ) {
const listener = (interval: Interval) => { this.notifyValueChange( interval ); };
init_child.addValueChangeListener( listener );
this._children[i] = init_child;
this._listeners[i] = listener;
}
}
/**
* 子要素を設定 (共通ルーチン)
*
* @param index
* @param curve
*
* @throws [[TypeMismatchError]]
*/
private _setChildCommon( index: number, curve: Curve )
{
if ( !curve.isTypeSupported( vec_compo_type ) ) {
// curve の型をベクトルの要素の型に変換できない
throw new TypeMismatchError( "type mismatch error" );
}
// 以前の子のリスナーを解除
let old_child = this._children[index];
let old_listener = this._listeners[index];
old_child.removeValueChangeListener( old_listener );
// 新しい子のリスナーを設定
let listener = (interval: Interval) => { this.notifyValueChange( interval ); };
curve.addValueChangeListener( listener );
// 新しい子を設定
this._children[index] = curve;
this._listeners[index] = listener;
}
/**
* time での複合値を取得
*
* @param Time time
*
* @return 複合値 (this._vector_type に適応した型)
*/
private _getCompoundValue( time: Time ): Float64Array
{
const dimension = this._dimension;
let vec = new Float64Array( dimension );
for ( let i = 0; i < dimension; ++i ) {
vec[i] = this._children[i].getValue( time, vec_compo_type );
}
return vec;
}
}
/**
* ベクトルの要素型
* @private
*/
const vec_compo_type = Type.find( "number" );
export default ComboVectorCurve;
|
b5af0ad369e99b873e0bc6680707c1d67912b8bb
|
TypeScript
|
thetlwinoo/gateway-portal
|
/src/main/webapp/app/shared/model/customers.model.ts
| 2.53125
| 3
|
import { Moment } from 'moment';
export interface ICustomers {
id?: number;
customerName?: string;
creditLimit?: number;
accountOpenedDate?: Moment;
standardDiscountPercentage?: number;
isStatementSent?: boolean;
isOnCreditHold?: boolean;
paymentDays?: number;
phoneNumber?: string;
faxNumber?: string;
deliveryRun?: string;
runPosition?: string;
websiteURL?: string;
deliveryAddressLine1?: string;
deliveryAddressLine2?: string;
deliveryPostalCode?: string;
deliveryLocation?: string;
postalAddressLine1?: string;
postalAddressLine2?: string;
postalPostalCode?: string;
validFrom?: Moment;
validTo?: Moment;
primaryContactPersonFullName?: string;
primaryContactPersonId?: number;
alternateContactPersonFullName?: string;
alternateContactPersonId?: number;
customerCategoryCustomerCategoryName?: string;
customerCategoryId?: number;
buyingGroupBuyingGroupName?: string;
buyingGroupId?: number;
billToCustomerCustomerName?: string;
billToCustomerId?: number;
deliveryCityCityName?: string;
deliveryCityId?: number;
postalCityCityName?: string;
postalCityId?: number;
deliveryMethodDeliveryMethodName?: string;
deliveryMethodId?: number;
}
export class Customers implements ICustomers {
constructor(
public id?: number,
public customerName?: string,
public creditLimit?: number,
public accountOpenedDate?: Moment,
public standardDiscountPercentage?: number,
public isStatementSent?: boolean,
public isOnCreditHold?: boolean,
public paymentDays?: number,
public phoneNumber?: string,
public faxNumber?: string,
public deliveryRun?: string,
public runPosition?: string,
public websiteURL?: string,
public deliveryAddressLine1?: string,
public deliveryAddressLine2?: string,
public deliveryPostalCode?: string,
public deliveryLocation?: string,
public postalAddressLine1?: string,
public postalAddressLine2?: string,
public postalPostalCode?: string,
public validFrom?: Moment,
public validTo?: Moment,
public primaryContactPersonFullName?: string,
public primaryContactPersonId?: number,
public alternateContactPersonFullName?: string,
public alternateContactPersonId?: number,
public customerCategoryCustomerCategoryName?: string,
public customerCategoryId?: number,
public buyingGroupBuyingGroupName?: string,
public buyingGroupId?: number,
public billToCustomerCustomerName?: string,
public billToCustomerId?: number,
public deliveryCityCityName?: string,
public deliveryCityId?: number,
public postalCityCityName?: string,
public postalCityId?: number,
public deliveryMethodDeliveryMethodName?: string,
public deliveryMethodId?: number
) {
this.isStatementSent = this.isStatementSent || false;
this.isOnCreditHold = this.isOnCreditHold || false;
}
}
|
d450049ba488ef3b6e583ec2f233fb91476bd3dc
|
TypeScript
|
void-aurora/toolkit
|
/packages/just/src/utils/async.ts
| 3.171875
| 3
|
/**
* Run async functions at the same time in specified limit number.
* @param actions the list of async functions.
* @param limit the limit number of actions can be run at the same time.
*/
export async function asyncParallel<T>(
actions: readonly (() => Promise<T>)[],
limit: number = 8,
): Promise<T[]> {
if (actions.length === 0) {
return [];
}
if (limit === 0 || limit >= actions.length) {
return Promise.all(actions.map(async a => a()));
}
return new Promise<T[]>((resolve, reject) => {
const { length } = actions;
const pool = [...actions];
const result: T[] = [];
let activeCount = 0;
let finishCount = 0;
const invoke = async (): Promise<void> => {
const index = activeCount;
activeCount += 1;
const { [index]: action } = pool;
if (action) {
try {
result[index] = await action();
finishCount += 1;
if (finishCount === length) {
resolve(result);
return;
}
} catch (error) {
reject(error);
return;
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
invoke();
}
};
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.all(pool.slice(0, limit).map(async () => invoke()));
});
}
|
b9a2dfdd992e98b51df1b80930b303237433bf47
|
TypeScript
|
thundercore/ThunderStorage
|
/backend/src/modules/DataSaver/services/dataSaver.repository.ts
| 2.5625
| 3
|
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { MetadataEntity } from '../entities/Metadata.entity'
import { ContentType } from '../constants/ContentType'
import { ContentEncoding } from '../constants/ContentEncoding'
import { RenderType } from '../constants/RenderType'
import { Transactional } from 'typeorm-transactional-cls-hooked'
import { Charset } from '../constants/Charset'
import { DataEntity } from '../entities/Data.entity'
import { sha256 } from 'ethers/utils/sha2'
import { TransactionDataEntity } from '../entities/TransactionData.entity'
interface IMetaData {
contentType: ContentType
contentEncoding?: ContentEncoding
charset?: Charset
}
interface ITransactionData {
transactionHash: string
renderType?: RenderType
}
@Injectable()
export class DataSaverRepository {
static getSha256BufferHash(buff: Buffer) {
// These are fixed and should only change if we use a different hashing algorithm
const sha256Code = '12'
const sha256DigestLength = '20'
const hashResult = sha256(buff).replace('0x', '')
return sha256Code + sha256DigestLength + hashResult
}
constructor(
@InjectRepository(DataEntity)
private readonly dataEntityRepository: Repository<DataEntity>,
@InjectRepository(MetadataEntity)
private readonly metadataEntityRepository: Repository<MetadataEntity>,
@InjectRepository(TransactionDataEntity)
private readonly transactionDataEntityRepository: Repository<
TransactionDataEntity
>
) {}
@Transactional()
async save(
binaryData: Buffer,
transactionData: ITransactionData,
metaData: IMetaData
): Promise<TransactionDataEntity> {
const hash = '0x' + DataSaverRepository.getSha256BufferHash(binaryData)
const dataEntity = this.dataEntityRepository.create({
binaryData
})
const metaEntity = this.metadataEntityRepository.create(metaData)
metaEntity.contentLength = binaryData.length
metaEntity.hash = hash
metaEntity.url = '/data/' + hash
await this.metadataEntityRepository.save(metaEntity)
const transactionDataEntity = this.transactionDataEntityRepository.create(
transactionData
)
dataEntity.metaData = metaEntity
transactionDataEntity.metaData = metaEntity
const [entity] = await Promise.all([
this.transactionDataEntityRepository.save(transactionDataEntity),
this.dataEntityRepository.save(dataEntity)
])
return entity
}
get(hash: string) {
return this.dataEntityRepository.findOne(hash)
}
}
|
e73a0024316f081290c9400b5c5e8ca1c26c8925
|
TypeScript
|
CodeMan99/wotblitz.js
|
/request.ts
| 2.734375
| 3
|
import fetch, {Response} from 'node-fetch';
import * as querystring from 'querystring';
import * as util from 'util';
type Region =
| '.com'
| '.asia'
| '.eu'
| '.ru'
type Language =
// "en" — English
| 'en'
// "ru" — Русский
| 'ru'
// "pl" — Polski
| 'pl'
// "de" — Deutsch
| 'de'
// "fr" — Français
| 'fr'
// "es" — Español
| 'es'
// "zh-cn" — 简体中文
| 'zh-cn'
// "zh-tw" — 繁體中文
| 'zh-tw'
// "tr" — Türkçe
| 'tr'
// "cs" — Čeština
| 'cs'
// "th" — ไทย (by default)
| 'th'
// "vi" — Tiếng Việt
| 'vi'
// "ko" — 한국어
| 'ko'
type HttpMethod = 'GET' | 'POST';
type RequestOptions = {
hostname: string;
language?: Language;
method?: HttpMethod;
path: string;
region?: Region;
}
class Request {
private appId: string | undefined;
region: Region;
language: Language;
userAgent = 'wotblitz-v1.3 (+https://github.com/CodeMan99/wotblitz.js)';
constructor(application_id?: string, region: Region = '.com', language: Language = 'en') {
this.appId = application_id;
this.region = region;
this.language = language;
}
get application_id(): string {
if (!this.appId) this.appId = process.env.APPLICATION_ID;
if (!this.appId) throw new Error('wotblitz/request: no APPLICATION_ID set in the environment');
return this.appId;
}
set application_id(appId: string) {
this.appId = appId;
}
/**
* WarGaming.net API request tool.
*
* @param {Object} options
* @param {string} options.hostname base host not including the TLD (example: "api.wotblitz")
* @param {string} [options.language=en] the response language, according to WarGaming.
* @param {string} [options.method=POST] the request method, normally "GET" or "POST"
* @param {string} options.path the request path part (example: "/wgn/servers/info/")
* @param {string} [options.region=.com] the region's top level domain part
* @param {Object} body use to specify the parameters of the route
* @returns {Promise<Object>} resolves to the "data" property of the request
* @see {@link https://developers.wargaming.net/documentation/guide/getting-started/|WarGaming.net Developer Room}
*/
async execute(options: RequestOptions, body: Record<string, any>): Promise<any> {
// assign defaults
options = Object.assign({
language: this.language,
method: 'POST',
region: this.region
}, options);
// Will throw error if `this.appId` is not set.
body.application_id = this.application_id;
body.language = options.language;
const url = 'https://' + options.hostname + options.region + options.path;
let request: Promise<Response>;
if (options.method !== 'GET') {
request = fetch(url, {
body: querystring.stringify(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': this.userAgent
},
method: options.method
});
} else {
request = fetch(url + '?' + querystring.stringify(body), {
headers: {
'User-Agent': this.userAgent
},
method: 'GET'
});
}
type ResponseError = {
code: number;
message: string;
field: string;
value: any;
}
type ResponseBody = {
status: 'ok';
data: any;
} | {
status: 'error';
error: ResponseError;
}
const response = await request;
const result: ResponseBody = await response.json();
switch (result.status) {
case 'ok':
return result.data;
case 'error':
// eslint-disable-next-line no-case-declarations
const e = result.error;
// eslint-disable-next-line no-case-declarations
const message = util.format('%d %s: %s=%j', e.code, e.message, e.field, e.value);
throw new Error(message);
default:
return null;
}
}
}
export = Request;
|
cbc057fcf2e3a15295e92258a36e93e632e6d025
|
TypeScript
|
ctagayun/ConsolidatedRepoGit2
|
/_00_Angular2-Kurata-Routing-With-Notes(VG)/APM12-Start-Advance-Routing-Lazy-Loading(Module12)old/src/app/user/auth-guard.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route,
CanActivate, CanActivateChild, CanLoad } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
constructor(private authService: AuthService,
private router: Router) { }
//the ActivatedRouteSnapshot provides information about the about-to-be activated
//route.
//RouterStateSnapshot provides access to the entire router state.
//checks if the user is currently logged in
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log('In canActivate: ' + state.url);
return this.checkLoggedIn(state.url);
}
//it calls the authorization service isLoggedIn method and returns true if the
//user is logged in. otherwise it redirets the to login page.
//we call this method from canActivate() method
checkLoggedIn(url: string): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
// Retain the attempted URL (In this case "Add Product")for redirection
this.authService.redirectUrl = url;
this.router.navigate(['/login']);
//returning false cancelling the navigation to the requested route
return false;
}
//Note: one of these two parameters must have the url that ws initially
//selected. In our example the "Add Product" url
//the RouterStateSnapshot will contain that url... ence the state.url
//eing pass to checkLoggedIn(state.url);
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log('In canActivateChild: ' + state.url);
return this.checkLoggedIn(state.url);
}
//unlike the canActivate, the canLoad cannot access the ActivatedRouteSnapShot or
//ROuterStateSnapshop bcause the module defining the route is not loaded yet.
//since we do not have access to ActivatedRouteSnapShot or ROuterStateSnapshop
//we will obtain the url from route.path property
canLoad(route: Route): boolean {
console.log('In canLoad: ' + route.path);
return this.checkLoggedIn(route.path);
}
}
//Note: since the auth-guard.serice is part of the user feature we will add it to the user.module.ts
|
b72c898ca28206418fd9da21ebec4fb9c05bed76
|
TypeScript
|
isnack/passaro-urbano
|
/src/app/carrinho.service.ts
| 2.734375
| 3
|
import { of } from 'rxjs';
import { ItemCarrinho } from './shared/itemCarrinho.model';
import { Oferta } from './shared/oferta.model';
export class CarrinhoService {
private itens: ItemCarrinho[] = [];
public getItens(): ItemCarrinho[] {
return this.itens;
}
public adicionarItemCarrinho(oferta: Oferta): void {
let itemCarrinho = new ItemCarrinho(
oferta.id,
oferta.imagens[0],
oferta.titulo,
oferta.descricao_oferta,
oferta.valor,
1,
);
let itemEncontrado = this.itens.find(
(item: ItemCarrinho) => item.id == itemCarrinho.id,
);
if (itemEncontrado) {
itemEncontrado.quantidade++;
} else {
this.itens.push(itemCarrinho);
}
}
public alterarQuantidadeItem(
itemCarrinho: ItemCarrinho,
param: string,
): void {
let itemEncontrado = this.itens.find(
(item: ItemCarrinho) => item.id == itemCarrinho.id,
);
if (param == '+') {
itemEncontrado.quantidade++;
} else if (param == '-') {
if (itemEncontrado.quantidade < 1) {
this.itens.splice(this.itens.indexOf(itemEncontrado), 1);
}
itemEncontrado.quantidade--;
}
}
public totalValor(): number {
let total: number = 0;
this.itens.map((item: ItemCarrinho) => {
total = total + item.quantidade * item.valor;
});
return total;
}
public limparItens(): void {
this.itens = [];
}
public verificarItemMaiorZero(itemCarrinho: ItemCarrinho[]): boolean {
let retorno: boolean = true;
itemCarrinho.map((item: ItemCarrinho) => {
if (item.quantidade === 0) retorno = false;
});
return retorno;
}
}
|
f4dece683d601f6ff52856e1c2a38f5c443076fd
|
TypeScript
|
jhoijune/algorithm
|
/src/Programmers/connectIslands.ts
| 3.296875
| 3
|
import {} from 'module';
class DisjointSet<T> {
private _parent: Map<T, T> = new Map();
makeGroup(element: T): T {
this._parent.set(element, element);
return element;
}
find(element: T): T {
let curr: T = element;
while (this._parent.get(curr)! !== curr) {
curr = this._parent.get(curr)!;
}
return curr;
}
union(elem1: T, elem2: T) {
let root1 = this.find(elem1);
let root2 = this.find(elem2);
if (root1 === root2) {
return;
}
if (root1 < root2) {
this._parent.set(root2, root1);
} else {
this._parent.set(root1, root2);
}
}
print() {
console.log(this._parent);
}
}
const solution = (n: number, costs: [number, number, number][]): number => {
costs.sort(([, , a], [, , b]) => a - b);
const ds = new DisjointSet<number>();
for (let num = 0; num < n; num++) {
ds.makeGroup(num);
}
const answer: number[] = [];
let index = 0;
while (answer.length !== n - 1) {
const [src, dst, cost] = costs[index++];
const srcRoot = ds.find(src);
const dstRoot = ds.find(dst);
if (srcRoot !== dstRoot) {
ds.union(srcRoot, dstRoot);
answer.push(cost);
}
}
return answer.reduce((prev, curr) => prev + curr, 0);
};
console.log(
solution(4, [
[0, 1, 1],
[0, 2, 2],
[1, 2, 5],
[1, 3, 1],
[2, 3, 8],
])
);
|
eae32ab009242aa3eecc20fb40d9ef7da31b1fe5
|
TypeScript
|
madanlimbu/hubspot-unopinionated-api
|
/src/api/file/query.ts
| 2.671875
| 3
|
import { Query, RequestParam } from '../Interface';
/***************** Request Type *****************/
export interface FileByIdRequest extends RequestParam {
pathParams: {
fileId: number | string;
};
}
export interface FileSignedUrlRequest extends RequestParam {
pathParams: {
fileId: number | string;
};
queryParams?: {
size?: 'thumb' | 'icon' | 'medium' | 'preview';
expirationSeconds?: number;
};
}
/***************** Response Types *****************/
export interface File {
id: string;
url: string;
path: string;
name: string;
extension: string;
type: string;
defaultHostingUrl: string;
createdAt: string;
updatedAt: string;
archived: boolean;
encoding: string;
access: 'PUBLIC_INDEXABLE' | 'PUBLIC_NOT_INDEXABLE' | 'PRIVATE' | 'HIDDEN_PRIVATE';
}
export interface FileSignedUrl {
// expiresAt: string;
url: string;
// name: string;
// extension: string;
// type: string;
// size: string;
}
/***************** Query function Types *****************/
// Query generators for Axios.
type QueryGetFileById = Query<FileByIdRequest>;
type QueryGetFileSignedUrlById = Query<FileSignedUrlRequest>;
/***************** Implementation of Query function Types *****************/
/**
* Get File detail by File ID
*
* @param ApiConfig
* @param FileByIdRequest
*/
export const queryFileById: QueryGetFileById = (config, arg) => {
const url = `https://api.hubspot.com/files/v3/files/${arg.params.pathParams.fileId}/?hapikey=${config.api_key}`;
const options = {
url,
method: <const>'GET',
};
return { ...options, ...arg.customAxiosConfig };
};
/**
* Get Private File Signed URL by File ID
*
* @param ApiConfig
* @param FileByIdRequest
*/
export const queryGetFileSignedUrlById: QueryGetFileSignedUrlById = (config, arg) => {
const { pathParams, queryParams } = arg.params;
const url = `https://api.hubspot.com/files/v3/files/${pathParams.fileId}/signed-url?hapikey=${config.api_key}`;
const options = {
url,
method: <const>'GET',
params: queryParams,
};
return { ...options, ...arg.customAxiosConfig };
};
|
1bb775cefc7075df1bddd5a57883456917b740f6
|
TypeScript
|
ysraelmoreno/probable-fortnight
|
/src/modules/courses/repositories/fakes/FakeCoursesRepository.ts
| 2.671875
| 3
|
import { uuid } from 'uuidv4'
import Course from '@modules/courses/infra/typeorm/entities/Course'
import ICreateCourseDTO from '@modules/courses/dtos/ICreateCourseDTO'
import IFindCourseByNameAndTeacherDTO from '@modules/courses/dtos/IFindCourseByNameAndTeacherDTO'
import ICourseRepository from '@modules/courses/repositories/ICoursesRepository'
import IListAllCoursesDTO from '@modules/courses/dtos/IListAllCoursesDTO'
class FakeCoursesRepository implements ICourseRepository {
private courses: Course[] = [];
public async findByIdAndName({ name, teacherId }: IFindCourseByNameAndTeacherDTO): Promise<Course | undefined> {
const findCourse = this.courses.find(course =>
course.teacherId === teacherId && course.name === name
)
return findCourse
}
public async list(id: string): Promise<Course[]> {
const courses = await this.courses.filter(course => course.teacherId === id)
return courses
}
public async create({ name, description, teacherId, category, tags, principalImage }: ICreateCourseDTO): Promise<Course> {
const course = new Course();
Object.assign(course, { id: uuid(), name, description, teacherId, category, tags, principalImage })
this.courses.push(course);
return course
}
}
export default FakeCoursesRepository;
|
61ad5e7848c9d0e894fa9e14b8a0568f816f22c9
|
TypeScript
|
demo-source/wasaby-controls
|
/tests/ControlsUnit/display/Abstract.test.ts
| 2.9375
| 3
|
import { assert } from 'chai';
import {
Abstract as Display,
Collection,
CollectionItem,
Enum as EnumDisplay,
Flags as FlagsDisplay
} from 'Controls/display';
import {
List,
Enum as EnumType,
Flags as FlagsType
} from 'Types/collection';
describe('Controls/_display/Abstract', () => {
describe('.getDefaultDisplay()', () => {
it('should return a display', () => {
const list = new List();
assert.instanceOf(Display.getDefaultDisplay(list), Display);
});
it('should return the special display for Array', () => {
const options = {keyProperty: 'foo'};
const display = Display.getDefaultDisplay<string, CollectionItem<string>, Collection<string>>([], options);
assert.instanceOf(display, Collection);
assert.equal(display.getKeyProperty(), options.keyProperty);
});
it('should return the special display for List', () => {
const collection = new List();
const display = Display.getDefaultDisplay(collection);
assert.instanceOf(display, Collection);
});
it('should return the special display for Enum', () => {
const collection = new EnumType();
const display = Display.getDefaultDisplay(collection);
assert.instanceOf(display, EnumDisplay);
});
it('should return the special display for Flags', () => {
const collection = new FlagsType();
const display = Display.getDefaultDisplay(collection);
assert.instanceOf(display, FlagsDisplay);
});
it('should throw an error for not IEnumerable', () => {
assert.throws(() => {
Display.getDefaultDisplay({} as any);
});
assert.throws(() => {
Display.getDefaultDisplay(null);
});
assert.throws(() => {
Display.getDefaultDisplay(undefined);
});
});
it('should return various instances', () => {
const list = new List();
const displayA = Display.getDefaultDisplay(list);
const displayB = Display.getDefaultDisplay(list);
assert.notEqual(displayA, displayB);
});
it('should return same instances', () => {
const list = new List();
const displayA = Display.getDefaultDisplay(list, {}, true);
const displayB = Display.getDefaultDisplay(list, {}, true);
assert.strictEqual(displayA, displayB);
});
});
describe('.releaseDefaultDisplay()', () => {
it('should return true if the display has been retrieved as singleton', () => {
const list = new List();
const display = Display.getDefaultDisplay(list, {}, true);
assert.isTrue(Display.releaseDefaultDisplay(display));
});
it('should return true if the display has been retrieved as not singleton', () => {
const list = new List();
const display = Display.getDefaultDisplay(list);
assert.isFalse(Display.releaseDefaultDisplay(display));
});
it('should destroy the instance after last one was released', () => {
const list = new List();
const displayA = Display.getDefaultDisplay(list, {}, true);
const displayB = Display.getDefaultDisplay(list, {}, true);
Display.releaseDefaultDisplay(displayA);
assert.isFalse(displayA.destroyed);
Display.releaseDefaultDisplay(displayB);
assert.isTrue(displayA.destroyed);
assert.isTrue(displayB.destroyed);
});
it('should force getDefaultDisplay return a new instance after last one was released', () => {
const list = new List();
const displayA = Display.getDefaultDisplay(list, {}, true);
const displayB = Display.getDefaultDisplay(list, {}, true);
Display.releaseDefaultDisplay(displayA);
Display.releaseDefaultDisplay(displayB);
const displayC = Display.getDefaultDisplay(list, {}, true);
assert.notEqual(displayC, displayA);
assert.notEqual(displayC, displayB);
});
});
});
|
954d421ddd5a79a7b9ea27be1ea04c011d9dd476
|
TypeScript
|
arifmedamine/cyberBlogApp
|
/src/issues/issues.service.ts
| 2.53125
| 3
|
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/core/prisma/prisma.service';
import { CreateIssueInput } from './dto/create-issue.input';
import { UpdateIssueInput } from './dto/update-issue.input';
@Injectable()
export class IssuesService {
constructor(private readonly data: PrismaService){}
async create(data: any) {
return await this.data.issues.create({
data,
}) ;
}
async findAll() {
return await this.data.issues.findMany();
}
async findOne(id: number) {
const issueFroDisplay = await this.data.issues.findUnique({
where: { id },
}) ;
if (!issueFroDisplay) {
throw new NotFoundException(`L'issue ayant l'identifiant ${id} n'existe pas`)
}
return issueFroDisplay
}
async update(data: UpdateIssueInput) {
return await this.data.issues.update({
where: {id: data.id},
data
});
}
async remove(id: number) {
return this.findOne(id).then(
async(issue) =>
await this.data.issues.delete({where: {id}}),
);
}
}
|
6a35d3ce0742de76466690dd1b97b93ddd3adc47
|
TypeScript
|
Jxck/jxck.io
|
/labs.jxck.io/react/chat/src/model/store.ts
| 2.9375
| 3
|
import { createStore } from "redux";
// Actions
type LoginAction = { type: "LOGIN"; username: string };
type LogoutAction = { type: "LOGOUT" };
type InputMessageAction = { type: "INPUT_MESSAGE"; message: string };
type onWebSocketOpenAction = { type: "ON_WS_OPEN" };
type onWebSocketMessageAction = { type: "ON_WS_MESSAGE"; message: string };
type appActions = LoginAction | LogoutAction | InputMessageAction | onWebSocketOpenAction | onWebSocketMessageAction;
// Action Creators
export const loginCreator = (username: string): LoginAction => {
return { type: "LOGIN", username };
};
export const logoutCreator = (): LogoutAction => {
return { type: "LOGOUT" };
};
export const inputMessageCreator = (message: string): InputMessageAction => {
return { type: "INPUT_MESSAGE", message };
};
export const onWSOpen = () => {
return { type: "ON_WS_OPEN" };
};
export const onWSMessage = (message: string) => {
return { type: "ON_WS_MESSAGE", message };
};
export interface AppState {
username: string | null;
messages: string[];
wsReady: boolean;
ws: WebSocket;
}
const initialState: AppState = {
username: null,
messages: [],
wsReady: false,
ws: new WebSocket("wss://ws.jxck.io", ["broadcast", "redux-chat"])
};
const reducer = (state: AppState = initialState, action: appActions) => {
console.log(action);
switch (action.type) {
case "LOGIN": {
const { username } = action;
return { ...state, username };
}
case "LOGOUT": {
const username = null;
return { ...state, username };
}
case "INPUT_MESSAGE": {
const { message } = action;
const { ws } = state;
ws.send(JSON.stringify({ message }));
return { ...state };
}
case "ON_WS_OPEN": {
return { ...state, wsReady: true };
}
case "ON_WS_MESSAGE": {
const { message } = action;
return { ...state, messages: [...state.messages, message] };
}
default: {
return state;
}
}
};
export const store = createStore(reducer, (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__());
|
e1eaa2710f233f6b78ba128b3afdb3efd1032861
|
TypeScript
|
agnoam/maxathon_server
|
/src/config/mongo.config.ts
| 2.59375
| 3
|
import mongoose, { Mongoose } from 'mongoose';
import configData from './mongo-data.config.json';
export module DBDriver {
export async function connect(): Promise<boolean> {
try {
const connected = await this.connectDB(configData.uri);
console.log("Connected to mongo database successfully");
return connected;
} catch(e) {
console.log('Error happend while connecting to the DB: ', e.message)
}
}
export async function connectDB(DBconnectionString: string): Promise<Mongoose> {
console.log(`Connecting to DB - uri: ${DBconnectionString}`);
return mongoose.connect(DBconnectionString, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
}
}
// When the node process is terminated (Ctrl+c is pressed) , close the connection to the DB.
process.on('SIGINT', () => {
mongoose.connection.close(() => {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
|
b667c21d539a34d5eb820cf1ea3f5f42b22d8bf7
|
TypeScript
|
dfe-analytical-services/explore-education-statistics
|
/src/explore-education-statistics-common/src/utils/number/formatPretty.ts
| 3.546875
| 4
|
import countDecimalPlaces from '@common/utils/number/countDecimalPlaces';
import clamp from 'lodash/clamp';
export const defaultMaxDecimalPlaces = 2;
/**
* Return a formatted {@param value} in a pretty format
* i.e. 10,000,000.000.
*
* {@param unit} can be used to add a unit to the
* formatted value. We will try and handle different
* units to get a result that looks the best.
*
* {@param decimalPlaces} can be optionally used
* determine the number of decimal places that
* the formatted number should have.
*/
export default function formatPretty(
value: string | number,
unit?: string,
decimalPlaces?: number,
): string {
let numberValue: number;
if (typeof value === 'string') {
numberValue = Number(value);
if (Number.isNaN(numberValue) || value.trim() === '') {
return value;
}
} else {
numberValue = value;
}
let formattedValue: string;
if (typeof decimalPlaces === 'undefined') {
const minDecimalPlaces = clamp(
countDecimalPlaces(value) ?? 0,
0,
defaultMaxDecimalPlaces,
);
formattedValue = numberValue.toLocaleString('en-GB', {
maximumFractionDigits: defaultMaxDecimalPlaces,
minimumFractionDigits: minDecimalPlaces,
});
} else {
formattedValue = numberValue.toLocaleString('en-GB', {
maximumFractionDigits: decimalPlaces,
minimumFractionDigits: decimalPlaces,
});
}
if (unit) {
switch (unit) {
case '£':
if (numberValue >= 0) {
return `£${formattedValue}`;
}
return `-£${formattedValue.substring(1)}`;
case '£m':
if (numberValue >= 0) {
return `£${formattedValue}m`;
}
return `-£${formattedValue.substring(1)}m`;
default:
return `${formattedValue}${unit}`;
}
}
return formattedValue;
}
|
9ce6a29e8213326eb88ae5a38156172d7e2e930e
|
TypeScript
|
arraycto/i2Bank
|
/src/hooks/validateMoney.ts
| 2.890625
| 3
|
export default function (money: string, event: KeyboardEvent) {
const reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
if (event.key==='.' && reg.test(money+'.00')){
money += '.';
}else if (event.key === 'Backspace' && money.length > 0) {
money = money.slice(0, -1);
}else if(reg.test(money+event.key)){
money+= event.key;
}
else{
event.preventDefault();
}
return money;
}
|
9a7b854fb74bbb2fcfc3839f4b9ccfd7a1e34224
|
TypeScript
|
webnicer/clueless
|
/src/players/types.ts
| 2.546875
| 3
|
export type PlayerPiecesType = { [pieceId: string]: boolean };
export type PlayerType = {
id: string;
name: string;
isProtected: boolean;
pieces: PlayerPiecesType;
};
|
d651ccf7640cde3b2f953139843cdb168e26d9e4
|
TypeScript
|
milesj/emojibase
|
/packages/core/src/fromUnicodeToHexcode.ts
| 3.234375
| 3
|
import { SEQUENCE_REMOVAL_PATTERN } from './constants';
import { Hexcode, Unicode } from './types';
/**
* This function will convert a literal emoji Unicode character into a dash separated
* hexadecimal codepoint. Unless `false` is passed as the 2nd argument, zero width
* joiner's and variation selectors are removed.
*
* ```ts
* import { fromUnicodeToHexcode } from 'emojibase';
*
* fromUnicodeToHexcode('👨👩👧👦'); // 1F468-1F469-1F467-1F466
* fromUnicodeToHexcode('👨👩👧👦', false); // 1F468-200D-1F469-200D-1F467-200D-1F466
* ```
*/
export function fromUnicodeToHexcode(unicode: Unicode, strip: boolean = true): Hexcode {
const hexcode: string[] = [];
[...unicode].forEach((codepoint) => {
let hex = codepoint.codePointAt(0)?.toString(16).toUpperCase() ?? '';
while (hex.length < 4) {
hex = `0${hex}`;
}
if (!strip || (strip && !hex.match(SEQUENCE_REMOVAL_PATTERN))) {
hexcode.push(hex);
}
});
return hexcode.join('-');
}
|
52dab39af21996b5e36ce2e460706991292ec052
|
TypeScript
|
ZhcZack/data-structure-and-algorithm-in-javascript
|
/src/data-structure/hash.ts
| 3.625
| 4
|
import { randomNumber } from "../algorithm/util";
interface HashTable {
insert(value: number): void
remove(value: number): void
search(value: number): boolean
}
type Hashable = string | number
export class ZHash implements HashTable {
private tables: Hashable[][]
constructor() {
this.tables = []
for (let i = 0; i < 13; i++) {
this.tables.push([])
}
}
insert(value: Hashable | Hashable[]): void {
if (Array.isArray(value)) {
for (let v of value) {
const index = fakeHash(v)
this.tables[index].push(v)
}
} else {
const index = fakeHash(value)
this.tables[index].push(value)
}
}
remove(value: Hashable): void {
if (!this.search(value)) {
return
}
const index = fakeHash(value)
for (let i = 0; i < this.tables[index].length; i++) {
if (this.tables[index][i] === value) {
this.tables[index].splice(i, 1)
return
}
}
}
search(value: Hashable): boolean {
const index = fakeHash(value)
for (let v of this.tables[index]) {
if (v === value) {
return true
}
}
return false
}
// for debug
display(): Hashable[] {
const result: Hashable[] = []
for (let table of this.tables) {
for (let value of table) {
result.push(value)
}
}
return result
}
}
function fakeHash(hashValue: Hashable): number {
let result = 0
if (typeof hashValue === 'string') {
let finalCode = 0
for (let char of hashValue) {
finalCode += char.charCodeAt(0)
}
result = finalCode % 13
} else if (typeof hashValue === 'number') {
result = result % 13
}
return result
}
|
6eee76c77fd41dc0e0f5460ee6cd023ee0123017
|
TypeScript
|
ShotaroOkada/fileupload_express_api
|
/src/controller/storage/postStorageController.ts
| 2.578125
| 3
|
import { Request, Response, NextFunction } from "express";
import { bucket, db } from "../../firebase";
import fs from 'fs';
// storageに画像をアップロードする
export function postStorageController(req: Request, res: Response, next: NextFunction) {
const files: Express.Multer.File[] = req.files['Files'];
const STORAGE_ROOT = "https://firebasestorage.googleapis.com/v0/b";
const bucketName = bucket.name;
files.forEach(fileInfo => {
console.log(`fileInfo${JSON.stringify(fileInfo)}`)
const uploadFilePath = `files/${fileInfo.originalname}`
console.log(`uploadFilePath:${uploadFilePath}`)
bucket.upload(fileInfo.path, { destination: uploadFilePath, contentType: fileInfo.mimetype }, error => {
if (error) {
console.log(`failed storage post ${fileInfo.originalname}`);
console.log(error.message);
return res.sendStatus(404);
} else {
console.log(`success storage post ${fileInfo.originalname}`);
// storageに画像をアップロードできた場合は、そのURLをrealtime databaseに保存する
const dlPath = encodeURIComponent(uploadFilePath);
const dlURL = `${STORAGE_ROOT}/${bucketName}/o/${dlPath}?alt=media`;
db.ref('files').push(dlURL, error => {
if (error) {
console.log(`failed database post ${uploadFilePath}`);
return res.sendStatus(404);
} else {
console.log(`success database post ${uploadFilePath}`);
// 一時的にサーバにおいたファイルを削除
fs.unlinkSync(fileInfo.path)
}
}
)
}
})
})
setTimeout(() => {
console.log('send 200')
return res.sendStatus(200);
}, 2000)
// return res.sendStatus(200);
}
|
279662798a7880d4fb8b0cd9631ab0abbe512acd
|
TypeScript
|
dappcenter/decrybe
|
/src/store/DisputeCreateStore.ts
| 2.640625
| 3
|
import { observable, action, computed} from "mobx"
import {RootStore} from './RootStore'
class DisputeCreateStore {
@observable title: String = "";
@observable task: String = ""
@observable briefDescription: String = ""
@observable description: String = ""
constructor(public root: RootStore) {
this.root = root
}
@action("set dispute title")
setTitle (title: String) {
this.title = title.replace(/(\s\s)/g, ' ')
}
@computed get getTitle() {
return this.title
}
@action("set task")
setTask (task: String) {
this.task = task
}
@computed get getTask() {
return this.task
}
@action("set task brief description")
setBriefDescription (briefDescription: String) {
this.briefDescription = briefDescription.replace(/(\s\s)/g, ' ');
}
@computed get getBriefDescription() {
return this.briefDescription
}
@action("set task description")
setDescription (description: String) {
this.description = description;
}
@computed get getDescription() {
return this.description
}
@action("Clean task creator")
clean () {
this.setTitle("")
this.setBriefDescription("");
this.setDescription('')
this.setTask("")
}
}
export { DisputeCreateStore }
|
c99de1c5259b37b93f3eeb6a4b1071089704fecd
|
TypeScript
|
Snosky/mame-hi-extractor
|
/src/Extractor/shinobi.ts
| 2.6875
| 3
|
import AbstractExtractor from "../AbstractExtractor";
import Extractor from "../Decorator/Extractor";
@Extractor({
name: 'shinobi'
})
export default class Shinobi extends AbstractExtractor {
protected charset = {
0x22: '.',
0x23: '\'',
0x25: '/',
0x26: '(',
0x27: ')',
0x28: '-',
0x29: '&man;',
0x2A: '&woman;',
0x2B: '&mid-dot;',
0x2E: '=',
};
extract(): this {
for (let i = 0; i < 20; i++) {
this.scores.default.push({
rank: i + 1,
score: parseInt(this.hi!.slice(i * 8, 4).readIntBE().toString(16)),
name: this.hi!.slice(i * 8 + 5, 3).toString(this.charset)
});
}
return this;
}
}
|
51d609fcbf963ebc7ad82eb59f147fea6e0e489f
|
TypeScript
|
aichouramine/survey-generator-angular
|
/src/app/question/question-base.ts
| 2.6875
| 3
|
export class QuestionBase<T> {
value: T;
key: string;
label: string;
required: boolean;
order: number;
activePage: number;
activePageOnClick: number;
controlType: string;
showIf: any;
longValuesLabels?: boolean;
header?: string;
maxLength: number;
content?: string;
constructor(options: {
value?: T,
key?: string,
label?: string,
required?: boolean,
order?: number,
activePage?: number,
activePageOnClick?: number;
controlType?: string,
showIf?: any,
header?: string,
longValuesLabels?: boolean,
maxLength?: number,
content?: string
} = {}) {
this.value = options.value;
this.key = options.key || '';
this.label = options.label || '';
if (options.required) {
this.required = true;
}
if (options.maxLength) {
this.maxLength = options.maxLength;
}
this.order = options.order === undefined ? 1 : options.order;
this.controlType = options.controlType || '';
this.showIf = options.showIf || false;
this.activePage = options.activePage;
this.activePageOnClick = options.activePageOnClick || null;
this.content = options.content || null;
this.header = options.header || null;
this.longValuesLabels = options.longValuesLabels || false;
}
isVisible(form: any) {
if (this.showIf && this.showIf.key && this.showIf.eq) {
const flag = this.showIf.eq.includes(parseInt(form.get(this.showIf.key).value));
// clear when form input is hidden
if (!flag) {
form.get(this.key).value = '';
}
return flag;
} else {
return true;
}
}
}
|
29ce39de87c9b6b8d71d5c443b717faaa95b9572
|
TypeScript
|
rodwyn/es6-store
|
/app/scripts/components/Window.ts
| 3.015625
| 3
|
interface Window {
isMobile: () => boolean;
redirect: (url: string) => void;
onResize: (callback: () => void, time: number) => void;
}
window.isMobile = () => 768 > Math.max(
0 || document.documentElement.clientWidth, window.innerWidth
);
window.redirect = (url: string) => {
window.location.href = url;
};
window.onResize = (callback: () => void, time: number) => {
let timeout = 0;
window.addEventListener('resize', event => {
clearTimeout(timeout);
timeout = setTimeout(callback, time, event);
});
};
|
87a00e3262e829499356db30379738a4b712fd9c
|
TypeScript
|
nickcaplan/cards-app
|
/src/main/webapp/app/shared/model/card.model.ts
| 2.640625
| 3
|
import { Moment } from 'moment';
export interface ICard {
id?: number;
cardNumber?: number;
bankName?: string;
expiryDate?: Moment;
}
export class Card implements ICard {
constructor(public id?: number, public cardNumber?: number, public bankName?: string, public expiryDate?: Moment) {}
}
|
00d91ec8b686ad8d40b45028b109a1f41bdde778
|
TypeScript
|
vonsky104/react-test-interview
|
/src/store/actions.ts
| 2.671875
| 3
|
import {
FETCH_BANDS,
RAISE_ERROR,
SortedByBandType,
REMOVE_ERRORS,
PREPARE_ACCORDIONS_STATE,
OPEN_ACCORDION, CLOSE_ACCORDION, OPEN_ALL_ACCORDIONS, CLOSE_ALL_ACCORDIONS
} from './action_types';
import { Dispatch } from "redux";
import { axios } from "../config/axios-control";
import { generateIdFromBandAndAlbum } from "../utils/helpers";
import { Album, Band, FetchedSong } from "../utils/interfaces";
export function fetchData() {
return (dispatch: Dispatch<any>) => {
axios
.get('data.json')
.then(response => {
const songs = response.data;
const sortedByBand = songs.reduce((acc: Array<SortedByBandType>, fetchedSong: FetchedSong) => {
const band = fetchedSong.band;
const album = fetchedSong.album;
const song = fetchedSong.song;
const existingBandIndex = acc.indexOf(acc.find((e: Band | undefined) => e!.name === band));
const albumId = generateIdFromBandAndAlbum(band, album);
if (existingBandIndex < 0) {
const bandToPush = {
name: band,
albums: [{
id: albumId,
name: album,
songs: [song]
}]
};
acc.push(bandToPush);
return acc;
}
const existingBand = acc[existingBandIndex];
const existingAlbums = existingBand!.albums;
const existingAlbumIndex = existingAlbums.indexOf(existingAlbums.find((e: Album | undefined) => e!.name === album));
if (existingAlbumIndex < 0) {
const objectToInsert = {
id: albumId,
name: album,
songs: [song]
};
acc[existingBandIndex]!.albums.push(objectToInsert);
return acc;
}
const existingAlbum = existingAlbums[existingAlbumIndex];
existingBand!.albums[existingAlbumIndex] = {
id: existingAlbum!.id,
name: existingAlbum!.name,
songs: [...existingAlbum!.songs, song]
};
return acc;
}, []);
dispatch({ type: REMOVE_ERRORS });
dispatch({
type: FETCH_BANDS,
payload: sortedByBand,
});
dispatch({
type: PREPARE_ACCORDIONS_STATE,
payload: prepareAccordionsState(sortedByBand)
});
})
.catch(e => {
console.log(e);
dispatch({
type: RAISE_ERROR,
payload: {
message: e,
}
});
});
}
}
export function openAccordion(id: string) {
return (dispatch: Dispatch<any>) => dispatch({ type: OPEN_ACCORDION, payload: id });
}
export function closeAccordion(id: string) {
return (dispatch: Dispatch<any>) => dispatch({ type: CLOSE_ACCORDION, payload: id });
}
export function openAllAccordions() {
return (dispatch: Dispatch<any>) => dispatch({ type: OPEN_ALL_ACCORDIONS });
}
export function closeAllAccordions() {
return (dispatch: Dispatch<any>) => dispatch({ type: CLOSE_ALL_ACCORDIONS });
}
function prepareAccordionsState(bands: Band[]) {
return bands.reduce((acc: object, band: Band) => {
const { albums } = band;
if (!albums) {
return acc;
}
albums.forEach((album: Album | undefined) => {
acc = {
...acc,
[album!.id]: false,
}
});
return acc;
}, {});
}
|
2afb56964e14ffad747f69e3f345a5421d8cf2c3
|
TypeScript
|
mxjp/rvx
|
/test/disposable.ts
| 2.9375
| 3
|
import test from "ava";
import { Disposable } from "../src";
test("create empty", t => {
const disposable = new Disposable();
disposable.dispose();
t.pass();
});
test("create with logic", t => {
const disposable = new Disposable(() => t.pass());
disposable.dispose();
});
test("add logic", t => {
const disposable = new Disposable();
disposable.add(() => t.pass());
disposable.dispose();
});
test("add void logic", t => {
const disposable = new Disposable();
disposable.add();
disposable.dispose();
t.pass();
});
test("delete logic", t => {
const disposable = new Disposable();
const logic = () => t.fail();
disposable.add(logic);
disposable.delete(logic);
disposable.dispose();
t.pass();
});
test("delete from empty", t => {
const disposable = new Disposable();
disposable.delete(() => { });
t.pass();
});
test("reuse", t => {
let state = 0;
const disposable = new Disposable(() => t.is(state, 1));
state = 1;
disposable.dispose();
disposable.add(() => {
t.is(state, 1);
return Promise.resolve("foo");
});
state = 2;
disposable.dispose();
});
|
1c58856ca8916c636d85a23042589248a00864b2
|
TypeScript
|
sniller27/ng6-proj
|
/src/app/app.component.ts
| 2.578125
| 3
|
import { Component } from '@angular/core';
import {NgForm} from '@angular/forms';
//httpclient module for making requests
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
////create instances of service in order to use it (this is done through DI)?
constructor(private data: DataService) { }
title = 'ng6-proj';
public open(event, item) {
// alert('Open ' + item);
//
// this.httpClient.post(`https://my-json-server.typicode.com/techsithgit/json-faker-directory/profiles/`,
// {
// name:'mark',
// age: 41
// })
// .subscribe(
// (data:any) => {
// console.log(data);
// }
// )
//
// this.data.sendPost().subscribe(
// //arrow function : without parameters? or observable? ... binds users object to received data
// // data => this.users$ = data
// //this doesn't work .... ???
// //console.log(data);
// console.log('wtf');
// );
}
onSubmit(userForm: NgForm) {
console.log(userForm.value);
console.log('Name:' + userForm.controls['first'].value);
console.log('Name:' + userForm.controls['last'].value);
console.log('Form Valid:' + userForm.valid);
console.log('Form Submitted:' + userForm.submitted);
console.log('hello');
}
}
|
ed140fe0b1d964f24497ff116fd6938e06c29d72
|
TypeScript
|
andersfischernielsen/rosdistro-dependency-analysis
|
/fetch.ts
| 2.671875
| 3
|
import monk from 'monk';
import fs from 'fs';
import { safeLoad, safeDump } from 'js-yaml';
import { Issue, GHComment } from './Issue';
type Fraction = {
owner: string;
repository: string;
bugs: number;
dependencyIssues: number;
concurrencyIssues: number;
memoryIssues: number;
dependencyFraction: number;
concurrencyFraction: number;
memoryFraction: number;
};
type Results = {
fractions: Fraction;
dependencyPositives: Issue[];
concurrencyPositives: Issue[];
memoryPositives: Issue[];
dependencyNegatives: Issue[];
allBugs: number;
allIssues: number;
};
const url = '127.0.0.1:27017/github';
const db = monk(url);
const toLower = (toLowerCase: string) => toLowerCase.toLowerCase();
async function getIssuesForRepository(
owner: string,
repository: string,
): Promise<Results> {
const getCommentForIssue = async (i: Issue) => {
const allComments: GHComment[] = await db.get('issue_comments').find({
$and: [{ owner: owner }, { repo: repository }, { issue_id: i.number }],
});
const comments = allComments.filter((i) => Date.parse(i.created_at) < date);
i.data_comments = comments;
return i;
};
const matchWithRegex = (issues: Issue[], regex: string[]) => {
const joined = regex.join('|');
return issues.filter((i) => {
return (
(i.body != undefined && toLower(i.body).match(joined) != null) ||
(i.title != undefined && toLower(i.title).match(joined) != null) ||
i.data_comments.some(
(c) => c.body != undefined && toLower(c.body).match(joined) != null,
)
);
});
};
const invertMatchWithRegex = (issues: Issue[], regex: string) => {
return issues.filter((i) => {
return (
(i.body != undefined && toLower(i.body).match(regex) == null) ||
(i.title != undefined && toLower(i.title).match(regex) == null) ||
i.data_comments.some(
(c) => c.body != undefined && toLower(c.body).match(regex) == null,
)
);
});
};
const fraction = (positives: Issue[], all: Issue[]) => {
const fraction = positives.length / all.length;
return isNaN(fraction) || !isFinite(fraction) ? 0 : fraction;
};
const date = 1561161601000; //22/06/2019 00:00:01
const allIssues: Issue[] = await db.get('issues').find({
$and: [{ owner: owner }, { repo: repository }],
});
const issuesWithBugLabels = allIssues.filter(
(i) =>
Date.parse(i.created_at) < date &&
i.labels.length > 0 &&
i.labels.some(
(l) =>
toLower(l.name).match('bug') != undefined ||
toLower(l.name).match('critical') != undefined,
),
);
const issuesWithComments = await Promise.all(
issuesWithBugLabels.map((i) => getCommentForIssue(i)),
);
const dependencyIssues = matchWithRegex(issuesWithComments, ['depend']);
const concurrencyIssues = matchWithRegex(issuesWithComments, [
'concurren',
'parallel',
'deadlock',
'race',
'lock',
]);
const memoryIssues = matchWithRegex(issuesWithComments, [
'leak',
'null dereference',
'buffer',
'overflow',
]);
const withoutDependencyIssues = invertMatchWithRegex(
issuesWithComments,
'depend',
);
console.info(`Parsed /${owner}/${repository}/...`);
const dependencyFraction = fraction(dependencyIssues, issuesWithComments);
const concurrencyFraction = fraction(concurrencyIssues, issuesWithComments);
const memoryFraction = fraction(memoryIssues, issuesWithComments);
return {
fractions: {
owner: owner,
repository: repository,
bugs: issuesWithComments.length,
dependencyIssues: dependencyIssues.length,
concurrencyIssues: concurrencyIssues.length,
memoryIssues: memoryIssues.length,
dependencyFraction: dependencyFraction,
concurrencyFraction: concurrencyFraction,
memoryFraction: memoryFraction,
},
dependencyPositives: dependencyIssues,
dependencyNegatives: withoutDependencyIssues,
concurrencyPositives: concurrencyIssues,
memoryPositives: memoryIssues,
allBugs: issuesWithComments.length,
allIssues: allIssues.length,
};
}
const fetchForAll = async (path: string) => {
const content = fs.readFileSync(path);
const loaded = safeLoad(content.toString());
const repositories = Object.entries(loaded.repositories)
.map((repo: any) => {
const content = repo[1];
if (!content.source) return undefined;
let url = content.source.url as string;
if (url.match('bitbucket')) return undefined;
const initial = url.split(/(https:\/\/github.com\/)/)[2];
const split = initial ? initial.split('/') : undefined;
if (!split) return undefined;
const nameWithoutGit = split[1].replace('.git', '');
const owner = split[0];
return { owner: owner, name: nameWithoutGit };
})
.filter((r) => r !== undefined);
return await Promise.all(
repositories.map((r) => getIssuesForRepository(r.owner, r.name)),
);
};
const fetchForAllTopStarred = async (path: string) => {
const content = fs.readFileSync(path);
const loaded = safeLoad(content.toString());
const repositories = Object.entries(loaded.repositories)
.map((repo: any) => {
const name: string = repo[0];
const owner: string = repo[1].organisation;
return { owner: owner, name: name };
})
.filter((r) => r !== undefined);
return await Promise.all(
repositories.map((r) => getIssuesForRepository(r.owner, r.name)),
);
};
const shouldRunOnTopStarred = false;
(shouldRunOnTopStarred
? fetchForAllTopStarred('data/18-09-2019-top-starred.yaml')
: fetchForAll('data/22-06-2019-distribution.yaml')
).then((rs) => {
const mode = shouldRunOnTopStarred ? '_top_starred' : '';
const filename = `fractions${mode}.yaml`;
const path = 'results';
const fractions = rs.reduce((acc, r) => acc.concat(r.fractions), []);
const dependPositives = rs.reduce(
(acc, r) => acc.concat(r.dependencyPositives),
[],
);
const concurrencyPositives = rs.reduce(
(acc, r) => acc.concat(r.concurrencyPositives),
[],
);
const memoryPositives = rs.reduce(
(acc, r) => acc.concat(r.memoryPositives),
[],
);
const dependNegatives = rs.reduce(
(acc, r) => acc.concat(r.dependencyNegatives),
[],
);
try {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
fs.writeFileSync(`${path}/${filename}`, safeDump(fractions));
if (!shouldRunOnTopStarred) {
fs.writeFileSync(
`${path}/dependPositives${mode}.yaml`,
safeDump(dependPositives),
);
fs.writeFileSync(
`${path}/concurrencyPositives${mode}.yaml`,
safeDump(concurrencyPositives),
);
fs.writeFileSync(
`${path}/memoryPositives${mode}.yaml`,
safeDump(memoryPositives),
);
fs.writeFileSync(
`${path}/dependencyNegatives${mode}.yaml`,
safeDump(dependNegatives),
);
}
console.log(`Results have been written to ${path}/`);
process.exit(0);
} catch (error) {
console.error(error);
}
});
|
a5a403992f2ce0edece01db35730496759089214
|
TypeScript
|
Lhhpw0204/teris-game
|
/src/core/Teris.ts
| 2.84375
| 3
|
import { Shape, Point } from "./types"
import { getRandom } from "./viewer/util"
import { SquareGroup } from "./SquareGroup"
export class TShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: -1, y: 0}, { x: 0, y: 0}, { x: 1, y: 0}, { x: 0, y: -1}], _centerPoint, _color);
}
}
export class LShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: -2, y: 0}, { x: -1, y: 0}, { x: 0, y: 0}, { x: 0, y: -1}], _centerPoint, _color);
}
}
export class LMirrorShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: 2, y: 0}, { x: 1, y: 0}, { x: 0, y: 0}, { x: 0, y: -1}], _centerPoint, _color);
}
}
export class SShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: 0, y: 0}, { x: 1, y: 0}, { x: 0, y: 1}, { x: -1, y: 1}], _centerPoint, _color);
}
rotate() {
super.rotate();
this.isClock = !this.isClock;
}
}
export class SMirrorShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: 0, y: 0}, { x: -1, y: 0}, { x: 0, y: 1}, { x: 1, y: 1}], _centerPoint, _color);
}
rotate() {
super.rotate();
this.isClock = !this.isClock;
}
}
export class SSquareShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: 0, y: 0}, { x: 1, y: 0}, { x: 0, y: 1}, { x: 1, y: 1}], _centerPoint, _color);
}
afterRotateShape() {
return this.shape;
}
}
export class LineShape extends SquareGroup{
constructor(_centerPoint: Point, _color: string){
super([{ x: -1, y: 0}, { x: 0, y: 0}, { x: 1, y: 0}, { x: 2, y: 0}], _centerPoint, _color);
}
rotate() {
super.rotate();
this.isClock = !this.isClock;
}
}
export const shapes = [
TShape, LShape, LMirrorShape, LineShape, SShape, SMirrorShape, SSquareShape
];
export const colors = [
"red",
"#fff",
"green",
"#2f7ce8"
]
/*
随机产生方块
*/
export function createTeris(centerPoint: Point): SquareGroup {
let index = getRandom(0, shapes.length);
const shape = shapes[index];
index = getRandom(0, colors.length);
const color = colors[index];
return new shape(centerPoint, color);
}
|
a472fa21fee48352d59cff42515961b7edd43cda
|
TypeScript
|
MikaStark/json-api
|
/projects/json-api/src/lib/interfaces/json-api-links.ts
| 3.296875
| 3
|
import { JsonApiMeta } from './json-api-meta';
/**
* ### Links
*
* Where specified, a `links` member can be used to represent links.
* The value of this member **MUST** be an object (a “links object”).
*
* Within this object, a link **MUST** be represented as either:
* * a string containing the link’s URI.
* * an object (“link object”) which can contain the following members:
* * `href`: a string containing the link’s URI.
* * `meta`: a meta object containing non-standard meta-information about the link.
* * Any link-specific target attributes described below.
*
* Except for the `profile` key in the top-level links object and the `type` key in an
* [error object](https://jsonapi.org/format/1.1/#error-objects)’s links object, each
* key present in a links object **MUST** have a single link as its value. The
* aforementioned `profile` and `type` keys, if present, **MUST** hold an array of links.
*
* @example
* ```json
* "links": {
* "self": "http://example.com/articles/1",
* "related": {
* "href": "http://example.com/articles/1/comments",
* "meta": {
* "count": 10
* }
* }
* }
* ```
* @see https://jsonapi.org/format/1.1/#document-links
*/
export interface JsonApiLinks {
[name: string]:
| string
| {
href: string;
meta: JsonApiMeta;
};
}
|
296bce57102ef02b3a759ddabe9c64d89c2f25a0
|
TypeScript
|
levi9-summer-workshop/Team-1
|
/online-survey-creator-client/src/app/question/question.model.ts
| 2.703125
| 3
|
import { Answer } from "../answer/answer.model";
export class Question {
public id: number;
public text: string;
public surveyAnswers: Answer[];
public questionType: string;
constructor (id: number, text?: string, surveyAnswers?: Answer[], questionType?: string) {
this.text = text;
this.surveyAnswers = surveyAnswers;
this.questionType = questionType;
}
}
|
1f53ae481a33b7e3a12f2b45f01a101f8c2852c4
|
TypeScript
|
jattapol456/madoobaan-backend
|
/src/types/index.d.ts
| 2.59375
| 3
|
import * as admin from 'firebase-admin'
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>
}[Keys]
type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, undefined>>
}[Keys]
type FirebaseUserRequest = Request & { user?: admin.auth.DecodedIdToken }
export interface IItem {
key: number | string
value: string
}
export interface IEditable {
editable: boolean
}
|
a1363ca252276b3e2228f857ee0958ddfc7a0193
|
TypeScript
|
angularcity/hd-handson
|
/src/app/product/store/product.reducer.ts
| 3.015625
| 3
|
import { Product } from "./product.model";
import { ProductActions, ProductActionTypes } from "./product.action";
export interface ProductState {
products: Product[];
homeDepotProducts: Product[];
availableProductIDs: {};
currentProductID: number | string;
currentAvailableProduct: Product;
}
const INITIAL_STATE: ProductState = {
products: [],
homeDepotProducts: [],
availableProductIDs: [],
currentProductID: null,
currentAvailableProduct: null
};
export function reducer(
state = INITIAL_STATE,
action: ProductActions
): ProductState {
switch (action.type) {
case ProductActionTypes.GetAllProducts:
// console.log("caught get all products in reducer");
return {
...state
};
case ProductActionTypes.GetAllProductsSuccess:
console.log("get me all products..", action.payload);
return {
...state,
products: action.payload
};
case ProductActionTypes.GetProductByIdSuccess:
// console.log("individual product success..", action.payload);
return {
...state,
homeDepotProducts: [...state.homeDepotProducts, action.payload],
availableProductIDs: {
...state.availableProductIDs,
[action.payload.id]: action.payload.id
},
currentProductID: action.payload.id
};
case ProductActionTypes.GetAvailableProductFromStore:
return {
...state,
currentAvailableProduct: state.homeDepotProducts.find(
prod => prod.id === action.payload
)
};
default:
return state;
}
}
|
210ce833b11fa268d95da71040c1ac5bbdbb9e4e
|
TypeScript
|
sciety/api-prototype
|
/update/src/rdf.ts
| 2.625
| 3
|
import { concatAll } from 'fp-ts/Monoid'
import * as Ord from 'fp-ts/Ord'
import { DataFactory } from 'n3'
import { BaseQuad, BlankNode, Literal, NamedNode, Quad, Term, Variable } from 'rdf-js'
import { rdf, xsd } from './namespace'
import * as S from './string'
export const { namedNode, literal, quad } = DataFactory
export type {
Term, NamedNode, BlankNode, Literal, Variable, DefaultGraph, BaseQuad, Quad
} from 'rdf-js'
export const date = (value: Date) => literal(value.toISOString().substring(0, 10), xsd.date)
export const url = (value: URL) => literal(value.toString(), xsd.anyURI)
const getOrd = (type: Term['termType']): Ord.Ord<any> => {
switch (type) {
case 'NamedNode':
return ordNamedNode
case 'BlankNode':
return ordBlankNode
case 'Literal':
return ordLiteral
case 'Variable':
return ordVariable
case 'DefaultGraph':
return Ord.fromCompare(() => 0)
case 'Quad':
return ordQuad
}
}
export const ord: Ord.Ord<Term> = Ord.fromCompare((x, y) => {
if (x.termType === y.termType) {
return getOrd(x.termType).compare(x, y)
}
return 0
})
const ordBlankNode = Ord.contramap((term: BlankNode) => term.value)(S.Ord)
const ordLiteral = Ord.contramap((term: Literal) => term.value)(S.Ord)
const ordNamedNode = Ord.fromCompare<NamedNode>((x, y) => {
if (x.equals(rdf.type)) {
return -1
}
if (y.equals(rdf.type)) {
return 1
}
return S.Ord.compare(x.value, y.value)
})
const ordVariable = Ord.contramap((term: Variable) => term.value)(S.Ord)
const ordQuad: Ord.Ord<BaseQuad> = concatAll(Ord.getMonoid<BaseQuad>())([
Ord.contramap((term: BaseQuad) => term.graph)(ord),
Ord.contramap((term: BaseQuad) => term.subject)(ord),
Ord.contramap((term: BaseQuad) => term.predicate)(ord),
Ord.contramap((term: BaseQuad) => term.object)(ord),
])
export const toTriple = <A extends BaseQuad>({
subject,
predicate,
object
}: A): A => DataFactory.triple<A>(subject, predicate, object) as any
|
bb345130a698dbbe5f2f50976eeab018210c5bce
|
TypeScript
|
robinsondotnet/vuex-plugin-firemodel
|
/dist/cjs/auth/api/auth.d.ts
| 2.875
| 3
|
/**
* These functions are really just wrappers around the available actions
* which Firemodel provides but are type-safe and often are a more easily
* used means to achieve **Firebase** _auth_ functions
*/
import { ActionCodeSettings, UserCredential, IdTokenResult, AuthCredential } from "@firebase/auth-types";
import { IAuthProfile } from "../../types";
import { IModelConstructor } from "firemodel";
/**
* Log into the Firebase AUTH sytem using email/password. If successful it returns
* a Firebase "user credential".
*/
export declare function signInWithEmailAndPassword(email: string, password: string): Promise<UserCredential>;
/**
* Allows a frontend app to create a new user for email and password
* authentication. The account will initially be set to _un-verified_ but
* the email used will be sent a link to make the account verified.
*/
export declare function createUserWithEmailAndPassword(email: string, password: string): Promise<UserCredential>;
/**
* Signs out the current user from Firebase; it will also
* optionally send a **reset** to the `Model` which stores the
* user profile of the user.
*/
export declare function signOut(payload: {
uid?: string;
email?: string;
/** model constructor or db path */
model?: IModelConstructor | string;
}): Promise<any>;
export declare function getIdToken(forceRefresh?: boolean): Promise<IdTokenResult>;
/**
* Sends a password reset email to the given email address.
* To complete the password reset, dispatch `confirmPasswordReset` with
* the code supplied in the email sent to the user, along with the new password
* specified by the user.
*/
export declare function sendPasswordResetEmail(email: string, actionCodeSettings?: ActionCodeSettings): Promise<void>;
/**
* Completes the password reset process, given a _confirmation code_
* and new _password_.
*/
export declare function confirmPasswordReset(code: string, newPassword: string): Promise<void>;
/**
* Checks a password reset code sent to the user by email or other
* out-of-band mechanism. Returns the user's email address if valid.
*/
export declare function verifyPasswordResetCode(code: string): Promise<string>;
/**
* Updates the user's email address. An email will be sent to the original email address
* that allows owner of that email address to revoke the email address change.
*/
export declare function updateEmail(newEmail: string): Promise<void>;
/**
* Updates the user's password. In order to allow this operation a user
* must have logged in recently. If this requirement isn't met a
* `auth/requires-recent-login` error will be thrown. You will then have to
* call the `reauthenticateWithCredential` to resolve this.
*/
export declare function updatePassword(password: string): Promise<void>;
/**
* Update a user's basic profile information with name and/or
* photo URL.
*/
export declare function updateProfile(profile: IAuthProfile): Promise<any>;
/**
* Sends a verification email to the currently logged in user
*/
export declare function sendEmailVerification(): Promise<void>;
export declare function reauthenticateWithCredential(credential: AuthCredential): Promise<void>;
export declare function linkWithCredential(credential: AuthCredential): Promise<any>;
|
8355e3afbeb2636bc1862945e2149ad9691148a1
|
TypeScript
|
poppa/bitsy-ts
|
/src/lib/token.ts
| 3.53125
| 4
|
export const enum Type {
Symbol,
Operator,
Equal,
Number,
LeftParen,
RightParen,
Keyword,
Comment,
}
export const typeMap = [
'Symbol',
'Operator',
'Equal',
'Number',
'LeftParen',
'RightParen',
'Keyword',
'Comment',
]
export interface Token {
readonly line: number
readonly column: number
readonly position: number
readonly value: string
readonly type: Type
}
export function charToType(c: string): Type {
switch (c) {
case '-': // fall-through
case '+': // fall-through
case '/': // fall-through
case '*': // fall-through
case '%':
return Type.Operator
case '=':
return Type.Equal
case '(':
return Type.LeftParen
case ')':
return Type.RightParen
default:
throw new Error(`Unknown character`)
}
}
|