commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
---|---|---|---|---|---|---|---|---|---|---|
de39f05e56364a34f00eb4ead9fe1bdbf0163e08 | src/components/type/type.mapper.ts | src/components/type/type.mapper.ts | import { Type } from './type.model';
import { ItemTemplate } from '@core/game_master/gameMaster';
import { Util } from '@util';
export class TypeMapper {
public static Map(rawType: ItemTemplate, typeIds: Map<number, string>): Type {
let type: Type = new Type();
type.id = rawType.templateId
type.name = Util.SnakeCase2HumanReadable(rawType.templateId.replace('POKEMON_TYPE_', ''));
type.damage = [];
for (let i = 0; i < rawType.typeEffective.attackScalar.length; i++) {
type.damage.push({
id: typeIds.get(i),
attackScalar: rawType.typeEffective.attackScalar[i]
});
}
return type
}
}
| import { Type } from './type.model';
import { ItemTemplate } from '@core/game_master/gameMaster';
import { Util } from '@util';
import APP_SETTINGS from '@settings/app';
export class TypeMapper {
public static Map(rawType: ItemTemplate): Type {
let type: Type = new Type();
type.id = rawType.templateId;
type.name = Util.SnakeCase2HumanReadable(rawType.templateId.replace('POKEMON_TYPE_', ''));
type.damage = APP_SETTINGS.POKEMON_TYPES.map((pokemonType, index) => { return {
id: pokemonType.id,
attackScalar: rawType.typeEffective.attackScalar[pokemonType.attackScalarIndex]
}});
return type;
}
}
| Add pokemon types - Refactoring | Add pokemon types - Refactoring
| TypeScript | mit | BrunnerLivio/pokemongo-data-normalizer,BrunnerLivio/pokemongo-json-pokedex,BrunnerLivio/pokemongo-json-pokedex,vfcp/pokemongo-json-pokedex,BrunnerLivio/pokemongo-data-normalizer,vfcp/pokemongo-json-pokedex | ---
+++
@@ -1,22 +1,20 @@
import { Type } from './type.model';
import { ItemTemplate } from '@core/game_master/gameMaster';
import { Util } from '@util';
+import APP_SETTINGS from '@settings/app';
export class TypeMapper {
- public static Map(rawType: ItemTemplate, typeIds: Map<number, string>): Type {
+ public static Map(rawType: ItemTemplate): Type {
let type: Type = new Type();
- type.id = rawType.templateId
+ type.id = rawType.templateId;
type.name = Util.SnakeCase2HumanReadable(rawType.templateId.replace('POKEMON_TYPE_', ''));
- type.damage = [];
- for (let i = 0; i < rawType.typeEffective.attackScalar.length; i++) {
- type.damage.push({
- id: typeIds.get(i),
- attackScalar: rawType.typeEffective.attackScalar[i]
- });
- }
+ type.damage = APP_SETTINGS.POKEMON_TYPES.map((pokemonType, index) => { return {
+ id: pokemonType.id,
+ attackScalar: rawType.typeEffective.attackScalar[pokemonType.attackScalarIndex]
+ }});
- return type
+ return type;
}
} |
83f5cbe1e56d0c1fc8edb6fa2350c9eac26881aa | types/detox/test/detox-jest-setup-tests.ts | types/detox/test/detox-jest-setup-tests.ts | declare var beforeAll: (callback: () => void) => void;
declare var beforeEach: (callback: () => void) => void;
declare var afterAll: (callback: () => void) => void;
import * as detox from "detox";
import * as adapter from "detox/runners/jest/adapter";
// Normally the Detox configuration from the project's package.json like so:
// const config = require("./package.json").detox;
declare const config: any;
declare const jasmine: any;
jasmine.getEnv().addReporter(adapter);
beforeAll(async () => {
await detox.init(config);
const initOptions: Detox.DetoxInitOptions = {
initGlobals: false,
launchApp: false,
};
await detox.init(config, initOptions);
});
beforeEach(async () => {
await adapter.beforeEach();
});
afterAll(async () => {
await adapter.afterAll();
await detox.cleanup();
});
| declare var beforeAll: (callback: () => void) => void;
declare var beforeEach: (callback: () => void) => void;
declare var afterAll: (callback: () => void) => void;
import detox = require("detox");
import adapter = require("detox/runners/jest/adapter");
// Normally the Detox configuration from the project's package.json like so:
// const config = require("./package.json").detox;
declare const config: any;
declare const jasmine: any;
jasmine.getEnv().addReporter(adapter);
beforeAll(async () => {
await detox.init(config);
const initOptions: Detox.DetoxInitOptions = {
initGlobals: false,
launchApp: false,
};
await detox.init(config, initOptions);
});
beforeEach(async () => {
await adapter.beforeEach();
});
afterAll(async () => {
await adapter.afterAll();
await detox.cleanup();
});
| Use `import = require` in jest setup tests | [detox] Use `import = require` in jest setup tests | TypeScript | mit | georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped | ---
+++
@@ -2,8 +2,8 @@
declare var beforeEach: (callback: () => void) => void;
declare var afterAll: (callback: () => void) => void;
-import * as detox from "detox";
-import * as adapter from "detox/runners/jest/adapter";
+import detox = require("detox");
+import adapter = require("detox/runners/jest/adapter");
// Normally the Detox configuration from the project's package.json like so:
// const config = require("./package.json").detox; |
8650a4129cb24a44c1f221bd877c6e375b52add0 | src/Unosquare.Tubular2.Web/e2e/pageSizeSelector-test.e2e-spec.ts | src/Unosquare.Tubular2.Web/e2e/pageSizeSelector-test.e2e-spec.ts | ///<reference path="../node_modules/@types/jasmine/index.d.ts"/>
import { browser, element, by } from '../node_modules/protractor/built';
describe('page size selector', () =>{
let dataRowsCollection,
firstDataRow,
lastDataRow,
firstPageBtn,
nextPageBtn,
pageSizeSelector,
gridPager
beforeAll(()=>{
browser.get('/');
gridPager = element(by.tagName('grid-pager')).$('ngb-pagination').$('nav ul');
pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select');
dataRowsCollection = element(by.tagName('tbody')).$$('tr');
firstDataRow = element(by.tagName('tbody')).$$('tr').first();
lastDataRow = element(by.tagName('tbody')).$$('tr').last();
firstPageBtn = gridPager.$$('li').first();
nextPageBtn = gridPager.$$('li');
});
it('should filter up to 10 data rows per page when selecting a page size of "10"', () => {
pageSizeSelector.$('[value="10"]').click();
expect(firstDataRow.$$('td').get(1).getText()).toMatch('1');
expect(lastDataRow.$$('td').get(1).getText()).toMatch('10');
expect(dataRowsCollection.count()).toBe(10);
});
it('should filter up to 20 data rows per page when selecting a page size of "20"', () => {
pageSizeSelector.$('[value="20"]').click();
nextPageBtn.get(5).$('a').click();
expect(firstDataRow.$$('td').get(1).getText()).toMatch('21');
expect(lastDataRow.$$('td').get(1).getText()).toMatch('40');
expect(dataRowsCollection.count()).toBe(20);
});
it('should filter up to 50 data rows per page when selecting a page size of "50"', () =>{
// Select '50' on tbPageSizeSelector
pageSizeSelector.$('[value="50"]').click();
// Verifying results on results-page 1
firstPageBtn.$('a').click();
expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
expect(lastDataRow.$$('td').get(1).getText()).toBe('50');
expect(dataRowsCollection.count()).toBe(50);
// Go to next page of results (page 2)
nextPageBtn.get(4).$('a').click();
// Verifying results on results-page 2
expect(firstDataRow.$$('td').get(1).getText()).toBe('51');
expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
expect(dataRowsCollection.count()).toBe(3);
});
it('should filter up to 100 data rows per page when selecting a page size of "100"', () => {
pageSizeSelector.$('[value="100"]').click();
expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
expect(dataRowsCollection.count()).toBe(53);
});
}); | Add page size selector e2e test | Add page size selector e2e test
| TypeScript | mit | unosquare/tubular2,unosquare/tubular2,unosquare/tubular2,unosquare/tubular2 | ---
+++
@@ -0,0 +1,65 @@
+///<reference path="../node_modules/@types/jasmine/index.d.ts"/>
+
+import { browser, element, by } from '../node_modules/protractor/built';
+
+describe('page size selector', () =>{
+ let dataRowsCollection,
+ firstDataRow,
+ lastDataRow,
+ firstPageBtn,
+ nextPageBtn,
+ pageSizeSelector,
+ gridPager
+
+ beforeAll(()=>{
+ browser.get('/');
+ gridPager = element(by.tagName('grid-pager')).$('ngb-pagination').$('nav ul');
+ pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select');
+ dataRowsCollection = element(by.tagName('tbody')).$$('tr');
+ firstDataRow = element(by.tagName('tbody')).$$('tr').first();
+ lastDataRow = element(by.tagName('tbody')).$$('tr').last();
+ firstPageBtn = gridPager.$$('li').first();
+ nextPageBtn = gridPager.$$('li');
+ });
+
+ it('should filter up to 10 data rows per page when selecting a page size of "10"', () => {
+ pageSizeSelector.$('[value="10"]').click();
+ expect(firstDataRow.$$('td').get(1).getText()).toMatch('1');
+ expect(lastDataRow.$$('td').get(1).getText()).toMatch('10');
+ expect(dataRowsCollection.count()).toBe(10);
+ });
+
+ it('should filter up to 20 data rows per page when selecting a page size of "20"', () => {
+ pageSizeSelector.$('[value="20"]').click();
+ nextPageBtn.get(5).$('a').click();
+ expect(firstDataRow.$$('td').get(1).getText()).toMatch('21');
+ expect(lastDataRow.$$('td').get(1).getText()).toMatch('40');
+ expect(dataRowsCollection.count()).toBe(20);
+ });
+
+ it('should filter up to 50 data rows per page when selecting a page size of "50"', () =>{
+ // Select '50' on tbPageSizeSelector
+ pageSizeSelector.$('[value="50"]').click();
+
+ // Verifying results on results-page 1
+ firstPageBtn.$('a').click();
+ expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
+ expect(lastDataRow.$$('td').get(1).getText()).toBe('50');
+ expect(dataRowsCollection.count()).toBe(50);
+
+ // Go to next page of results (page 2)
+ nextPageBtn.get(4).$('a').click();
+ // Verifying results on results-page 2
+ expect(firstDataRow.$$('td').get(1).getText()).toBe('51');
+ expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
+ expect(dataRowsCollection.count()).toBe(3);
+ });
+
+ it('should filter up to 100 data rows per page when selecting a page size of "100"', () => {
+ pageSizeSelector.$('[value="100"]').click();
+
+ expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
+ expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
+ expect(dataRowsCollection.count()).toBe(53);
+ });
+}); |
|
106523df6771477ebe2cfbaf7a1f6124c4705416 | CrashReporter/languages/ChineseSimplified.ts | CrashReporter/languages/ChineseSimplified.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>MainWindow</name>
<message>
<location filename="../mainwindow.ui" line="14"/>
<source>Crash Reporter</source>
<translation>错误报告</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="28"/>
<source>Sorry</source>
<translation>抱歉!</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="44"/>
<source>Grabber encountered a problem and crashed. The program will try to restore your tabs and other settings when it restarts.</source>
<translation>Grabber 遇到了问题并且停止工作。程序将会在重启时尝试恢复您的标签页与设置</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="60"/>
<source>To help us fix this crash, you can send us a bug report.</source>
<translation>为了帮助我们修复问题,您可以给我们发送错误报告</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="70"/>
<source>Send a bug report</source>
<translation>发送错误报告</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="95"/>
<source>Log</source>
<translation>日志</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="102"/>
<source>Settings</source>
<translation>设置</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="109"/>
<source>Dump</source>
<translation>转储信息</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="155"/>
<source>Restart</source>
<translation>重启程序</translation>
</message>
<message>
<location filename="../mainwindow.ui" line="162"/>
<source>Quit</source>
<translation>退出</translation>
</message>
</context>
</TS>
| Update Chinese Simplified Translation for Crash Report | Update Chinese Simplified Translation for Crash Report
| TypeScript | apache-2.0 | YoukaiCat/imgbrd-grabber,Bionus/imgbrd-grabber,YoukaiCat/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber,Bionus/imgbrd-grabber | ---
+++
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.1">
+<context>
+ <name>MainWindow</name>
+ <message>
+ <location filename="../mainwindow.ui" line="14"/>
+ <source>Crash Reporter</source>
+ <translation>错误报告</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="28"/>
+ <source>Sorry</source>
+ <translation>抱歉!</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="44"/>
+ <source>Grabber encountered a problem and crashed. The program will try to restore your tabs and other settings when it restarts.</source>
+ <translation>Grabber 遇到了问题并且停止工作。程序将会在重启时尝试恢复您的标签页与设置</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="60"/>
+ <source>To help us fix this crash, you can send us a bug report.</source>
+ <translation>为了帮助我们修复问题,您可以给我们发送错误报告</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="70"/>
+ <source>Send a bug report</source>
+ <translation>发送错误报告</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="95"/>
+ <source>Log</source>
+ <translation>日志</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="102"/>
+ <source>Settings</source>
+ <translation>设置</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="109"/>
+ <source>Dump</source>
+ <translation>转储信息</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="155"/>
+ <source>Restart</source>
+ <translation>重启程序</translation>
+ </message>
+ <message>
+ <location filename="../mainwindow.ui" line="162"/>
+ <source>Quit</source>
+ <translation>退出</translation>
+ </message>
+</context>
+</TS> |
|
4696bc75849d4c62a9eba78007e35a1685e24b6b | shared/utils/tool-homepages.ts | shared/utils/tool-homepages.ts | /**
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const browserify = 'http://browserify.org/';
export const rollup = 'https://rollupjs.org/';
export const webpack = 'https://webpack.js.org/';
export const parcel = 'https://parceljs.org/';
| Add utility for getting tool homepages | Add utility for getting tool homepages
| TypeScript | apache-2.0 | GoogleChromeLabs/tooling.report,GoogleChromeLabs/tooling.report,GoogleChromeLabs/tooling.report | ---
+++
@@ -0,0 +1,16 @@
+/**
+ * Copyright 2020 Google Inc. All Rights Reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+export const browserify = 'http://browserify.org/';
+export const rollup = 'https://rollupjs.org/';
+export const webpack = 'https://webpack.js.org/';
+export const parcel = 'https://parceljs.org/'; |
|
4a7e0dc9602ebec4478ea0078eeb266a0b8763d8 | projects/hslayers/src/common/dimension.spec.ts | projects/hslayers/src/common/dimension.spec.ts | import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {HsDimensionService} from './dimension.service';
import {HsMapService} from '../components/map/map.service';
import {HsMapServiceMock} from '../components/map/map.service.mock';
import {HsUtilsService} from '../components/utils/utils.service';
import {HsUtilsServiceMock} from '../components/utils/utils.service.mock';
import {TestBed} from '@angular/core/testing';
describe('HsGetCapabilitiesModule', () => {
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
});
let service: HsDimensionService;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [],
providers: [
HsDimensionService,
{provide: HsMapService, useValue: new HsMapServiceMock()},
{provide: HsUtilsService, useValue: new HsUtilsServiceMock()},
],
}); //.compileComponents();
service = TestBed.get(HsDimensionService);
});
it('prepareTimeSteps', () => {
const values = service.prepareTimeSteps(
'2016-03-16T12:00:00.000Z/2016-07-16T12:00:00.000Z/P30DT12H'
);
expect(values).toBeDefined();
expect(values).toEqual([
'2016-03-16T12:00:00.000Z',
'2016-04-16T00:00:00.000Z',
'2016-05-16T12:00:00.000Z',
'2016-06-16T00:00:00.000Z',
'2016-07-16T12:00:00.000Z',
]);
});
});
| Test for dimensions service prepareTimeSteps | test: Test for dimensions service prepareTimeSteps
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -0,0 +1,50 @@
+import {
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting,
+} from '@angular/platform-browser-dynamic/testing';
+import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
+import {HsDimensionService} from './dimension.service';
+import {HsMapService} from '../components/map/map.service';
+import {HsMapServiceMock} from '../components/map/map.service.mock';
+import {HsUtilsService} from '../components/utils/utils.service';
+import {HsUtilsServiceMock} from '../components/utils/utils.service.mock';
+import {TestBed} from '@angular/core/testing';
+
+describe('HsGetCapabilitiesModule', () => {
+ beforeAll(() => {
+ TestBed.resetTestEnvironment();
+ TestBed.initTestEnvironment(
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting()
+ );
+ });
+
+ let service: HsDimensionService;
+
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
+ imports: [],
+ providers: [
+ HsDimensionService,
+ {provide: HsMapService, useValue: new HsMapServiceMock()},
+ {provide: HsUtilsService, useValue: new HsUtilsServiceMock()},
+ ],
+ }); //.compileComponents();
+ service = TestBed.get(HsDimensionService);
+ });
+
+ it('prepareTimeSteps', () => {
+ const values = service.prepareTimeSteps(
+ '2016-03-16T12:00:00.000Z/2016-07-16T12:00:00.000Z/P30DT12H'
+ );
+ expect(values).toBeDefined();
+ expect(values).toEqual([
+ '2016-03-16T12:00:00.000Z',
+ '2016-04-16T00:00:00.000Z',
+ '2016-05-16T12:00:00.000Z',
+ '2016-06-16T00:00:00.000Z',
+ '2016-07-16T12:00:00.000Z',
+ ]);
+ });
+}); |
|
275ea9b18a262396500a4c66e3b13573082dbf70 | e2e/logout.e2e-spec.ts | e2e/logout.e2e-spec.ts | import { browser, element, by, ElementFinder, protractor, $, ExpectedConditions } from 'protractor';
import { LoginPageOjbect } from './login-page-object';
describe('Logout E2E Test', () => {
let originalTimeout;
let loginPage: LoginPageOjbect;
let moreButton: ElementFinder = element(by.id('barButtonMore'));
let logoutButton: ElementFinder = element(by.id('morePopoverLogoutButton'));
beforeEach(function () {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
beforeEach(() => {
loginPage = new LoginPageOjbect();
loginPage.loadPage();
});
afterEach(function () {
browser.manage().deleteAllCookies();
browser.executeScript('window.sessionStorage.clear();');
browser.executeScript('window.localStorage.clear();');
browser.executeScript('window.indexedDB.deleteDatabase("imsClientDB")');
});
it('Should return to Loginscreen', () => {
loginPage.login();
waitUntilElementsAreClickable();
moreButton.click();
waitUntilElementsAreClickable();
logoutButton.click();
waitUntilPageReady();
loginPage.getServerInputText().then(text => expect(text).toEqual(loginPage.server));
loginPage.getUserInputText().then(text => expect(text).toEqual(loginPage.user));
loginPage.getPasswordInputText().then(text => expect(text).toEqual(''));
});
});
function waitUntilElementsAreClickable() {
browser.wait(ExpectedConditions.stalenessOf($('.click-block-active')));
browser.sleep(500);
}
function waitUntilPageReady() {
browser.sleep(1000);
}
| Add e2e test for test logout behaviour | Add e2e test for test logout behaviour
| TypeScript | mit | IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app | ---
+++
@@ -0,0 +1,54 @@
+import { browser, element, by, ElementFinder, protractor, $, ExpectedConditions } from 'protractor';
+import { LoginPageOjbect } from './login-page-object';
+
+describe('Logout E2E Test', () => {
+
+ let originalTimeout;
+ let loginPage: LoginPageOjbect;
+ let moreButton: ElementFinder = element(by.id('barButtonMore'));
+ let logoutButton: ElementFinder = element(by.id('morePopoverLogoutButton'));
+
+
+ beforeEach(function () {
+ originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
+ jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
+ });
+
+ afterEach(function () {
+ jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
+ });
+
+
+ beforeEach(() => {
+ loginPage = new LoginPageOjbect();
+ loginPage.loadPage();
+ });
+
+ afterEach(function () {
+ browser.manage().deleteAllCookies();
+ browser.executeScript('window.sessionStorage.clear();');
+ browser.executeScript('window.localStorage.clear();');
+ browser.executeScript('window.indexedDB.deleteDatabase("imsClientDB")');
+ });
+
+ it('Should return to Loginscreen', () => {
+ loginPage.login();
+ waitUntilElementsAreClickable();
+ moreButton.click();
+ waitUntilElementsAreClickable();
+ logoutButton.click();
+ waitUntilPageReady();
+ loginPage.getServerInputText().then(text => expect(text).toEqual(loginPage.server));
+ loginPage.getUserInputText().then(text => expect(text).toEqual(loginPage.user));
+ loginPage.getPasswordInputText().then(text => expect(text).toEqual(''));
+ });
+});
+
+function waitUntilElementsAreClickable() {
+ browser.wait(ExpectedConditions.stalenessOf($('.click-block-active')));
+ browser.sleep(500);
+}
+
+function waitUntilPageReady() {
+ browser.sleep(1000);
+} |
|
851cc2aba5afbe076fbfc2bd66d0cc6b784f4d9a | src/Test/Ast/TableCaption.ts | src/Test/Ast/TableCaption.ts | import { expect } from 'chai'
import Up from '../../index'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { TableNode } from '../../SyntaxNodes/TableNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
context("In a table's label line, when the term for 'table' is followed by a colon,", () => {
specify('the colon can be folowed by a table caption', () => {
const text = `
Table: Games in the Chrono series
Game; Release Date
Chrono Trigger; 1995
Chrono Cross; 1999`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new TableNode(
new TableNode.Header([
new TableNode.Header.Cell([new PlainTextNode('Game')]),
new TableNode.Header.Cell([new PlainTextNode('Release Date')])
]), [
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]),
new TableNode.Row.Cell([new PlainTextNode('1995')])
]),
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]),
new TableNode.Row.Cell([new PlainTextNode('1999')])
])
],
new TableNode.Caption([
new PlainTextNode('Games in the Chrono series')
]))
]))
})
})
describe("A table caption", () => {
it('is evaluated for inline conventions', () => {
const text = `
Table: Games in the *Chrono* series
Game; Release Date
Chrono Trigger; 1995
Chrono Cross; 1999`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new TableNode(
new TableNode.Header([
new TableNode.Header.Cell([new PlainTextNode('Game')]),
new TableNode.Header.Cell([new PlainTextNode('Release Date')])
]), [
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]),
new TableNode.Row.Cell([new PlainTextNode('1995')])
]),
new TableNode.Row([
new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]),
new TableNode.Row.Cell([new PlainTextNode('1999')])
])
],
new TableNode.Caption([
new PlainTextNode('Games in the '),
new EmphasisNode([
new PlainTextNode('Chrono')
]),
new PlainTextNode(' series'),
]))
]))
})
})
| Add 2 failing table caption tests | Add 2 failing table caption tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,79 @@
+import { expect } from 'chai'
+import Up from '../../index'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { TableNode } from '../../SyntaxNodes/TableNode'
+import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+
+
+
+context("In a table's label line, when the term for 'table' is followed by a colon,", () => {
+ specify('the colon can be folowed by a table caption', () => {
+ const text = `
+Table: Games in the Chrono series
+
+Game; Release Date
+
+Chrono Trigger; 1995
+Chrono Cross; 1999`
+
+ expect(Up.toAst(text)).to.be.eql(
+ new DocumentNode([
+ new TableNode(
+ new TableNode.Header([
+ new TableNode.Header.Cell([new PlainTextNode('Game')]),
+ new TableNode.Header.Cell([new PlainTextNode('Release Date')])
+ ]), [
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]),
+ new TableNode.Row.Cell([new PlainTextNode('1995')])
+ ]),
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]),
+ new TableNode.Row.Cell([new PlainTextNode('1999')])
+ ])
+ ],
+ new TableNode.Caption([
+ new PlainTextNode('Games in the Chrono series')
+ ]))
+ ]))
+ })
+})
+
+
+describe("A table caption", () => {
+ it('is evaluated for inline conventions', () => {
+ const text = `
+Table: Games in the *Chrono* series
+
+Game; Release Date
+
+Chrono Trigger; 1995
+Chrono Cross; 1999`
+
+ expect(Up.toAst(text)).to.be.eql(
+ new DocumentNode([
+ new TableNode(
+ new TableNode.Header([
+ new TableNode.Header.Cell([new PlainTextNode('Game')]),
+ new TableNode.Header.Cell([new PlainTextNode('Release Date')])
+ ]), [
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('Chrono Trigger')]),
+ new TableNode.Row.Cell([new PlainTextNode('1995')])
+ ]),
+ new TableNode.Row([
+ new TableNode.Row.Cell([new PlainTextNode('Chrono Cross')]),
+ new TableNode.Row.Cell([new PlainTextNode('1999')])
+ ])
+ ],
+ new TableNode.Caption([
+ new PlainTextNode('Games in the '),
+ new EmphasisNode([
+ new PlainTextNode('Chrono')
+ ]),
+ new PlainTextNode(' series'),
+ ]))
+ ]))
+ })
+}) |
|
fc8052ec790b2fc43306e12ebf005d1160e2f544 | src/test/Apha/Scheduling/Storage/MemoryScheduleStorage.spec.ts | src/test/Apha/Scheduling/Storage/MemoryScheduleStorage.spec.ts |
import {expect} from "chai";
import {MemoryScheduleStorage} from "../../../../main/Apha/Scheduling/Storage/MemoryScheduleStorage";
import {ScheduledEvent} from "../../../../main/Apha/Scheduling/Storage/ScheduleStorage";
import {Event} from "../../../../main/Apha/Message/Event";
describe("MemoryScheduleStorage", () => {
let storage;
beforeEach(() => {
storage = new MemoryScheduleStorage();
});
describe("add", () => {
it("stores a scheduled event into storage", () => {
let schedule: ScheduledEvent = {
event: new MemoryScheduleStorageSpecEvent(),
timestamp: 1,
token: "foo"
};
storage.add(schedule);
let allSchedule = storage.findAll();
expect(allSchedule[0]).to.eql(schedule);
});
});
describe("remove", () => {
it("removes a scheduled event from storage", () => {
storage.add({
event: new MemoryScheduleStorageSpecEvent(),
timestamp: 1,
token: "foo"
});
storage.remove("foo");
expect(storage.findAll()).to.have.lengthOf(0);
});
it("is idempotent", () => {
expect(() => {
storage.remove("foo");
}).not.to.throw(Error);
});
});
describe("findAll", () => {
it("retrieves all scheduled events from storage", () => {
let schedule: ScheduledEvent = {
event: new MemoryScheduleStorageSpecEvent(),
timestamp: 1,
token: "foo"
};
storage.add(schedule);
expect(storage.findAll()).to.have.lengthOf(1);
});
});
});
class MemoryScheduleStorageSpecEvent extends Event {}
| Add test for schedule storage. | Add test for schedule storage.
| TypeScript | mit | martyn82/aphajs | ---
+++
@@ -0,0 +1,64 @@
+
+import {expect} from "chai";
+import {MemoryScheduleStorage} from "../../../../main/Apha/Scheduling/Storage/MemoryScheduleStorage";
+import {ScheduledEvent} from "../../../../main/Apha/Scheduling/Storage/ScheduleStorage";
+import {Event} from "../../../../main/Apha/Message/Event";
+
+describe("MemoryScheduleStorage", () => {
+ let storage;
+
+ beforeEach(() => {
+ storage = new MemoryScheduleStorage();
+ });
+
+ describe("add", () => {
+ it("stores a scheduled event into storage", () => {
+ let schedule: ScheduledEvent = {
+ event: new MemoryScheduleStorageSpecEvent(),
+ timestamp: 1,
+ token: "foo"
+ };
+
+ storage.add(schedule);
+ let allSchedule = storage.findAll();
+
+ expect(allSchedule[0]).to.eql(schedule);
+ });
+ });
+
+ describe("remove", () => {
+ it("removes a scheduled event from storage", () => {
+ storage.add({
+ event: new MemoryScheduleStorageSpecEvent(),
+ timestamp: 1,
+ token: "foo"
+ });
+
+ storage.remove("foo");
+
+ expect(storage.findAll()).to.have.lengthOf(0);
+ });
+
+ it("is idempotent", () => {
+ expect(() => {
+ storage.remove("foo");
+ }).not.to.throw(Error);
+ });
+ });
+
+ describe("findAll", () => {
+ it("retrieves all scheduled events from storage", () => {
+ let schedule: ScheduledEvent = {
+ event: new MemoryScheduleStorageSpecEvent(),
+ timestamp: 1,
+ token: "foo"
+ };
+
+ storage.add(schedule);
+
+ expect(storage.findAll()).to.have.lengthOf(1);
+ });
+ });
+});
+
+class MemoryScheduleStorageSpecEvent extends Event {} |
|
e2b8a8bb01b2c1b95202e03107db125c89e8332f | src/Test/Html/Config/Footnote.ts | src/Test/Html/Config/Footnote.ts | import { expect } from 'chai'
import { Up } from '../../../index'
import { FootnoteNode } from '../../../SyntaxNodes/FootnoteNode'
import { FootnoteBlockNode } from '../../../SyntaxNodes/FootnoteBlockNode' | Add empty file for footnote html config tests | Add empty file for footnote html config tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,4 @@
+import { expect } from 'chai'
+import { Up } from '../../../index'
+import { FootnoteNode } from '../../../SyntaxNodes/FootnoteNode'
+import { FootnoteBlockNode } from '../../../SyntaxNodes/FootnoteBlockNode' |
|
93b4ea5be43eda0d70963c54af80721cfa27b2ac | src/utils/maps.ts | src/utils/maps.ts | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { arrayDiff, arrayMerge, arrayUnion } from "./arrays";
/**
* Determines the keys added, changed, and removed between two Maps.
* For changes, simple triple equal comparisons are done, not in-depth
* tree checking.
* @param a The first object. Must be defined.
* @param b The second object. Must be defined.
* @returns The difference between the keys of each object.
*/
export function mapDiff<K, V>(a: Map<K, V>, b: Map<K, V>): { changed: K[], added: K[], removed: K[] } {
const aKeys = [...a.keys()];
const bKeys = [...b.keys()];
const keyDiff = arrayDiff(aKeys, bKeys);
const possibleChanges = arrayUnion(aKeys, bKeys);
const changes = possibleChanges.filter(k => a.get(k) !== b.get(k));
return {changed: changes, added: keyDiff.added, removed: keyDiff.removed};
}
/**
* Gets all the key changes (added, removed, or value difference) between
* two Maps. Triple equals is used to compare values, not in-depth tree
* checking.
* @param a The first object. Must be defined.
* @param b The second object. Must be defined.
* @returns The keys which have been added, removed, or changed between the
* two objects.
*/
export function mapKeyChanges<K, V>(a: Map<K, V>, b: Map<K, V>): K[] {
const diff = mapDiff(a, b);
return arrayMerge(diff.removed, diff.added, diff.changed);
}
| Create Maps utility comparison functions | Create Maps utility comparison functions
| TypeScript | apache-2.0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -0,0 +1,49 @@
+/*
+Copyright 2020 The Matrix.org Foundation C.I.C.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+import { arrayDiff, arrayMerge, arrayUnion } from "./arrays";
+
+/**
+ * Determines the keys added, changed, and removed between two Maps.
+ * For changes, simple triple equal comparisons are done, not in-depth
+ * tree checking.
+ * @param a The first object. Must be defined.
+ * @param b The second object. Must be defined.
+ * @returns The difference between the keys of each object.
+ */
+export function mapDiff<K, V>(a: Map<K, V>, b: Map<K, V>): { changed: K[], added: K[], removed: K[] } {
+ const aKeys = [...a.keys()];
+ const bKeys = [...b.keys()];
+ const keyDiff = arrayDiff(aKeys, bKeys);
+ const possibleChanges = arrayUnion(aKeys, bKeys);
+ const changes = possibleChanges.filter(k => a.get(k) !== b.get(k));
+
+ return {changed: changes, added: keyDiff.added, removed: keyDiff.removed};
+}
+
+/**
+ * Gets all the key changes (added, removed, or value difference) between
+ * two Maps. Triple equals is used to compare values, not in-depth tree
+ * checking.
+ * @param a The first object. Must be defined.
+ * @param b The second object. Must be defined.
+ * @returns The keys which have been added, removed, or changed between the
+ * two objects.
+ */
+export function mapKeyChanges<K, V>(a: Map<K, V>, b: Map<K, V>): K[] {
+ const diff = mapDiff(a, b);
+ return arrayMerge(diff.removed, diff.added, diff.changed);
+} |
|
67894c08e837be1ee81af002ec534d8a8d5c73d2 | app/src/lib/to-milliseconds.ts | app/src/lib/to-milliseconds.ts | import { assertNever } from './fatal-error'
type Unit = 'year' | 'day' | 'hour' | 'minute' | 'second'
type Plural = `${Unit}s`
export function toMilliseconds(value: 1, unit: Unit): number
export function toMilliseconds(value: number, unit: Plural): number
export function toMilliseconds(value: number, unit: Unit | Plural): number {
switch (unit) {
case 'year':
case 'years':
return value * 1000 * 60 * 60 * 24 * 365
case 'day':
case 'days':
return value * 1000 * 60 * 60 * 24
case 'hour':
case 'hours':
return value * 1000 * 60 * 60
case 'minute':
case 'minutes':
return value * 1000 * 60
case 'second':
case 'seconds':
return value * 1000
default:
assertNever(unit, `Unknown time unit ${unit}`)
}
}
| Add a helper function for converting time to milliseconds | Add a helper function for converting time to milliseconds
| TypeScript | mit | desktop/desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop | ---
+++
@@ -0,0 +1,28 @@
+import { assertNever } from './fatal-error'
+
+type Unit = 'year' | 'day' | 'hour' | 'minute' | 'second'
+type Plural = `${Unit}s`
+
+export function toMilliseconds(value: 1, unit: Unit): number
+export function toMilliseconds(value: number, unit: Plural): number
+export function toMilliseconds(value: number, unit: Unit | Plural): number {
+ switch (unit) {
+ case 'year':
+ case 'years':
+ return value * 1000 * 60 * 60 * 24 * 365
+ case 'day':
+ case 'days':
+ return value * 1000 * 60 * 60 * 24
+ case 'hour':
+ case 'hours':
+ return value * 1000 * 60 * 60
+ case 'minute':
+ case 'minutes':
+ return value * 1000 * 60
+ case 'second':
+ case 'seconds':
+ return value * 1000
+ default:
+ assertNever(unit, `Unknown time unit ${unit}`)
+ }
+} |
|
8900999afa75652f5e1a9ef656ba4b552dc861d3 | src/functions/tokeniseSentence.ts | src/functions/tokeniseSentence.ts | import { TokenisedPhrase } from '@/types'
import { tokeniseWord } from '@/functions/tokeniseWord'
export function tokeniseSentence(
sentence: string,
splitBy: string[],
alphabets: string[],
): TokenisedPhrase[] {
/**
* Takes a string and converts it to tokens. Tokens are dicts that instruct
* the renderer on what to draw e.g. what letters and shapes are present.
* The renderer will decide how to draw those things e.g. what size
* everything is.
*
* @param sentence: a string containing the sentence to be tokenised.
* Gallifreyo's definition of a sentence is a series of words, but what those
* words are can be anything. Most words will also be sentences.
* @param splitBy: an array of strings by which to split
*/
// This is a recursive function that pops from splitBy. There are two
// possible return values:
// 1. If there is at least one splitBy delimiter, split the text by it.
// The result will be at least one string. Pass that to a new
// tokeniseSentence call to be broken down further or tokenised.
// 2. If all the delimiters have been used up, then the string is a word.
// It needs to be broken up into letters and tokenised, and then returned.
// As a result, a nested structure of tokenised words should be produced.
if (splitBy.length > 0) {
// Split the sentence by the first splitBy into a series of phrases.
// Right now, we don't care what those phrases actually are. I'm using
// "phrases" to ambiguously mean either a sentence or a word.
const phrases: TokenisedPhrase[] = []
for (const phrase of sentence.split(splitBy.shift())) {
// splitBy[0] is the delimiter for this sentence depth
// At depth 0, delimiter is "\n\n", therefore each phrase is paragraph
// This phrase should be further split
const tokenisedPhrase = tokeniseSentence(phrase, splitBy, alphabets)
phrases.push(tokenisedPhrase)
}
return phrases
} else {
// The delimiters have been used up, so sentence is a word.
return tokeniseWord(sentence, alphabets)
}
return null
}
| Make function to make tokens from a sentence | Make function to make tokens from a sentence
| TypeScript | mit | rossjrw/gallifreyo,rossjrw/gallifreyo,rossjrw/gallifreyo | ---
+++
@@ -0,0 +1,46 @@
+import { TokenisedPhrase } from '@/types'
+import { tokeniseWord } from '@/functions/tokeniseWord'
+
+export function tokeniseSentence(
+ sentence: string,
+ splitBy: string[],
+ alphabets: string[],
+): TokenisedPhrase[] {
+ /**
+ * Takes a string and converts it to tokens. Tokens are dicts that instruct
+ * the renderer on what to draw e.g. what letters and shapes are present.
+ * The renderer will decide how to draw those things e.g. what size
+ * everything is.
+ *
+ * @param sentence: a string containing the sentence to be tokenised.
+ * Gallifreyo's definition of a sentence is a series of words, but what those
+ * words are can be anything. Most words will also be sentences.
+ * @param splitBy: an array of strings by which to split
+ */
+ // This is a recursive function that pops from splitBy. There are two
+ // possible return values:
+ // 1. If there is at least one splitBy delimiter, split the text by it.
+ // The result will be at least one string. Pass that to a new
+ // tokeniseSentence call to be broken down further or tokenised.
+ // 2. If all the delimiters have been used up, then the string is a word.
+ // It needs to be broken up into letters and tokenised, and then returned.
+ // As a result, a nested structure of tokenised words should be produced.
+ if (splitBy.length > 0) {
+ // Split the sentence by the first splitBy into a series of phrases.
+ // Right now, we don't care what those phrases actually are. I'm using
+ // "phrases" to ambiguously mean either a sentence or a word.
+ const phrases: TokenisedPhrase[] = []
+ for (const phrase of sentence.split(splitBy.shift())) {
+ // splitBy[0] is the delimiter for this sentence depth
+ // At depth 0, delimiter is "\n\n", therefore each phrase is paragraph
+ // This phrase should be further split
+ const tokenisedPhrase = tokeniseSentence(phrase, splitBy, alphabets)
+ phrases.push(tokenisedPhrase)
+ }
+ return phrases
+ } else {
+ // The delimiters have been used up, so sentence is a word.
+ return tokeniseWord(sentence, alphabets)
+ }
+ return null
+} |
|
01b8c8e9d68193a3f4044f5a0e7a148ba3b8cfd4 | lib/components/map/with-map.tsx | lib/components/map/with-map.tsx | import { MapRef, useMap } from 'react-map-gl'
import React, { Component, FC } from 'react'
/**
* Higher-order component that passes a map prop to its children.
* Intended to wrap around class components that are direct or indirect children of <MapProvider>.
* Function components should use react-map-gl's useMap instead.
*/
export default function withMap<T>(
ClassComponent: Component<T>
): FC<T & { map: MapRef }> {
const WrappedComponent = (props: T): JSX.Element => {
const mapRefs = useMap()
return <ClassComponent {...props} map={mapRefs.current} />
}
return WrappedComponent
}
| Add HOC to access native map object. | improvement(withMap): Add HOC to access native map object.
| TypeScript | mit | opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux | ---
+++
@@ -0,0 +1,18 @@
+import { MapRef, useMap } from 'react-map-gl'
+import React, { Component, FC } from 'react'
+
+/**
+ * Higher-order component that passes a map prop to its children.
+ * Intended to wrap around class components that are direct or indirect children of <MapProvider>.
+ * Function components should use react-map-gl's useMap instead.
+ */
+export default function withMap<T>(
+ ClassComponent: Component<T>
+): FC<T & { map: MapRef }> {
+ const WrappedComponent = (props: T): JSX.Element => {
+ const mapRefs = useMap()
+ return <ClassComponent {...props} map={mapRefs.current} />
+ }
+
+ return WrappedComponent
+} |
|
0a3b928fef3fd05df5d3ddc7f45a549d14c79d82 | src/utils/turkopticon.ts | src/utils/turkopticon.ts | import axios from 'axios';
export const fetchRequesterTO = async (requesterIds: string[]) => {
const x = await axios.get(`https://turkopticon.ucsd.edu/api/multi-attrs.php?ids=`);
return x;
};
| Add stub utility function for querying TO | Add stub utility function for querying TO
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,6 @@
+import axios from 'axios';
+
+export const fetchRequesterTO = async (requesterIds: string[]) => {
+ const x = await axios.get(`https://turkopticon.ucsd.edu/api/multi-attrs.php?ids=`);
+ return x;
+}; |
|
bd39fc72c6ea8304c00f7b469635b5bbbeeb1d17 | tests/cases/fourslash/quicklInfoDisplayPartsInterface.ts | tests/cases/fourslash/quicklInfoDisplayPartsInterface.ts | /// <reference path='fourslash.ts'/>
////interface /*1*/i {
////}
////var /*2*/iInstance: /*3*/i;
goTo.marker('1');
verify.verifyQuickInfo("interface", "", { start: test.markerByName("1").position, length: "i".length },
[{ text: "interface", kind: "keyword" }, { text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
[]);
goTo.marker('2');
verify.verifyQuickInfo("var", "", { start: test.markerByName("2").position, length: "iInstance".length },
[{ text: "(", kind: "punctuation" }, { text: "var", kind: "text" }, { text: ")", kind: "punctuation" },
{ text: " ", kind: "space" }, { text: "iInstance", kind: "localName" }, { text: ":", kind: "punctuation" },
{ text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
[]);
goTo.marker('3');
verify.verifyQuickInfo("interface", "", { start: test.markerByName("3").position, length: "i".length },
[{ text: "interface", kind: "keyword" }, { text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
[]); | Test case for interface display parts | Test case for interface display parts
| TypeScript | apache-2.0 | kpreisser/TypeScript,HereSinceres/TypeScript,synaptek/TypeScript,HereSinceres/TypeScript,chuckjaz/TypeScript,OlegDokuka/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,ziacik/TypeScript,shanexu/TypeScript,mihailik/TypeScript,OlegDokuka/TypeScript,chocolatechipui/TypeScript,AbubakerB/TypeScript,weswigham/TypeScript,rgbkrk/TypeScript,progre/TypeScript,kitsonk/TypeScript,bpowers/TypeScript,rodrigues-daniel/TypeScript,mszczepaniak/TypeScript,sassson/TypeScript,Eyas/TypeScript,Viromo/TypeScript,nagyistoce/TypeScript,blakeembrey/TypeScript,tinganho/TypeScript,Raynos/TypeScript,zmaruo/TypeScript,alexeagle/TypeScript,billti/TypeScript,nojvek/TypeScript,mcanthony/TypeScript,weswigham/TypeScript,nycdotnet/TypeScript,kingland/TypeScript,nojvek/TypeScript,TukekeSoft/TypeScript,abbasmhd/TypeScript,kimamula/TypeScript,synaptek/TypeScript,fdecampredon/jsx-typescript,plantain-00/TypeScript,blakeembrey/TypeScript,thr0w/Thr0wScript,samuelhorwitz/typescript,JohnZ622/TypeScript,jwbay/TypeScript,plantain-00/TypeScript,vilic/TypeScript,hitesh97/TypeScript,zhengbli/TypeScript,erikmcc/TypeScript,AbubakerB/TypeScript,germ13/TypeScript,yukulele/TypeScript,JohnZ622/TypeScript,MartyIX/TypeScript,Mqgh2013/TypeScript,Viromo/TypeScript,SimoneGianni/TypeScript,Microsoft/TypeScript,thr0w/Thr0wScript,donaldpipowitch/TypeScript,zmaruo/TypeScript,Viromo/TypeScript,hoanhtien/TypeScript,evgrud/TypeScript,tempbottle/TypeScript,shovon/TypeScript,enginekit/TypeScript,mihailik/TypeScript,kitsonk/TypeScript,jwbay/TypeScript,Mqgh2013/TypeScript,suto/TypeScript,gonifade/TypeScript,shanexu/TypeScript,gdi2290/TypeScript,jwbay/TypeScript,tempbottle/TypeScript,jdavidberger/TypeScript,impinball/TypeScript,Microsoft/TypeScript,AbubakerB/TypeScript,thr0w/Thr0wScript,jamesrmccallum/TypeScript,gonifade/TypeScript,DLehenbauer/TypeScript,shiftkey/TypeScript,moander/TypeScript,RyanCavanaugh/TypeScript,OlegDokuka/TypeScript,fabioparra/TypeScript,SaschaNaz/TypeScript,Raynos/TypeScript,rodrigues-daniel/TypeScript,mcanthony/TypeScript,impinball/TypeScript,MartyIX/TypeScript,moander/TypeScript,ZLJASON/TypeScript,blakeembrey/TypeScript,ziacik/TypeScript,plantain-00/TypeScript,sassson/TypeScript,nojvek/TypeScript,DanielRosenwasser/TypeScript,zhengbli/TypeScript,ropik/TypeScript,hitesh97/TypeScript,progre/TypeScript,progre/TypeScript,RReverser/TypeScript,microsoft/TypeScript,jeremyepling/TypeScript,RReverser/TypeScript,donaldpipowitch/TypeScript,DanielRosenwasser/TypeScript,fdecampredon/jsx-typescript,microsoft/TypeScript,hoanhtien/TypeScript,shanexu/TypeScript,Raynos/TypeScript,jteplitz602/TypeScript,Eyas/TypeScript,DLehenbauer/TypeScript,mszczepaniak/TypeScript,minestarks/TypeScript,kumikumi/TypeScript,ropik/TypeScript,donaldpipowitch/TypeScript,ionux/TypeScript,fearthecowboy/TypeScript,nycdotnet/TypeScript,mauricionr/TypeScript,zmaruo/TypeScript,ionux/TypeScript,mauricionr/TypeScript,fearthecowboy/TypeScript,ropik/TypeScript,nojvek/TypeScript,kingland/TypeScript,DanielRosenwasser/TypeScript,germ13/TypeScript,mihailik/TypeScript,mauricionr/TypeScript,mmoskal/TypeScript,ziacik/TypeScript,MartyIX/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,DLehenbauer/TypeScript,webhost/TypeScript,basarat/TypeScript,SimoneGianni/TypeScript,fabioparra/TypeScript,jbondc/TypeScript,jamesrmccallum/TypeScript,nagyistoce/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,nycdotnet/TypeScript,evgrud/TypeScript,RyanCavanaugh/TypeScript,AbubakerB/TypeScript,nycdotnet/TypeScript,fabioparra/TypeScript,mihailik/TypeScript,SimoneGianni/TypeScript,zhengbli/TypeScript,nagyistoce/TypeScript,evgrud/TypeScript,yazeng/TypeScript,shovon/TypeScript,bpowers/TypeScript,sassson/TypeScript,tinganho/TypeScript,evgrud/TypeScript,RyanCavanaugh/TypeScript,JohnZ622/TypeScript,alexeagle/TypeScript,MartyIX/TypeScript,jwbay/TypeScript,gonifade/TypeScript,kimamula/TypeScript,pcan/TypeScript,samuelhorwitz/typescript,kumikumi/TypeScript,ziacik/TypeScript,RReverser/TypeScript,basarat/TypeScript,yazeng/TypeScript,DanielRosenwasser/TypeScript,abbasmhd/TypeScript,billti/TypeScript,keir-rex/TypeScript,tempbottle/TypeScript,jteplitz602/TypeScript,keir-rex/TypeScript,msynk/TypeScript,enginekit/TypeScript,minestarks/TypeScript,hitesh97/TypeScript,rodrigues-daniel/TypeScript,plantain-00/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,Viromo/TypeScript,Eyas/TypeScript,fdecampredon/jsx-typescript,synaptek/TypeScript,bpowers/TypeScript,basarat/TypeScript,suto/TypeScript,alexeagle/TypeScript,mauricionr/TypeScript,SmallAiTT/TypeScript,SmallAiTT/TypeScript,chocolatechipui/TypeScript,billti/TypeScript,impinball/TypeScript,matthewjh/TypeScript,Raynos/TypeScript,microsoft/TypeScript,rodrigues-daniel/TypeScript,yazeng/TypeScript,mmoskal/TypeScript,rgbkrk/TypeScript,mcanthony/TypeScript,shanexu/TypeScript,erikmcc/TypeScript,webhost/TypeScript,jteplitz602/TypeScript,webhost/TypeScript,enginekit/TypeScript,SaschaNaz/TypeScript,moander/TypeScript,jeremyepling/TypeScript,kpreisser/TypeScript,yortus/TypeScript,minestarks/TypeScript,ionux/TypeScript,JohnZ622/TypeScript,abbasmhd/TypeScript,ropik/TypeScript,kitsonk/TypeScript,kingland/TypeScript,mmoskal/TypeScript,jamesrmccallum/TypeScript,yukulele/TypeScript,tinganho/TypeScript,ZLJASON/TypeScript,HereSinceres/TypeScript,yortus/TypeScript,chocolatechipui/TypeScript,TukekeSoft/TypeScript,kimamula/TypeScript,jdavidberger/TypeScript,jbondc/TypeScript,jeremyepling/TypeScript,samuelhorwitz/typescript,shiftkey/TypeScript,yukulele/TypeScript,kimamula/TypeScript,erikmcc/TypeScript,matthewjh/TypeScript,yortus/TypeScript,jdavidberger/TypeScript,mmoskal/TypeScript,ZLJASON/TypeScript,chuckjaz/TypeScript,hoanhtien/TypeScript,ionux/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,germ13/TypeScript,fabioparra/TypeScript,yortus/TypeScript,basarat/TypeScript,Mqgh2013/TypeScript,mcanthony/TypeScript,moander/TypeScript,matthewjh/TypeScript,pcan/TypeScript,rgbkrk/TypeScript,erikmcc/TypeScript,suto/TypeScript,shovon/TypeScript,pcan/TypeScript,fdecampredon/jsx-typescript,Eyas/TypeScript,keir-rex/TypeScript,msynk/TypeScript,SmallAiTT/TypeScript,thr0w/Thr0wScript,blakeembrey/TypeScript,vilic/TypeScript,chuckjaz/TypeScript,DLehenbauer/TypeScript,kumikumi/TypeScript,samuelhorwitz/typescript,msynk/TypeScript,mszczepaniak/TypeScript,synaptek/TypeScript,shiftkey/TypeScript,fearthecowboy/TypeScript,jbondc/TypeScript | ---
+++
@@ -0,0 +1,22 @@
+/// <reference path='fourslash.ts'/>
+
+////interface /*1*/i {
+////}
+////var /*2*/iInstance: /*3*/i;
+
+goTo.marker('1');
+verify.verifyQuickInfo("interface", "", { start: test.markerByName("1").position, length: "i".length },
+ [{ text: "interface", kind: "keyword" }, { text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
+ []);
+
+goTo.marker('2');
+verify.verifyQuickInfo("var", "", { start: test.markerByName("2").position, length: "iInstance".length },
+ [{ text: "(", kind: "punctuation" }, { text: "var", kind: "text" }, { text: ")", kind: "punctuation" },
+ { text: " ", kind: "space" }, { text: "iInstance", kind: "localName" }, { text: ":", kind: "punctuation" },
+ { text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
+ []);
+
+goTo.marker('3');
+verify.verifyQuickInfo("interface", "", { start: test.markerByName("3").position, length: "i".length },
+ [{ text: "interface", kind: "keyword" }, { text: " ", kind: "space" }, { text: "i", kind: "interfaceName" }],
+ []); |
|
9360ca5ab0a653176ce3bd1794c8a4cc4fd0f316 | client/Components/StatBlock.test.tsx | client/Components/StatBlock.test.tsx | import * as React from "react";
import * as renderer from "react-test-renderer";
import { StatBlock } from "../../common/StatBlock";
import { DefaultRules } from "../Rules/Rules";
import { buildStatBlockTextEnricher } from "../test/buildEncounter";
import { StatBlockComponent } from "./StatBlock";
describe("StatBlock component", () => {
test("Shows the statblock's name", () => {
const rules = new DefaultRules();
const component = renderer.create(
<StatBlockComponent
statBlock={{ ...StatBlock.Default(), Name: "Snarglebargle" }}
enricher={buildStatBlockTextEnricher(rules)}
displayMode="default"
/>);
const header = component.toJSON().children.filter(c => c.type == "h3").pop();
expect(header.children).toEqual(["Snarglebargle"]);
});
}); | Test that StatBlock component renders its name | Test that StatBlock component renders its name
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -0,0 +1,20 @@
+import * as React from "react";
+import * as renderer from "react-test-renderer";
+import { StatBlock } from "../../common/StatBlock";
+import { DefaultRules } from "../Rules/Rules";
+import { buildStatBlockTextEnricher } from "../test/buildEncounter";
+import { StatBlockComponent } from "./StatBlock";
+
+describe("StatBlock component", () => {
+ test("Shows the statblock's name", () => {
+ const rules = new DefaultRules();
+ const component = renderer.create(
+ <StatBlockComponent
+ statBlock={{ ...StatBlock.Default(), Name: "Snarglebargle" }}
+ enricher={buildStatBlockTextEnricher(rules)}
+ displayMode="default"
+ />);
+ const header = component.toJSON().children.filter(c => c.type == "h3").pop();
+ expect(header.children).toEqual(["Snarglebargle"]);
+ });
+}); |
|
292688119b54d0a9f404690d9d3ff5aa3419399a | src/renderer/constants/dictionary.ts | src/renderer/constants/dictionary.ts | export const MonthsList = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
export const DaysList = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
| Add months and days list | Add months and days list
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -0,0 +1,24 @@
+export const MonthsList = [
+ 'January',
+ 'February',
+ 'March',
+ 'April',
+ 'May',
+ 'June',
+ 'July',
+ 'August',
+ 'September',
+ 'October',
+ 'November',
+ 'December',
+];
+
+export const DaysList = [
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ 'Sunday',
+]; |
|
2266b78d831945bcb0966ed6564730032b3bb35b | app/features/SectionDivider/index.tsx | app/features/SectionDivider/index.tsx | import * as React from 'react';
import styled from 'styled-components';
import { Draggable, DragMode, Unregister } from 'core/interactions/handlers/draggable';
interface Props {
onDrag: (deltaY: number) => void;
}
export class SectionDivider extends React.Component<Props, {}> {
draggable = new Draggable({ mode: DragMode.absolute });
unregisterDragHandler: Unregister;
dividerRef: HTMLDivElement;
componentDidMount() {
const { draggable } = this;
draggable.onDrag(this.onDrag);
this.unregisterDragHandler = this.draggable.register(this.dividerRef!, this.dividerRef!);
}
componentWillUnmount() {
this.unregisterDragHandler();
}
onDrag = (deltaX: number, deltaY: number) => {
this.props.onDrag(deltaY);
};
render() {
return <Divider innerRef={ref => (this.dividerRef = ref)} />;
}
}
export default SectionDivider;
const Divider = styled.div`
width: 100%;
height: 10px;
background-color: black;
cursor: row-resize;
`;
| import * as React from 'react';
import styled from 'styled-components';
import { Draggable, DragMode, Unregister } from 'core/interactions/handlers/draggable';
interface Props {
onDrag: (deltaY: number) => void;
}
export class SectionDivider extends React.Component<Props, {}> {
draggable = new Draggable({ mode: DragMode.absolute });
unregisterDragHandler: Unregister;
dividerRef: HTMLDivElement;
componentDidMount() {
const { draggable } = this;
draggable.onDrag(this.onDrag);
this.unregisterDragHandler = this.draggable.register(this.dividerRef!, this.dividerRef!);
}
componentWillUnmount() {
this.unregisterDragHandler();
}
onDrag = (deltaX: number, deltaY: number) => {
this.props.onDrag(deltaY);
};
render() {
return <Divider innerRef={ref => (this.dividerRef = ref)} />;
}
}
export default SectionDivider;
const Divider = styled.div`
width: 100%;
height: 3px;
background-color: black;
cursor: row-resize;
`;
| Adjust size of section divider | Adjust size of section divider
| TypeScript | mit | cannoneyed/fiddle,cannoneyed/fiddle,cannoneyed/fiddle | ---
+++
@@ -36,7 +36,7 @@
const Divider = styled.div`
width: 100%;
- height: 10px;
+ height: 3px;
background-color: black;
cursor: row-resize;
`; |
0dca9096133632281cd91f65e0ecd3a8a8660509 | helpers/Array+first.ts | helpers/Array+first.ts | declare global {
interface Array<T> {
first(): T | undefined
}
}
Array.prototype.first = function first(): Element | undefined {
if (this.length > 0) {
return this[0]
} else {
return undefined
}
}
export {}
| Add currently unused Array.prototype.first extension | Add currently unused Array.prototype.first extension
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -0,0 +1,15 @@
+declare global {
+ interface Array<T> {
+ first(): T | undefined
+ }
+}
+
+Array.prototype.first = function first(): Element | undefined {
+ if (this.length > 0) {
+ return this[0]
+ } else {
+ return undefined
+ }
+}
+
+export {} |
|
c8a1268df576cfcb92e068ec059d83e2a2f6f663 | test/e2e/console/console-eval-fake_test.ts | test/e2e/console/console-eval-fake_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {assert} from 'chai';
import {describe, it} from 'mocha';
import {click, getBrowserAndPages, pasteText, step} from '../../shared/helper.js';
import {CONSOLE_TAB_SELECTOR, focusConsolePrompt} from '../helpers/console-helpers.js';
import {getCurrentConsoleMessages} from '../helpers/console-helpers.js';
describe('The Console Tab', async () => {
it('doesn’t break when global `eval` is overwritten', async () => {
const {frontend} = getBrowserAndPages();
let messages: string[];
await step('navigate to the Console tab', async () => {
await click(CONSOLE_TAB_SELECTOR);
await focusConsolePrompt();
});
await step('enter code that overwrites eval', async () => {
await pasteText(`
const foo = 'fooValue';
globalThis.eval = 'non-function';
`);
await frontend.keyboard.press('Enter');
// Wait for the console to be usable again.
await frontend.waitForFunction(() => {
return document.querySelectorAll('.console-user-command-result').length === 1;
});
});
await step('enter a code snippet', async () => {
await pasteText('foo;');
await frontend.keyboard.press('Enter');
});
await step('retrieve the console log', async () => {
messages = await getCurrentConsoleMessages();
});
await step('check that the expected output is logged', async () => {
assert.deepEqual(messages, [
'"non-function"',
'"fooValue"',
]);
});
});
});
| Add e2e test for fake eval in Console | Add e2e test for fake eval in Console
This patch ports the following layout test:
https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/web_tests/http/tests/devtools/console/console-eval-fake.js;drc=78e2bc9c2def358a0745878ffc66ce85ee5221d8
CL removing the upstream test:
https://chromium-review.googlesource.com/c/chromium/src/+/2270177
Bug: chromium:1099603
Change-Id: Id33fa12254d4bf10f4797aa1f54487a0b3acd4cb
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2270157
Reviewed-by: Peter Marshall <[email protected]>
Commit-Queue: Mathias Bynens <[email protected]>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -0,0 +1,51 @@
+// Copyright 2020 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import {assert} from 'chai';
+import {describe, it} from 'mocha';
+
+import {click, getBrowserAndPages, pasteText, step} from '../../shared/helper.js';
+import {CONSOLE_TAB_SELECTOR, focusConsolePrompt} from '../helpers/console-helpers.js';
+import {getCurrentConsoleMessages} from '../helpers/console-helpers.js';
+
+describe('The Console Tab', async () => {
+ it('doesn’t break when global `eval` is overwritten', async () => {
+ const {frontend} = getBrowserAndPages();
+ let messages: string[];
+
+ await step('navigate to the Console tab', async () => {
+ await click(CONSOLE_TAB_SELECTOR);
+ await focusConsolePrompt();
+ });
+
+ await step('enter code that overwrites eval', async () => {
+ await pasteText(`
+ const foo = 'fooValue';
+ globalThis.eval = 'non-function';
+ `);
+ await frontend.keyboard.press('Enter');
+
+ // Wait for the console to be usable again.
+ await frontend.waitForFunction(() => {
+ return document.querySelectorAll('.console-user-command-result').length === 1;
+ });
+ });
+
+ await step('enter a code snippet', async () => {
+ await pasteText('foo;');
+ await frontend.keyboard.press('Enter');
+ });
+
+ await step('retrieve the console log', async () => {
+ messages = await getCurrentConsoleMessages();
+ });
+
+ await step('check that the expected output is logged', async () => {
+ assert.deepEqual(messages, [
+ '"non-function"',
+ '"fooValue"',
+ ]);
+ });
+ });
+}); |
|
8b40723e0b301bf51a7a7f5d465bf65292e9cf8f | opr-core/src/server/customrequesthandler.ts | opr-core/src/server/customrequesthandler.ts | import type {Request} from 'express';
/**
* Interface for custom request handlers for OprServer. This interface requires
* that the request body is a (possibly empty) JSON object, and that the
* response is a JSON object. The response object is not directly available. If
* the handler encounters a problem it must throw a StatusError.
*/
export interface CustomRequestHandler {
handle(body: unknown, request: Request): unknown;
}
| Support custom request handlers, and add a Google Cloud custom request handler that checks identity tokens | Support custom request handlers, and add a Google Cloud custom request handler that checks identity tokens
| TypeScript | apache-2.0 | google/open-product-recovery,google/open-product-recovery,google/open-product-recovery | ---
+++
@@ -0,0 +1,11 @@
+import type {Request} from 'express';
+
+/**
+ * Interface for custom request handlers for OprServer. This interface requires
+ * that the request body is a (possibly empty) JSON object, and that the
+ * response is a JSON object. The response object is not directly available. If
+ * the handler encounters a problem it must throw a StatusError.
+ */
+export interface CustomRequestHandler {
+ handle(body: unknown, request: Request): unknown;
+} |
|
5ab573ae056e99f44c8d48f6548e80574fa744b1 | test/property-decorators/to-uppercase.spec.ts | test/property-decorators/to-uppercase.spec.ts | import { ToUppercase } from './../../src/';
describe('ToUppercase decorator', () => {
it('should throw an error when is applied over non string property', () => {
class TestClassToUppercaseProperty {
@ToUppercase() myProp: number;
}
let testClass = new TestClassToUppercaseProperty();
expect(() => testClass.myProp = 7).toThrowError('The ToUppercase decorator have to be used over string object');
});
it('should apply default behavior', () => {
class TestClassToUppercaseProperty {
@ToUppercase() myProp: string;
}
let testClass = new TestClassToUppercaseProperty();
let stringToAssign = 'a long string to be tested';
testClass.myProp = stringToAssign;
expect(testClass.myProp).toEqual(stringToAssign.toUpperCase());
});
it('should capitalize', () => {
class TestClassToUppercaseProperty {
@ToUppercase({ capitalize: true }) myProp: string;
}
let testClass = new TestClassToUppercaseProperty();
testClass.myProp = 'a long String to be tested';
expect(testClass.myProp).toEqual('A long String to be tested');
});
it('should use locale', () => {
class TestClassToUppercaseProperty {
@ToUppercase({ useLocale: true }) myProp: string;
}
let testClass = new TestClassToUppercaseProperty();
let stringToTest = 'a long String to be tested';
testClass.myProp = stringToTest;
expect(testClass.myProp).toEqual(stringToTest.toLocaleUpperCase());
});
it('should capitalize using locale', () => {
class TestClassToUppercaseProperty {
@ToUppercase({ capitalize: true, useLocale: true }) myProp: string;
}
let testClass = new TestClassToUppercaseProperty();
let stringToTest = 'a long String to be tested';
testClass.myProp = stringToTest;
expect(testClass.myProp).toBe(stringToTest[0].toLocaleUpperCase() + stringToTest.slice(1));
});
}); | Add unit tests for ToUppercase decorator | Add unit tests for ToUppercase decorator
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -0,0 +1,57 @@
+import { ToUppercase } from './../../src/';
+
+describe('ToUppercase decorator', () => {
+
+ it('should throw an error when is applied over non string property', () => {
+ class TestClassToUppercaseProperty {
+ @ToUppercase() myProp: number;
+ }
+ let testClass = new TestClassToUppercaseProperty();
+ expect(() => testClass.myProp = 7).toThrowError('The ToUppercase decorator have to be used over string object');
+ });
+
+ it('should apply default behavior', () => {
+ class TestClassToUppercaseProperty {
+ @ToUppercase() myProp: string;
+ }
+
+ let testClass = new TestClassToUppercaseProperty();
+ let stringToAssign = 'a long string to be tested';
+ testClass.myProp = stringToAssign;
+ expect(testClass.myProp).toEqual(stringToAssign.toUpperCase());
+ });
+
+
+ it('should capitalize', () => {
+ class TestClassToUppercaseProperty {
+ @ToUppercase({ capitalize: true }) myProp: string;
+ }
+
+ let testClass = new TestClassToUppercaseProperty();
+ testClass.myProp = 'a long String to be tested';
+ expect(testClass.myProp).toEqual('A long String to be tested');
+ });
+
+ it('should use locale', () => {
+ class TestClassToUppercaseProperty {
+ @ToUppercase({ useLocale: true }) myProp: string;
+ }
+
+ let testClass = new TestClassToUppercaseProperty();
+ let stringToTest = 'a long String to be tested';
+ testClass.myProp = stringToTest;
+ expect(testClass.myProp).toEqual(stringToTest.toLocaleUpperCase());
+ });
+
+ it('should capitalize using locale', () => {
+ class TestClassToUppercaseProperty {
+ @ToUppercase({ capitalize: true, useLocale: true }) myProp: string;
+ }
+
+ let testClass = new TestClassToUppercaseProperty();
+ let stringToTest = 'a long String to be tested';
+ testClass.myProp = stringToTest;
+ expect(testClass.myProp).toBe(stringToTest[0].toLocaleUpperCase() + stringToTest.slice(1));
+ });
+
+}); |
|
ec07e4fbdce17062a137e6ee30d164831c6df0d9 | app/src/ui/dialog/ok-cancel-button-group.tsx | app/src/ui/dialog/ok-cancel-button-group.tsx | import * as React from 'react'
import * as classNames from 'classnames'
import { Button } from '../lib/button'
interface IOkCancelButtonGroupProps {
/**
* An optional className to be applied to the rendered div element.
*/
readonly className?: string
readonly destructive?: boolean
readonly okButtonText?: string
readonly okButtonTitle?: string
readonly onOkButtonClick?: (
event: React.MouseEvent<HTMLButtonElement>
) => void
readonly okButtonDisabled?: boolean
readonly cancelButtonText?: string
readonly cancelButtonTitle?: string
readonly onCancelButtonClick?: (
event: React.MouseEvent<HTMLButtonElement>
) => void
readonly cancelButtonDisabled?: boolean
}
export class OkCancelButtonGroup extends React.Component<
IOkCancelButtonGroupProps,
{}
> {
private onOkButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
if (this.props.onOkButtonClick !== undefined) {
this.props.onOkButtonClick(event)
}
if (event.defaultPrevented) {
return
}
if (this.props.destructive === true) {
event.preventDefault()
if (event.currentTarget.form) {
event.currentTarget.form.submit()
}
}
}
private onCancelButtonClick = (
event: React.MouseEvent<HTMLButtonElement>
) => {
if (this.props.onCancelButtonClick !== undefined) {
this.props.onCancelButtonClick(event)
}
if (event.defaultPrevented) {
return
}
if (this.props.destructive === true) {
event.preventDefault()
if (event.currentTarget.form) {
event.currentTarget.form.reset()
}
}
}
private renderOkButton() {
return (
<Button
onClick={this.onOkButtonClick}
disabled={this.props.okButtonDisabled}
tooltip={this.props.okButtonTitle}
type={this.props.destructive === true ? 'button' : 'submit'}
>
{this.props.okButtonText || 'Ok'}
</Button>
)
}
private renderCancelButton() {
return (
<Button
onClick={this.onCancelButtonClick}
disabled={this.props.cancelButtonDisabled}
tooltip={this.props.cancelButtonTitle}
type={this.props.destructive === true ? 'submit' : 'reset'}
>
{this.props.cancelButtonText || 'Cancel'}
</Button>
)
}
private renderButtons() {
if (__DARWIN__) {
return (
<>
{this.renderCancelButton()}
{this.renderOkButton()}
</>
)
} else {
return (
<>
{this.renderOkButton()}
{this.renderCancelButton()}
</>
)
}
}
public render() {
const className = classNames('button-group', this.props.className, {
destructive: this.props.destructive === true,
})
return (
<div className={className}>
{this.renderButtons()}
{this.props.children}
</div>
)
}
}
| Add first attempt at a declarative button group | Add first attempt at a declarative button group
| TypeScript | mit | artivilla/desktop,say25/desktop,desktop/desktop,desktop/desktop,say25/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop | ---
+++
@@ -0,0 +1,124 @@
+import * as React from 'react'
+import * as classNames from 'classnames'
+import { Button } from '../lib/button'
+
+interface IOkCancelButtonGroupProps {
+ /**
+ * An optional className to be applied to the rendered div element.
+ */
+ readonly className?: string
+
+ readonly destructive?: boolean
+
+ readonly okButtonText?: string
+ readonly okButtonTitle?: string
+ readonly onOkButtonClick?: (
+ event: React.MouseEvent<HTMLButtonElement>
+ ) => void
+ readonly okButtonDisabled?: boolean
+
+ readonly cancelButtonText?: string
+ readonly cancelButtonTitle?: string
+ readonly onCancelButtonClick?: (
+ event: React.MouseEvent<HTMLButtonElement>
+ ) => void
+ readonly cancelButtonDisabled?: boolean
+}
+
+export class OkCancelButtonGroup extends React.Component<
+ IOkCancelButtonGroupProps,
+ {}
+> {
+ private onOkButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
+ if (this.props.onOkButtonClick !== undefined) {
+ this.props.onOkButtonClick(event)
+ }
+
+ if (event.defaultPrevented) {
+ return
+ }
+
+ if (this.props.destructive === true) {
+ event.preventDefault()
+ if (event.currentTarget.form) {
+ event.currentTarget.form.submit()
+ }
+ }
+ }
+
+ private onCancelButtonClick = (
+ event: React.MouseEvent<HTMLButtonElement>
+ ) => {
+ if (this.props.onCancelButtonClick !== undefined) {
+ this.props.onCancelButtonClick(event)
+ }
+
+ if (event.defaultPrevented) {
+ return
+ }
+
+ if (this.props.destructive === true) {
+ event.preventDefault()
+ if (event.currentTarget.form) {
+ event.currentTarget.form.reset()
+ }
+ }
+ }
+
+ private renderOkButton() {
+ return (
+ <Button
+ onClick={this.onOkButtonClick}
+ disabled={this.props.okButtonDisabled}
+ tooltip={this.props.okButtonTitle}
+ type={this.props.destructive === true ? 'button' : 'submit'}
+ >
+ {this.props.okButtonText || 'Ok'}
+ </Button>
+ )
+ }
+
+ private renderCancelButton() {
+ return (
+ <Button
+ onClick={this.onCancelButtonClick}
+ disabled={this.props.cancelButtonDisabled}
+ tooltip={this.props.cancelButtonTitle}
+ type={this.props.destructive === true ? 'submit' : 'reset'}
+ >
+ {this.props.cancelButtonText || 'Cancel'}
+ </Button>
+ )
+ }
+
+ private renderButtons() {
+ if (__DARWIN__) {
+ return (
+ <>
+ {this.renderCancelButton()}
+ {this.renderOkButton()}
+ </>
+ )
+ } else {
+ return (
+ <>
+ {this.renderOkButton()}
+ {this.renderCancelButton()}
+ </>
+ )
+ }
+ }
+
+ public render() {
+ const className = classNames('button-group', this.props.className, {
+ destructive: this.props.destructive === true,
+ })
+
+ return (
+ <div className={className}>
+ {this.renderButtons()}
+ {this.props.children}
+ </div>
+ )
+ }
+} |
|
15082bcf9aee384a9b3e57b8b0736cffb120324e | src/styles/elements/button.ts | src/styles/elements/button.ts | const theme = {
verticalAlign: '',
background: '',
textColor: '',
fontFamily: '',
horizontalMargin: '',
verticalMargin: '',
verticalPadding: '',
horizontalPadding: '',
shadowOffset: '',
textTransform: '',
textShadow: '',
fontWeight: '',
lineHeight: '',
borderRadius: '',
boxShadow: '',
transition: '',
willChange: '',
tapColor: ''
};
const button = {
cursor: 'pointer',
display: 'inline-block',
minHeight: '1em',
outline: 'none',
border: 'none',
verticalAlign: theme.verticalAlign,
background: theme.background,
color: theme.textColor,
fontFamily: theme.fontFamily,
margin: `0em ${theme.horizontalMargin} ${theme.verticalMargin} 0em`,
padding: `${theme.verticalPadding} ${theme.horizontalPadding} ${theme.verticalPadding + theme.shadowOffset}`,
textTransform: theme.textTransform,
textShadow: theme.textShadow,
fontWeight: theme.fontWeight,
lineHeight: theme.lineHeight,
fontStyle: 'normal',
textAlign: 'center',
textDecoration: 'none',
borderRadius: theme.borderRadius,
boxShadow: theme.boxShadow,
userSelect: 'none',
transition: theme.transition,
willChange: theme.willChange,
WebkitTapHighlightColor: theme.tapColor
};
| Add sample style object for Button | Add sample style object for Button
| TypeScript | mit | maxdeviant/semantic-ui-css-in-js,maxdeviant/semantic-ui-css-in-js | ---
+++
@@ -0,0 +1,55 @@
+const theme = {
+ verticalAlign: '',
+ background: '',
+ textColor: '',
+ fontFamily: '',
+ horizontalMargin: '',
+ verticalMargin: '',
+ verticalPadding: '',
+ horizontalPadding: '',
+ shadowOffset: '',
+ textTransform: '',
+ textShadow: '',
+ fontWeight: '',
+ lineHeight: '',
+ borderRadius: '',
+ boxShadow: '',
+ transition: '',
+ willChange: '',
+ tapColor: ''
+};
+
+const button = {
+ cursor: 'pointer',
+ display: 'inline-block',
+
+ minHeight: '1em',
+
+ outline: 'none',
+ border: 'none',
+ verticalAlign: theme.verticalAlign,
+ background: theme.background,
+ color: theme.textColor,
+
+ fontFamily: theme.fontFamily,
+
+ margin: `0em ${theme.horizontalMargin} ${theme.verticalMargin} 0em`,
+ padding: `${theme.verticalPadding} ${theme.horizontalPadding} ${theme.verticalPadding + theme.shadowOffset}`,
+
+ textTransform: theme.textTransform,
+ textShadow: theme.textShadow,
+ fontWeight: theme.fontWeight,
+ lineHeight: theme.lineHeight,
+ fontStyle: 'normal',
+ textAlign: 'center',
+ textDecoration: 'none',
+
+ borderRadius: theme.borderRadius,
+ boxShadow: theme.boxShadow,
+
+ userSelect: 'none',
+ transition: theme.transition,
+ willChange: theme.willChange,
+
+ WebkitTapHighlightColor: theme.tapColor
+}; |
|
c4c32b1e2b4138bfd4a1dcef80556baf30fa995e | test/EventListenerDataSpec.ts | test/EventListenerDataSpec.ts | import EventDispatcher from "../src/lib/EventDispatcher";
import EventListenerData from "../src/lib/EventListenerData";
import chai = require('chai');
import sinon = require('sinon');
import sinonChai = require('sinon-chai');
import BasicEvent from "../src/lib/event/BasicEvent";
const {expect} = chai;
chai.use(sinonChai);
describe('EventListenerData', () =>
{
describe('#dispose()', () =>
{
const A = new EventDispatcher();
const handler = sinon.spy();
const eventListenerData:EventListenerData = A.addEventListener('T', handler);
eventListenerData.dispose();
it('should remove the event listener from the attached EventDispatcher', () =>
{
A.dispatchEvent(new BasicEvent('T'));
expect(handler).to.not.have.been.called;
});
});
});
| Add unit test for EventListenerData | Add unit test for EventListenerData
| TypeScript | mit | mediamonks/seng-event,mediamonks/seng-event | ---
+++
@@ -0,0 +1,25 @@
+import EventDispatcher from "../src/lib/EventDispatcher";
+import EventListenerData from "../src/lib/EventListenerData";
+import chai = require('chai');
+import sinon = require('sinon');
+import sinonChai = require('sinon-chai');
+import BasicEvent from "../src/lib/event/BasicEvent";
+const {expect} = chai;
+chai.use(sinonChai);
+
+describe('EventListenerData', () =>
+{
+ describe('#dispose()', () =>
+ {
+ const A = new EventDispatcher();
+ const handler = sinon.spy();
+ const eventListenerData:EventListenerData = A.addEventListener('T', handler);
+ eventListenerData.dispose();
+
+ it('should remove the event listener from the attached EventDispatcher', () =>
+ {
+ A.dispatchEvent(new BasicEvent('T'));
+ expect(handler).to.not.have.been.called;
+ });
+ });
+}); |
|
ff53321059f0eb50c3b0ca9adf7d5d98fe88138b | src/events/gestures/pointer_map.ts | src/events/gestures/pointer_map.ts | export interface PointerMapEntry<T> {
id: number;
value: T;
}
export type PointerMap<T> = PointerMapEntry<T>[];
export type PointerMapList<T> = PointerMap<T[]>;
export function pointerMapSet<T>(map: PointerMap<T>, id: number, value: T) {
for (let i = 0; i < map.length; i++) {
const item = map[i];
if (item.id === id) {
item.value = value;
return;
}
}
map.push({ id, value });
}
export function pointerMapGet<T>(map: PointerMap<T>, id: number): T | undefined {
for (let i = 0; i < map.length; i++) {
const item = map[i];
if (item.id === id) {
return item.value;
}
}
return undefined;
}
export function pointerMapDelete<T>(map: PointerMap<T>, id: number): void {
for (let i = 0; i < map.length; i++) {
const item = map[i];
if (item.id === id) {
if (i === map.length - 1) {
map.pop()!;
} else {
map[i] = map.pop()!;
}
return;
}
}
}
export function pointerMapListPush<T>(map: PointerMapList<T>, id: number, value: T): void {
for (let i = 0; i < map.length; i++) {
const item = map[i];
if (item.id === id) {
item.value.push(value);
return;
}
}
map.push({
id,
value: [value],
});
}
export function pointerMapListDelete<T>(map: PointerMapList<T>, id: number, value: T): void {
for (let i = 0; i < map.length; i++) {
const item = map[i];
if (item.id === id) {
const values = item.value;
if (values.length === 1) {
if (i === map.length - 1) {
map.pop()!;
} else {
map[i] = map.pop()!;
}
} else {
for (let j = 0; j < values.length; j++) {
const v = values[j];
if (v === value) {
if (j === values.length - 1) {
values.pop()!;
} else {
values[j] = values.pop()!;
}
}
}
}
return;
}
}
}
| Add pointer map data structure | Add pointer map data structure
| TypeScript | mit | ivijs/ivi,ivijs/ivi | ---
+++
@@ -0,0 +1,84 @@
+export interface PointerMapEntry<T> {
+ id: number;
+ value: T;
+}
+
+export type PointerMap<T> = PointerMapEntry<T>[];
+export type PointerMapList<T> = PointerMap<T[]>;
+
+export function pointerMapSet<T>(map: PointerMap<T>, id: number, value: T) {
+ for (let i = 0; i < map.length; i++) {
+ const item = map[i];
+ if (item.id === id) {
+ item.value = value;
+ return;
+ }
+ }
+ map.push({ id, value });
+}
+
+export function pointerMapGet<T>(map: PointerMap<T>, id: number): T | undefined {
+ for (let i = 0; i < map.length; i++) {
+ const item = map[i];
+ if (item.id === id) {
+ return item.value;
+ }
+ }
+ return undefined;
+}
+
+export function pointerMapDelete<T>(map: PointerMap<T>, id: number): void {
+ for (let i = 0; i < map.length; i++) {
+ const item = map[i];
+ if (item.id === id) {
+ if (i === map.length - 1) {
+ map.pop()!;
+ } else {
+ map[i] = map.pop()!;
+ }
+ return;
+ }
+ }
+}
+
+export function pointerMapListPush<T>(map: PointerMapList<T>, id: number, value: T): void {
+ for (let i = 0; i < map.length; i++) {
+ const item = map[i];
+ if (item.id === id) {
+ item.value.push(value);
+ return;
+ }
+ }
+ map.push({
+ id,
+ value: [value],
+ });
+}
+
+export function pointerMapListDelete<T>(map: PointerMapList<T>, id: number, value: T): void {
+ for (let i = 0; i < map.length; i++) {
+ const item = map[i];
+ if (item.id === id) {
+ const values = item.value;
+ if (values.length === 1) {
+ if (i === map.length - 1) {
+ map.pop()!;
+ } else {
+ map[i] = map.pop()!;
+ }
+ } else {
+ for (let j = 0; j < values.length; j++) {
+ const v = values[j];
+ if (v === value) {
+ if (j === values.length - 1) {
+ values.pop()!;
+ } else {
+ values[j] = values.pop()!;
+ }
+ }
+ }
+ }
+ return;
+ }
+ }
+} |
|
435fd38cb17645073f6f9d08ee3dc3fafa3769a9 | test/property-decorators/min.spec.ts | test/property-decorators/min.spec.ts | import { Min } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (greater or equals than min value)', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 5;
expect(testClass.myNumber).toEqual(5);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 3;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (less than min value)', () => {
class TestClassMinValue {
@Min(5, true)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 10;
testClass.myNumber = 3;
expect(testClass.myNumber).toEqual(10);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMinValue {
@Min(5, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMinValue();
expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
});
}); | Add unit tests for min decorator | Add unit tests for min decorator
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -0,0 +1,50 @@
+import { Min } from './../../src/';
+
+describe('LoggerMethod decorator', () => {
+
+ it('should assign a valid value (greater or equals than min value)', () => {
+ class TestClassMinValue {
+ @Min(5)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMinValue();
+ testClass.myNumber = 5;
+ expect(testClass.myNumber).toEqual(5);
+ });
+
+ it('should assign null to the property (default value, protect = false) without throw an exception', () => {
+ class TestClassMinValue {
+ @Min(5)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMinValue();
+ testClass.myNumber = 3;
+ expect(testClass.myNumber).toBeNull();
+ });
+
+ it('should protect the previous value when assign an invalid value (less than min value)', () => {
+ class TestClassMinValue {
+ @Min(5, true)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMinValue();
+ testClass.myNumber = 10;
+ testClass.myNumber = 3;
+ expect(testClass.myNumber).toEqual(10);
+ });
+
+ it('should throw an error when the value assigned is invalid', () => {
+ let exceptionMsg = 'Invalid min value assigned!';
+ class TestClassMinValue {
+ @Min(5, false, exceptionMsg)
+ myNumber: number;
+ }
+
+ let testClass = new TestClassMinValue();
+ expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
+ });
+
+}); |
|
0181eb9423f25208792dbe26523159bbdcb18955 | src/adhocracy/adhocracy/frontend/static/js/Packages/MetaApi/MetaApiSpec.ts | src/adhocracy/adhocracy/frontend/static/js/Packages/MetaApi/MetaApiSpec.ts | /// <reference path="../../../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/>
import AdhMetaApi = require("./MetaApi");
var sampleMetaApi : AdhMetaApi.IMetaApi = {
"resources" : {
"adhocracy.resources.root.IRootPool" : {
"sheets" : [
"adhocracy.sheets.name.IName",
"adhocracy.sheets.pool.IPool",
"adhocracy.sheets.metadata.IMetadata"
],
"element_types" : [
"adhocracy.interfaces.IPool"
]
}
},
"sheets" : {
"adhocracy.sheets.metadata.IMetadata" : {
"fields" : [
{
"name" : "creator",
"readable" : true,
"editable" : false,
"create_mandatory" : false,
"valuetype" : "adhocracy.schema.AbsolutePath",
"targetsheet" : "adhocracy.sheets.user.IUserBasic",
"containertype" : "list",
"creatable" : false
},
{
"create_mandatory" : false,
"creatable" : false,
"readable" : true,
"editable" : false,
"valuetype" : "adhocracy.schema.DateTime",
"name" : "creation_date"
},
{
"editable" : false,
"readable" : true,
"create_mandatory" : false,
"creatable" : false,
"valuetype" : "adhocracy.schema.DateTime",
"name" : "modification_date"
}
]
},
"adhocracy.sheets.name.IName" : {
"fields" : [
{
"readable" : true,
"editable" : false,
"create_mandatory" : true,
"creatable" : true,
"valuetype" : "adhocracy.schema.Name",
"name" : "name"
}
]
},
"adhocracy.sheets.pool.IPool" : {
"fields" : [
{
"name" : "elements",
"create_mandatory" : false,
"readable" : true,
"editable" : false,
"valuetype" : "adhocracy.schema.AbsolutePath",
"targetsheet" : "adhocracy.interfaces.ISheet",
"containertype" : "list",
"creatable" : false
}
]
}
}
};
export var register = () => {
describe("MetaApi", () => {
var adhMetaApi : AdhMetaApi.MetaApiQuery;
beforeEach(() => {
adhMetaApi = new AdhMetaApi.MetaApiQuery(sampleMetaApi);
});
it("works!", () => {
expect(adhMetaApi.field("adhocracy.sheets.pool.IPool", "elements").name).toBe("elements");
expect(adhMetaApi.field("adhocracy.sheets.pool.IPool", "elements").editable).toBe(false);
});
});
};
| Add meta api unit tests. | Add meta api unit tests.
| TypeScript | agpl-3.0 | fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator | ---
+++
@@ -0,0 +1,92 @@
+/// <reference path="../../../lib/DefinitelyTyped/jasmine/jasmine.d.ts"/>
+
+import AdhMetaApi = require("./MetaApi");
+
+var sampleMetaApi : AdhMetaApi.IMetaApi = {
+ "resources" : {
+ "adhocracy.resources.root.IRootPool" : {
+ "sheets" : [
+ "adhocracy.sheets.name.IName",
+ "adhocracy.sheets.pool.IPool",
+ "adhocracy.sheets.metadata.IMetadata"
+ ],
+ "element_types" : [
+ "adhocracy.interfaces.IPool"
+ ]
+ }
+ },
+ "sheets" : {
+ "adhocracy.sheets.metadata.IMetadata" : {
+ "fields" : [
+ {
+ "name" : "creator",
+ "readable" : true,
+ "editable" : false,
+ "create_mandatory" : false,
+ "valuetype" : "adhocracy.schema.AbsolutePath",
+ "targetsheet" : "adhocracy.sheets.user.IUserBasic",
+ "containertype" : "list",
+ "creatable" : false
+ },
+ {
+ "create_mandatory" : false,
+ "creatable" : false,
+ "readable" : true,
+ "editable" : false,
+ "valuetype" : "adhocracy.schema.DateTime",
+ "name" : "creation_date"
+ },
+ {
+ "editable" : false,
+ "readable" : true,
+ "create_mandatory" : false,
+ "creatable" : false,
+ "valuetype" : "adhocracy.schema.DateTime",
+ "name" : "modification_date"
+ }
+ ]
+ },
+ "adhocracy.sheets.name.IName" : {
+ "fields" : [
+ {
+ "readable" : true,
+ "editable" : false,
+ "create_mandatory" : true,
+ "creatable" : true,
+ "valuetype" : "adhocracy.schema.Name",
+ "name" : "name"
+ }
+ ]
+ },
+ "adhocracy.sheets.pool.IPool" : {
+ "fields" : [
+ {
+ "name" : "elements",
+ "create_mandatory" : false,
+ "readable" : true,
+ "editable" : false,
+ "valuetype" : "adhocracy.schema.AbsolutePath",
+ "targetsheet" : "adhocracy.interfaces.ISheet",
+ "containertype" : "list",
+ "creatable" : false
+ }
+ ]
+ }
+ }
+};
+
+
+export var register = () => {
+ describe("MetaApi", () => {
+ var adhMetaApi : AdhMetaApi.MetaApiQuery;
+
+ beforeEach(() => {
+ adhMetaApi = new AdhMetaApi.MetaApiQuery(sampleMetaApi);
+ });
+
+ it("works!", () => {
+ expect(adhMetaApi.field("adhocracy.sheets.pool.IPool", "elements").name).toBe("elements");
+ expect(adhMetaApi.field("adhocracy.sheets.pool.IPool", "elements").editable).toBe(false);
+ });
+ });
+}; |
|
2b7c10cc0e2dddaf87cd652ea220950d9fecc613 | test/media_providers/Disk/DiskStrategy.ts | test/media_providers/Disk/DiskStrategy.ts | /// <reference path="../../../node_modules/@types/mocha/index.d.ts" />
/// <reference path="../../../node_modules/@types/chai/index.d.ts" />
/**
* Module dependencies.
*/
import * as chai from 'chai';
import * as chai_as_promised from 'chai-as-promised';
import * as mock from 'mock-require';
import * as path from 'path';
mock('fluent-ffmpeg', (path : string) => {
return {
ffprobe: (cb : any) => {
if(!path.match(/exists/)){
cb(Error('unable to find file on disk'));
} else {
cb(undefined, {
streams: [
{
duration: 200,
sample_rate: 44100
}
],
format: {
tags: {
title: 'Test Title',
artist: 'My Artist',
album: 'My Album',
genre: 'Example Genre'
}
}
});
}
}
}
});
import DiskSongFactory from '../../../src/media_providers/disk/DiskStrategy';
import Song from '../../../src/Song';
/**
* Globals
*/
const expect = chai.expect;
chai.use(chai_as_promised);
describe('Disk strategy', () => {
it('provides correctly constructed songs', () => {
const df = new DiskSongFactory('my_music');
const song = df.getSong('songexists.mp3');
return Promise.all([
expect(song).to.be.instanceOf(Promise),
expect(song).to.eventually.be.instanceof(Song).with.property('identifier', 'my_music' + path.sep + 'songexists.mp3'),
expect(song).to.eventually.be.instanceof(Song).with.property('title', 'Test Title'),
expect(song).to.eventually.be.instanceof(Song).with.property('duration', 200),
expect(song).to.eventually.be.instanceof(Song).with.property('sample_rate', 44100),
expect(song).to.eventually.be.instanceof(Song).with.property('artist', 'My Artist'),
expect(song).to.eventually.be.instanceof(Song).with.property('album', 'My Album'),
expect(song).to.eventually.be.instanceof(Song).with.property('genre', 'Example Genre')
]);
});
it('reports errors when trying to find song on disk', () => {
const df = new DiskSongFactory('my_music');
const song = df.getSong('no.wav');
return expect(song).to.eventually.be.rejectedWith(Error, 'unable to find file on disk');
});
});
| Create test for disk strategy | Create test for disk strategy
| TypeScript | mit | robertmain/jukebox,robertmain/jukebox | ---
+++
@@ -0,0 +1,74 @@
+/// <reference path="../../../node_modules/@types/mocha/index.d.ts" />
+/// <reference path="../../../node_modules/@types/chai/index.d.ts" />
+
+/**
+* Module dependencies.
+*/
+import * as chai from 'chai';
+import * as chai_as_promised from 'chai-as-promised';
+import * as mock from 'mock-require';
+import * as path from 'path';
+
+mock('fluent-ffmpeg', (path : string) => {
+ return {
+ ffprobe: (cb : any) => {
+ if(!path.match(/exists/)){
+ cb(Error('unable to find file on disk'));
+ } else {
+ cb(undefined, {
+ streams: [
+ {
+ duration: 200,
+ sample_rate: 44100
+ }
+ ],
+ format: {
+ tags: {
+ title: 'Test Title',
+ artist: 'My Artist',
+ album: 'My Album',
+ genre: 'Example Genre'
+ }
+ }
+ });
+ }
+ }
+ }
+});
+
+import DiskSongFactory from '../../../src/media_providers/disk/DiskStrategy';
+import Song from '../../../src/Song';
+
+/**
+* Globals
+*/
+const expect = chai.expect;
+chai.use(chai_as_promised);
+
+describe('Disk strategy', () => {
+ it('provides correctly constructed songs', () => {
+ const df = new DiskSongFactory('my_music');
+
+ const song = df.getSong('songexists.mp3');
+
+ return Promise.all([
+ expect(song).to.be.instanceOf(Promise),
+ expect(song).to.eventually.be.instanceof(Song).with.property('identifier', 'my_music' + path.sep + 'songexists.mp3'),
+ expect(song).to.eventually.be.instanceof(Song).with.property('title', 'Test Title'),
+ expect(song).to.eventually.be.instanceof(Song).with.property('duration', 200),
+ expect(song).to.eventually.be.instanceof(Song).with.property('sample_rate', 44100),
+ expect(song).to.eventually.be.instanceof(Song).with.property('artist', 'My Artist'),
+ expect(song).to.eventually.be.instanceof(Song).with.property('album', 'My Album'),
+ expect(song).to.eventually.be.instanceof(Song).with.property('genre', 'Example Genre')
+ ]);
+ });
+
+ it('reports errors when trying to find song on disk', () => {
+ const df = new DiskSongFactory('my_music');
+
+ const song = df.getSong('no.wav');
+
+ return expect(song).to.eventually.be.rejectedWith(Error, 'unable to find file on disk');
+ });
+});
+ |
|
359d4626415ea07a11c1864a285bbc16ca85e888 | app/src/lib/git/environment.ts | app/src/lib/git/environment.ts | import { envForAuthentication } from './authentication'
import { IGitAccount } from '../../models/git-account'
/**
* Create a set of environment variables to use when invoking a Git
* subcommand that needs to communicate with a remote (i.e. fetch, clone,
* push, pull, ls-remote, etc etc).
*
* The environment variables deal with setting up sane defaults, configuring
* authentication, and resolving proxy urls if necessary.
*
* @param account The authentication information (if available) to provide
* to Git for use when connectingt to the remote
* @param remoteUrl The primary remote URL for this operation. Note that Git
* might connect to other remotes in order to fulfill the
* operation. As an example, a clone of
* https://github.com/desktop/desktop could containt a submodule
* pointing to another host entirely. Used to resolve which
* proxy (if any) should be used for the operation.
*/
export function envForRemoteOperation(account: IGitAccount, remoteUrl: string) {
return {
...envForAuthentication(account),
}
}
| Create stub replacement for envForAuthentication | Create stub replacement for envForAuthentication
| TypeScript | mit | say25/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,say25/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop | ---
+++
@@ -0,0 +1,25 @@
+import { envForAuthentication } from './authentication'
+import { IGitAccount } from '../../models/git-account'
+
+/**
+ * Create a set of environment variables to use when invoking a Git
+ * subcommand that needs to communicate with a remote (i.e. fetch, clone,
+ * push, pull, ls-remote, etc etc).
+ *
+ * The environment variables deal with setting up sane defaults, configuring
+ * authentication, and resolving proxy urls if necessary.
+ *
+ * @param account The authentication information (if available) to provide
+ * to Git for use when connectingt to the remote
+ * @param remoteUrl The primary remote URL for this operation. Note that Git
+ * might connect to other remotes in order to fulfill the
+ * operation. As an example, a clone of
+ * https://github.com/desktop/desktop could containt a submodule
+ * pointing to another host entirely. Used to resolve which
+ * proxy (if any) should be used for the operation.
+ */
+export function envForRemoteOperation(account: IGitAccount, remoteUrl: string) {
+ return {
+ ...envForAuthentication(account),
+ }
+} |
|
31f47687feccbd4f6438668c0b63aabdaa7cb80f | src/plugins/autocompletion_providers/Cd.ts | src/plugins/autocompletion_providers/Cd.ts | import {executable, sequence, decorate, string, noisySuggestions, runtime, choice} from "../../shell/Parser";
import {expandHistoricalDirectory} from "../../Command";
import {description, styles, style} from "./Suggestions";
import * as _ from "lodash";
import {relativeDirectoryPath} from "./File";
import {pathIn} from "./Common";
const historicalDirectory = runtime(async (context) =>
decorate(
choice(
_.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => decorate(string(alias), description(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack))))
),
style(styles.directory)
)
);
const cdpathDirectory = runtime(
async (context) => choice(context.environment.cdpath(context.directory).filter(directory => directory !== context.directory).map(directory =>
decorate(pathIn(directory, info => info.stat.isDirectory()), description(`In ${directory}`))))
);
export const cd = sequence(decorate(executable("cd"), description("Change the working directory")), choice([
noisySuggestions(historicalDirectory),
noisySuggestions(cdpathDirectory),
relativeDirectoryPath,
]));
| import {executable, sequence, decorate, string, noisySuggestions, runtime, choice} from "../../shell/Parser";
import {expandHistoricalDirectory} from "../../Command";
import {description, styles, style, Suggestion} from "./Suggestions";
import * as _ from "lodash";
import {relativeDirectoryPath} from "./File";
import {pathIn} from "./Common";
import {PluginManager} from "../../PluginManager";
const historicalDirectory = runtime(async (context) =>
decorate(
choice(
_.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => decorate(string(alias), description(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack))))
),
style(styles.directory)
)
);
const cdpathDirectory = runtime(
async (context) => choice(context.environment.cdpath(context.directory).filter(directory => directory !== context.directory).map(directory =>
decorate(pathIn(directory, info => info.stat.isDirectory()), description(`In ${directory}`))))
);
export const cd = sequence(decorate(executable("cd"), description("Change the working directory")), choice([
noisySuggestions(historicalDirectory),
noisySuggestions(cdpathDirectory),
relativeDirectoryPath,
]));
PluginManager.registerAutocompletionProvider("cd", async(context) => {
return _.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack)).withStyle(styles.directory));
});
| Add cd historical directories suggestions. | Add cd historical directories suggestions.
| TypeScript | mit | j-allard/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,black-screen/black-screen,drew-gross/black-screen,vshatskyi/black-screen,drew-gross/black-screen,drew-gross/black-screen,shockone/black-screen,j-allard/black-screen,railsware/upterm,shockone/black-screen,vshatskyi/black-screen,j-allard/black-screen,railsware/upterm,black-screen/black-screen,drew-gross/black-screen,black-screen/black-screen | ---
+++
@@ -1,9 +1,10 @@
import {executable, sequence, decorate, string, noisySuggestions, runtime, choice} from "../../shell/Parser";
import {expandHistoricalDirectory} from "../../Command";
-import {description, styles, style} from "./Suggestions";
+import {description, styles, style, Suggestion} from "./Suggestions";
import * as _ from "lodash";
import {relativeDirectoryPath} from "./File";
import {pathIn} from "./Common";
+import {PluginManager} from "../../PluginManager";
const historicalDirectory = runtime(async (context) =>
decorate(
@@ -25,3 +26,8 @@
noisySuggestions(cdpathDirectory),
relativeDirectoryPath,
]));
+
+PluginManager.registerAutocompletionProvider("cd", async(context) => {
+ return _.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
+ .map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack)).withStyle(styles.directory));
+}); |
f7e36f818b42bd84047d7c41a51b50341568980e | test/components/ControlPanel.spec.tsx | test/components/ControlPanel.spec.tsx | import * as React from 'react';
import * as sinon from 'sinon';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { ControlPanelComponent } from '../../app/modules/ControlPanel/ControlPanel';
function setup() {
const props = {
currentSlide: 0,
numberOfSlides: 3,
addSlide: sinon.spy(() => {}),
goToSlide: sinon.spy(() => {}),
saveLastSlideDimensions: sinon.spy(() => {}),
toggleFullScreen: sinon.spy(() => {}),
};
const wrapper = shallow(<ControlPanelComponent {...props} />);
return { props, wrapper };
}
describe('<ControlPanel />', () => {
const CLICKS = 3;
describe('Self', () => {
const { wrapper } = setup();
it('should render two <Button /> components', () => {
expect(wrapper.find('Button')).to.have.length(2);
});
it('should render one Add Button', () => {
expect(wrapper.find({ iconName: 'add' })).to.have.length(1);
});
it('should render one FullScreen Button', () => {
expect(wrapper.find({ iconName: 'fullscreen' })).to.have.length(1);
});
})
describe('Add Button', () => {
const { props: { addSlide, goToSlide }, wrapper } = setup();
const addButton = wrapper.find({ iconName: 'add' });
afterEach(() => {
addSlide.reset();
goToSlide.reset();
});
it('should call addSlide when clicked', () => {
for (let i = 0; i < CLICKS; i++) {
addButton.simulate('click');
expect(addSlide.callCount).to.equal(i + 1);
}
});
it('should call goToSlide when clicked', () => {
for (let i = 0; i < CLICKS; i++) {
addButton.simulate('click');
expect(goToSlide.callCount).to.equal(i + 1);
}
});
});
describe('FullScreen Button', () => {
const { props: { saveLastSlideDimensions, toggleFullScreen }, wrapper } = setup();
const fullScreenButton = wrapper.find({ iconName: 'fullscreen' });
afterEach(() => {
saveLastSlideDimensions.reset();
toggleFullScreen.reset();
});
it('should call saveLastSlideDimensions when clicked', () => {
for (let i = 0; i < CLICKS; i++) {
fullScreenButton.simulate('click');
expect(saveLastSlideDimensions.callCount).to.equal(i + 1);
}
});
it('should call toggleFullScreen when clicked', () => {
for(let i = 0; i < CLICKS; i++) {
fullScreenButton.simulate('click');
expect(toggleFullScreen.callCount).to.equal(i + 1);
}
});
});
}); | Add test for <ControlPanel /> | test: Add test for <ControlPanel />
| TypeScript | mit | chengsieuly/devdecks,chengsieuly/devdecks,DevDecks/devdecks,DevDecks/devdecks,Team-CHAD/DevDecks,chengsieuly/devdecks,Team-CHAD/DevDecks,DevDecks/devdecks,Team-CHAD/DevDecks | ---
+++
@@ -0,0 +1,89 @@
+import * as React from 'react';
+import * as sinon from 'sinon';
+import { expect } from 'chai';
+import { shallow } from 'enzyme';
+import { ControlPanelComponent } from '../../app/modules/ControlPanel/ControlPanel';
+
+function setup() {
+ const props = {
+ currentSlide: 0,
+ numberOfSlides: 3,
+ addSlide: sinon.spy(() => {}),
+ goToSlide: sinon.spy(() => {}),
+ saveLastSlideDimensions: sinon.spy(() => {}),
+ toggleFullScreen: sinon.spy(() => {}),
+ };
+
+ const wrapper = shallow(<ControlPanelComponent {...props} />);
+
+ return { props, wrapper };
+}
+
+describe('<ControlPanel />', () => {
+ const CLICKS = 3;
+
+ describe('Self', () => {
+ const { wrapper } = setup();
+
+ it('should render two <Button /> components', () => {
+ expect(wrapper.find('Button')).to.have.length(2);
+ });
+
+ it('should render one Add Button', () => {
+ expect(wrapper.find({ iconName: 'add' })).to.have.length(1);
+ });
+
+ it('should render one FullScreen Button', () => {
+ expect(wrapper.find({ iconName: 'fullscreen' })).to.have.length(1);
+ });
+ })
+
+ describe('Add Button', () => {
+ const { props: { addSlide, goToSlide }, wrapper } = setup();
+
+ const addButton = wrapper.find({ iconName: 'add' });
+
+ afterEach(() => {
+ addSlide.reset();
+ goToSlide.reset();
+ });
+
+ it('should call addSlide when clicked', () => {
+ for (let i = 0; i < CLICKS; i++) {
+ addButton.simulate('click');
+ expect(addSlide.callCount).to.equal(i + 1);
+ }
+ });
+
+ it('should call goToSlide when clicked', () => {
+ for (let i = 0; i < CLICKS; i++) {
+ addButton.simulate('click');
+ expect(goToSlide.callCount).to.equal(i + 1);
+ }
+ });
+ });
+
+ describe('FullScreen Button', () => {
+ const { props: { saveLastSlideDimensions, toggleFullScreen }, wrapper } = setup();
+ const fullScreenButton = wrapper.find({ iconName: 'fullscreen' });
+
+ afterEach(() => {
+ saveLastSlideDimensions.reset();
+ toggleFullScreen.reset();
+ });
+
+ it('should call saveLastSlideDimensions when clicked', () => {
+ for (let i = 0; i < CLICKS; i++) {
+ fullScreenButton.simulate('click');
+ expect(saveLastSlideDimensions.callCount).to.equal(i + 1);
+ }
+ });
+
+ it('should call toggleFullScreen when clicked', () => {
+ for(let i = 0; i < CLICKS; i++) {
+ fullScreenButton.simulate('click');
+ expect(toggleFullScreen.callCount).to.equal(i + 1);
+ }
+ });
+ });
+}); |
|
ce45813ce594495171ada31f62fcbf446ebb335b | server/apollo/src/core/transfer.ts | server/apollo/src/core/transfer.ts | import { Account } from "./account";
import { Balance } from "./balance";
import { Month } from "./month";
export interface Transfer {
fromAccount: Account;
toAccount: Account;
fromMonth: Month;
toMonth: Month;
description: string;
balace: Balance;
} | Add missing definition of Transfer. | Add missing definition of Transfer.
| TypeScript | apache-2.0 | cherba29/tally,cherba29/tally,cherba29/tally,cherba29/tally | ---
+++
@@ -0,0 +1,12 @@
+import { Account } from "./account";
+import { Balance } from "./balance";
+import { Month } from "./month";
+
+export interface Transfer {
+ fromAccount: Account;
+ toAccount: Account;
+ fromMonth: Month;
+ toMonth: Month;
+ description: string;
+ balace: Balance;
+} |
|
0bd78503b9d90ecc0250fabc8423c006a30c9fe3 | packages/@sanity/field/src/utils/useHover.ts | packages/@sanity/field/src/utils/useHover.ts | import {useState, useRef, useEffect} from 'react'
export function useHover<T extends HTMLElement>(): [React.MutableRefObject<T | null>, boolean] {
const [value, setValue] = useState(false)
const ref = useRef<T | null>(null)
const handleMouseOver = () => setValue(true)
const handleMouseOut = () => setValue(false)
useEffect(() => {
const node = ref.current
if (!node) {
return () => undefined
}
node.addEventListener('mouseover', handleMouseOver)
node.addEventListener('mouseout', handleMouseOut)
return () => {
node.removeEventListener('mouseover', handleMouseOver)
node.removeEventListener('mouseout', handleMouseOut)
}
}, [ref.current])
return [ref, value]
}
| Fix nesting of fields in change list | [field] Fix nesting of fields in change list
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -0,0 +1,27 @@
+import {useState, useRef, useEffect} from 'react'
+
+export function useHover<T extends HTMLElement>(): [React.MutableRefObject<T | null>, boolean] {
+ const [value, setValue] = useState(false)
+
+ const ref = useRef<T | null>(null)
+
+ const handleMouseOver = () => setValue(true)
+ const handleMouseOut = () => setValue(false)
+
+ useEffect(() => {
+ const node = ref.current
+ if (!node) {
+ return () => undefined
+ }
+
+ node.addEventListener('mouseover', handleMouseOver)
+ node.addEventListener('mouseout', handleMouseOut)
+
+ return () => {
+ node.removeEventListener('mouseover', handleMouseOver)
+ node.removeEventListener('mouseout', handleMouseOut)
+ }
+ }, [ref.current])
+
+ return [ref, value]
+} |
|
2ab033755b0756de6c95be0ce3da97abfcf0dc50 | spec/components/errormessageoverlay.spec.ts | spec/components/errormessageoverlay.spec.ts | import { UIInstanceManager } from './../../src/ts/uimanager';
import { ErrorMessageOverlay } from '../../src/ts/components/errormessageoverlay';
import { MobileV3PlayerEvent } from '../../src/ts/mobilev3playerapi';
import { MockHelper, TestingPlayerAPI } from '../helper/MockHelper';
describe('ErrorMessageOverlay', () => {
describe('configure', () => {
let errorMessageOverlay: ErrorMessageOverlay;
let playerMock: TestingPlayerAPI;
let uiInstanceManagerMock: UIInstanceManager;
beforeEach(() => {
errorMessageOverlay = new ErrorMessageOverlay({});
playerMock = MockHelper.getPlayerMock();
uiInstanceManagerMock = MockHelper.getUiInstanceManagerMock();
});
it('should add event listener for source loaded event', () => {
const onSpy = jest.spyOn(playerMock, 'on');
errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
expect(onSpy).toHaveBeenCalledWith(playerMock.exports.PlayerEvent.SourceLoaded, expect.any(Function));
});
it('should add event listener for error event when not mobile v3', () => {
const onSpy = jest.spyOn(playerMock, 'on');
errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
expect(onSpy).toHaveBeenCalledWith(playerMock.exports.PlayerEvent.Error, expect.any(Function));
});
describe('mobile v3 handling', () => {
let onSpy: jest.SpyInstance;
beforeEach(() => {
onSpy = jest.spyOn(playerMock, 'on');
(playerMock.exports.PlayerEvent as any).SourceError = MobileV3PlayerEvent.SourceError;
(playerMock.exports.PlayerEvent as any).PlayerError = MobileV3PlayerEvent.PlayerError;
(playerMock.exports.PlayerEvent as any).PlaylistTransition = MobileV3PlayerEvent.PlaylistTransition;
});
it('should add event listener for sourceerror and playererror when mobile v3', () => {
errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.PlayerError, expect.any(Function));
expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.SourceError, expect.any(Function));
});
it('should use message from the error event when mobile v3', () => {
const setTextSpy = jest.spyOn(errorMessageOverlay['errorLabel'], 'setText');
errorMessageOverlay['tvNoiseBackground'] = { start: () => {} } as any;
errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
const playerErrorEvent = {
type: MobileV3PlayerEvent.PlayerError,
message: 'this is a player error',
name: 'playererror',
};
playerMock.eventEmitter.fireEvent<any>(playerErrorEvent);
expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.PlayerError, expect.any(Function));
expect(setTextSpy).toHaveBeenCalledWith(`${playerErrorEvent.message}\n(${playerErrorEvent.name})`);
});
});
});
});
| Add unit test for ErrorMessageOverlay class | Add unit test for ErrorMessageOverlay class
| TypeScript | mit | bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui,bitmovin/bitmovin-player-ui | ---
+++
@@ -0,0 +1,69 @@
+import { UIInstanceManager } from './../../src/ts/uimanager';
+import { ErrorMessageOverlay } from '../../src/ts/components/errormessageoverlay';
+import { MobileV3PlayerEvent } from '../../src/ts/mobilev3playerapi';
+import { MockHelper, TestingPlayerAPI } from '../helper/MockHelper';
+
+describe('ErrorMessageOverlay', () => {
+ describe('configure', () => {
+ let errorMessageOverlay: ErrorMessageOverlay;
+ let playerMock: TestingPlayerAPI;
+ let uiInstanceManagerMock: UIInstanceManager;
+
+ beforeEach(() => {
+ errorMessageOverlay = new ErrorMessageOverlay({});
+ playerMock = MockHelper.getPlayerMock();
+ uiInstanceManagerMock = MockHelper.getUiInstanceManagerMock();
+ });
+
+ it('should add event listener for source loaded event', () => {
+ const onSpy = jest.spyOn(playerMock, 'on');
+ errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
+
+ expect(onSpy).toHaveBeenCalledWith(playerMock.exports.PlayerEvent.SourceLoaded, expect.any(Function));
+ });
+
+ it('should add event listener for error event when not mobile v3', () => {
+ const onSpy = jest.spyOn(playerMock, 'on');
+ errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
+
+ expect(onSpy).toHaveBeenCalledWith(playerMock.exports.PlayerEvent.Error, expect.any(Function));
+ });
+
+ describe('mobile v3 handling', () => {
+ let onSpy: jest.SpyInstance;
+
+ beforeEach(() => {
+ onSpy = jest.spyOn(playerMock, 'on');
+
+ (playerMock.exports.PlayerEvent as any).SourceError = MobileV3PlayerEvent.SourceError;
+ (playerMock.exports.PlayerEvent as any).PlayerError = MobileV3PlayerEvent.PlayerError;
+ (playerMock.exports.PlayerEvent as any).PlaylistTransition = MobileV3PlayerEvent.PlaylistTransition;
+ });
+
+ it('should add event listener for sourceerror and playererror when mobile v3', () => {
+ errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
+
+ expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.PlayerError, expect.any(Function));
+ expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.SourceError, expect.any(Function));
+ });
+
+ it('should use message from the error event when mobile v3', () => {
+ const setTextSpy = jest.spyOn(errorMessageOverlay['errorLabel'], 'setText');
+
+ errorMessageOverlay['tvNoiseBackground'] = { start: () => {} } as any;
+
+ errorMessageOverlay.configure(playerMock, uiInstanceManagerMock);
+
+ const playerErrorEvent = {
+ type: MobileV3PlayerEvent.PlayerError,
+ message: 'this is a player error',
+ name: 'playererror',
+ };
+ playerMock.eventEmitter.fireEvent<any>(playerErrorEvent);
+
+ expect(onSpy).toHaveBeenCalledWith(MobileV3PlayerEvent.PlayerError, expect.any(Function));
+ expect(setTextSpy).toHaveBeenCalledWith(`${playerErrorEvent.message}\n(${playerErrorEvent.name})`);
+ });
+ });
+ });
+}); |
|
db1c23f25c3d943bd5c04e04ab26066e536e5384 | cypress/tests/multi-apps.cy.ts | cypress/tests/multi-apps.cy.ts | describe('Hslayers application', () => {
beforeEach(() => {
cy.visit('/multi-apps');
});
it('should display multiple hslayers elements', () => {
cy.get('hslayers').should('have.length', 2);
});
});
| Check if multiple apps can be loaded | test: Check if multiple apps can be loaded
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -0,0 +1,9 @@
+describe('Hslayers application', () => {
+ beforeEach(() => {
+ cy.visit('/multi-apps');
+ });
+
+ it('should display multiple hslayers elements', () => {
+ cy.get('hslayers').should('have.length', 2);
+ });
+}); |
|
f137b3e122354a6e651a65fa2325570a276bc4a9 | types/react-bootstrap/lib/Carousel.d.ts | types/react-bootstrap/lib/Carousel.d.ts | import * as React from 'react';
import { Omit, Sizes, SelectCallback } from 'react-bootstrap';
import CarouselItem = require('./CarouselItem');
import CarouselCaption = require('./CarouselCaption');
declare namespace Carousel {
export type CarouselProps = Omit<React.HTMLProps<Carousel>, 'wrap'> & {
activeIndex?: number;
bsSize?: Sizes;
bsStyle?: string;
controls?: boolean;
defaultActiveIndex?: number;
direction?: string;
indicators?: boolean;
interval?: number;
nextIcon?: React.ReactNode;
onSelect?: SelectCallback;
// TODO: Add more specific type
onSlideEnd?: Function;
pauseOnHover?: boolean;
prevIcon?: React.ReactNode;
slide?: boolean;
wrap?: boolean;
};
}
declare class Carousel extends React.Component<Carousel.CarouselProps> {
public static Caption: typeof CarouselCaption;
public static Item: typeof CarouselItem;
}
export = Carousel;
| import * as React from 'react';
import { Omit, Sizes, SelectCallback } from 'react-bootstrap';
import CarouselItem = require('./CarouselItem');
import CarouselCaption = require('./CarouselCaption');
declare namespace Carousel {
export type CarouselProps = Omit<React.HTMLProps<Carousel>, 'wrap'> & {
activeIndex?: number;
bsSize?: Sizes;
bsStyle?: string;
controls?: boolean;
defaultActiveIndex?: number;
direction?: string;
indicators?: boolean;
interval?: number | null;
nextIcon?: React.ReactNode;
onSelect?: SelectCallback;
// TODO: Add more specific type
onSlideEnd?: Function;
pauseOnHover?: boolean;
prevIcon?: React.ReactNode;
slide?: boolean;
wrap?: boolean;
};
}
declare class Carousel extends React.Component<Carousel.CarouselProps> {
public static Caption: typeof CarouselCaption;
public static Item: typeof CarouselItem;
}
export = Carousel;
| Allow interval prop to be null | react-bootstrap: Allow interval prop to be null
The react-bootstrap docs state that the interval prop on a Carousel can
be null. In this state, a Carousel will not automatically cycle through
its items. Tested locally.
https://react-bootstrap.github.io/components/carousel/#carousels-props-carousel
| TypeScript | mit | AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped | ---
+++
@@ -12,7 +12,7 @@
defaultActiveIndex?: number;
direction?: string;
indicators?: boolean;
- interval?: number;
+ interval?: number | null;
nextIcon?: React.ReactNode;
onSelect?: SelectCallback;
// TODO: Add more specific type |
a9e55e1eee0d1df4fe59d2513067a21e59a5f111 | src/classes/angleworms-collision-detector.ts | src/classes/angleworms-collision-detector.ts | import IMap from '../interfaces/map.interface';
import IPlayerCollisionDetectorComponent from '../interfaces/player-collision-detector-component.interface';
import IPlayer from '../interfaces/player.interface';
import MapPosition from '../types/map-position.type';
import Locator from './locator';
export default class AnglewormsCollisionDetectorComponent implements IPlayerCollisionDetectorComponent {
private map: IMap;
public constructor() {
this.map = Locator.getMap();
}
public isSafeToGoLeft(player: IPlayer): boolean {
const nextPosition: MapPosition = {
x: player.getHead().getPosition().x - 2,
y: player.getHead().getPosition().y,
};
return (this.map.getMapItemsAt(nextPosition).length === 0);
}
public isSafeToGoUp(player: IPlayer): boolean {
const nextPosition: MapPosition = {
x: player.getHead().getPosition().x,
y: player.getHead().getPosition().y - 2,
};
return (this.map.getMapItemsAt(nextPosition).length === 0);
}
public isSafeToGoRight(player: IPlayer): boolean {
const nextPosition: MapPosition = {
x: player.getHead().getPosition().x + 2,
y: player.getHead().getPosition().y,
};
return (this.map.getMapItemsAt(nextPosition).length === 0);
}
public isSafeToGoDown(player: IPlayer): boolean {
const nextPosition: MapPosition = {
x: player.getHead().getPosition().x,
y: player.getHead().getPosition().y + 2,
};
return (this.map.getMapItemsAt(nextPosition).length === 0);
}
public isSafeNotToChangeDirection(player: IPlayer): boolean {
const nextPosition: MapPosition = {
x: player.getHead().getPosition().x + 2 * player.getVelocity().x,
y: player.getHead().getPosition().y + 2 * player.getVelocity().y,
};
return (this.map.getMapItemsAt(nextPosition).length === 0);
}
}
| Add Angleworms II style collisions detection. | Add Angleworms II style collisions detection.
| TypeScript | isc | kamsac/angleworms-game,kamsac/angleworms-game | ---
+++
@@ -0,0 +1,58 @@
+import IMap from '../interfaces/map.interface';
+import IPlayerCollisionDetectorComponent from '../interfaces/player-collision-detector-component.interface';
+import IPlayer from '../interfaces/player.interface';
+import MapPosition from '../types/map-position.type';
+import Locator from './locator';
+
+export default class AnglewormsCollisionDetectorComponent implements IPlayerCollisionDetectorComponent {
+ private map: IMap;
+
+ public constructor() {
+ this.map = Locator.getMap();
+ }
+
+ public isSafeToGoLeft(player: IPlayer): boolean {
+ const nextPosition: MapPosition = {
+ x: player.getHead().getPosition().x - 2,
+ y: player.getHead().getPosition().y,
+ };
+
+ return (this.map.getMapItemsAt(nextPosition).length === 0);
+ }
+
+ public isSafeToGoUp(player: IPlayer): boolean {
+ const nextPosition: MapPosition = {
+ x: player.getHead().getPosition().x,
+ y: player.getHead().getPosition().y - 2,
+ };
+
+ return (this.map.getMapItemsAt(nextPosition).length === 0);
+ }
+
+ public isSafeToGoRight(player: IPlayer): boolean {
+ const nextPosition: MapPosition = {
+ x: player.getHead().getPosition().x + 2,
+ y: player.getHead().getPosition().y,
+ };
+
+ return (this.map.getMapItemsAt(nextPosition).length === 0);
+ }
+
+ public isSafeToGoDown(player: IPlayer): boolean {
+ const nextPosition: MapPosition = {
+ x: player.getHead().getPosition().x,
+ y: player.getHead().getPosition().y + 2,
+ };
+
+ return (this.map.getMapItemsAt(nextPosition).length === 0);
+ }
+
+ public isSafeNotToChangeDirection(player: IPlayer): boolean {
+ const nextPosition: MapPosition = {
+ x: player.getHead().getPosition().x + 2 * player.getVelocity().x,
+ y: player.getHead().getPosition().y + 2 * player.getVelocity().y,
+ };
+
+ return (this.map.getMapItemsAt(nextPosition).length === 0);
+ }
+} |
|
19f932748efcb2eb257be979e9705769623b18b8 | myFirstApps/src/app/class/auth.service.spec.ts | myFirstApps/src/app/class/auth.service.spec.ts | import { AuthService } from './auth.service';
describe('Testing for AuthService Class', ()=>{
let service : AuthService;
beforeEach(()=>{
service = new AuthService();
});
afterEach(()=>{
service = null;
localStorage.removeItem('token');
})
it('should return true from isAuthenticated when localStorage have a token', ()=>{
localStorage.setItem('token', '1234');
expect(service.isAuthenticated()).toBeTruthy(); // expect true
})
it('should return false from isAUthenticated when not have a token', ()=> {
expect(service.isAuthenticated()).toBeFalsy(); // expect false
});
}); | Add unit test for AuthService class | Add unit test for AuthService class
| TypeScript | mit | fedorax/angular-basic,fedorax/angular-basic,fedorax/angular-basic | ---
+++
@@ -0,0 +1,23 @@
+import { AuthService } from './auth.service';
+
+describe('Testing for AuthService Class', ()=>{
+ let service : AuthService;
+
+ beforeEach(()=>{
+ service = new AuthService();
+ });
+
+ afterEach(()=>{
+ service = null;
+ localStorage.removeItem('token');
+ })
+
+ it('should return true from isAuthenticated when localStorage have a token', ()=>{
+ localStorage.setItem('token', '1234');
+ expect(service.isAuthenticated()).toBeTruthy(); // expect true
+ })
+
+ it('should return false from isAUthenticated when not have a token', ()=> {
+ expect(service.isAuthenticated()).toBeFalsy(); // expect false
+ });
+}); |
|
4f448a6ceefd850656ef35f5956ff59e21b860eb | ui/src/shared/components/SourceIndicator.tsx | ui/src/shared/components/SourceIndicator.tsx | import React, {SFC} from 'react'
import PropTypes from 'prop-types'
import _ from 'lodash'
import uuid from 'uuid'
import ReactTooltip from 'react-tooltip'
import {Source} from 'src/types'
interface Props {
sourceOverride?: Source
}
const SourceIndicator: SFC<Props> = (
{sourceOverride},
{source: {name, url}}
) => {
const sourceName: string = _.get(sourceOverride, 'name', name)
const sourceUrl: string = _.get(sourceOverride, 'url', url)
const sourceNameTooltip: string = `<h1>Connected to Source:</h1><p><code>${sourceName} @ ${sourceUrl}</code></p>`
const uuidTooltip: string = uuid.v4()
return sourceName ? (
<div
className="source-indicator"
data-for={uuidTooltip}
data-tip={sourceNameTooltip}
>
<span className="icon disks" />
<ReactTooltip
id={uuidTooltip}
effect="solid"
html={true}
place="left"
class="influx-tooltip"
/>
</div>
) : null
}
const {shape} = PropTypes
SourceIndicator.contextTypes = {
source: shape({}),
}
export default SourceIndicator
| import React, {SFC} from 'react'
import PropTypes from 'prop-types'
import _ from 'lodash'
import uuid from 'uuid'
import ReactTooltip from 'react-tooltip'
import {Source} from 'src/types'
interface Props {
sourceOverride?: Source
}
const SourceIndicator: SFC<Props> = ({sourceOverride}, {source}) => {
if (!source) {
return null
}
const {name, url} = source
const sourceName: string = _.get(sourceOverride, 'name', name)
const sourceUrl: string = _.get(sourceOverride, 'url', url)
const sourceNameTooltip: string = `<h1>Connected to Source:</h1><p><code>${sourceName} @ ${sourceUrl}</code></p>`
const uuidTooltip: string = uuid.v4()
return (
<div
className="source-indicator"
data-for={uuidTooltip}
data-tip={sourceNameTooltip}
>
<span className="icon disks" />
<ReactTooltip
id={uuidTooltip}
effect="solid"
html={true}
place="left"
class="influx-tooltip"
/>
</div>
)
}
const {shape} = PropTypes
SourceIndicator.contextTypes = {
source: shape({}),
}
export default SourceIndicator
| Refactor component to guard against missing context | Refactor component to guard against missing context
| TypeScript | mit | nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb | ---
+++
@@ -11,16 +11,19 @@
sourceOverride?: Source
}
-const SourceIndicator: SFC<Props> = (
- {sourceOverride},
- {source: {name, url}}
-) => {
+const SourceIndicator: SFC<Props> = ({sourceOverride}, {source}) => {
+ if (!source) {
+ return null
+ }
+
+ const {name, url} = source
const sourceName: string = _.get(sourceOverride, 'name', name)
const sourceUrl: string = _.get(sourceOverride, 'url', url)
+
const sourceNameTooltip: string = `<h1>Connected to Source:</h1><p><code>${sourceName} @ ${sourceUrl}</code></p>`
const uuidTooltip: string = uuid.v4()
- return sourceName ? (
+ return (
<div
className="source-indicator"
data-for={uuidTooltip}
@@ -35,7 +38,7 @@
class="influx-tooltip"
/>
</div>
- ) : null
+ )
}
const {shape} = PropTypes |
cd2708fb0e8a0e3b820c5a6146d842625ba022cf | server/libs/api/quiz-functions.ts | server/libs/api/quiz-functions.ts | ///<reference path="../../../typings/globals/shuffle-array/index.d.ts"/>
import * as shuffleArray from "shuffle-array";
export class QuizFunctions {
count: number;
temp = 0;
all = new Array();
all2 = new Array();
constructor(jsonval) {
let question = new Array();
let time = new Array();
for (var i = 0; i < jsonval.data.length; i++) {
question.push(jsonval.data[i].id);
time.push(jsonval.data[i].question_time);
this.all.push([question[i], time[i]]);
}
}
makeQuestionRandomArray() {
shuffleArray(this.all);
// console.log(this.all);
}
makeTime() {
let question = new Array();
let time = new Array();
this.count = 0;
for (var i = 0; i < this.all.length; i++) {
this.temp = parseInt(this.all[i][1]);
if (this.count + this.temp < 15) {
this.count = this.count + this.temp;
question.push(this.all[i]);
time.push(this.all[i][1]);
this.all2.push(this.all[i][0]);
}
}
return this.all2;
}
}
| Add time based question loading algorithm | Add time based question loading algorithm
| TypeScript | mit | shavindraSN/examen,shavindraSN/examen,shavindraSN/examen | ---
+++
@@ -0,0 +1,43 @@
+///<reference path="../../../typings/globals/shuffle-array/index.d.ts"/>
+import * as shuffleArray from "shuffle-array";
+
+export class QuizFunctions {
+ count: number;
+ temp = 0;
+ all = new Array();
+ all2 = new Array();
+
+ constructor(jsonval) {
+ let question = new Array();
+ let time = new Array();
+
+ for (var i = 0; i < jsonval.data.length; i++) {
+ question.push(jsonval.data[i].id);
+ time.push(jsonval.data[i].question_time);
+ this.all.push([question[i], time[i]]);
+ }
+ }
+
+ makeQuestionRandomArray() {
+ shuffleArray(this.all);
+ // console.log(this.all);
+ }
+
+ makeTime() {
+ let question = new Array();
+ let time = new Array();
+ this.count = 0;
+
+ for (var i = 0; i < this.all.length; i++) {
+ this.temp = parseInt(this.all[i][1]);
+
+ if (this.count + this.temp < 15) {
+ this.count = this.count + this.temp;
+ question.push(this.all[i]);
+ time.push(this.all[i][1]);
+ this.all2.push(this.all[i][0]);
+ }
+ }
+ return this.all2;
+ }
+} |
|
569b304e794dfab0aefd5d837e88c42f3180faa8 | build/server/server.env=node.ts | build/server/server.env=node.ts | class $mol_build_server extends $mol_server {
expressGenerator() {
return ( req : any , res : any , next : () => void )=> {
try {
return this.generator( req.url ) || next()
} catch( error ) {
$mol_atom_restore( error )
throw error
}
}
}
build() : $mol_build {
return null
}
@ $mol_prop()
generator( path : string ) {
var matched = path.match( /^((?:\/\w+)+)\/-\/(\w+(?:.\w+)+)$/ )
if( !matched ) return null
var build = this.build()
var [ path , path , bundle ] = matched
path = build.root().resolve( path ).path()
build.bundle({ path , bundle })
return <void> null
}
port() {
return 80
}
}
| class $mol_build_server extends $mol_server {
expressGenerator() {
return ( req : any , res : any , next : () => void )=> {
try {
return this.generator( req.url ) || next()
} catch( error ) {
$mol_atom_restore( error )
if( req.url.match( /\.js$/ ) ) {
console.error( error )
res.send( `console.error( ${ JSON.stringify( error.message ) } )` ).end()
} else {
throw error
}
}
}
}
build() : $mol_build {
return null
}
@ $mol_prop()
generator( path : string ) {
var matched = path.match( /^((?:\/\w+)+)\/-\/(\w+(?:.\w+)+)$/ )
if( !matched ) return null
var build = this.build()
var [ path , path , bundle ] = matched
path = build.root().resolve( path ).path()
build.bundle({ path , bundle })
return <void> null
}
port() {
return 80
}
}
| Print errors in js building to browser console. | Print errors in js building to browser console.
| TypeScript | mit | nin-jin/mol,eigenmethod/mol,nin-jin/mol,eigenmethod/mol,eigenmethod/mol,nin-jin/mol | ---
+++
@@ -6,7 +6,12 @@
return this.generator( req.url ) || next()
} catch( error ) {
$mol_atom_restore( error )
- throw error
+ if( req.url.match( /\.js$/ ) ) {
+ console.error( error )
+ res.send( `console.error( ${ JSON.stringify( error.message ) } )` ).end()
+ } else {
+ throw error
+ }
}
}
} |
5d99b4fcd51f1a6b7b447aad00678cfc00e9ae42 | src/core/assert.ts | src/core/assert.ts | /**
* Specialized type of error to easily identify exceptions originated in `assert()` expressions.
*/
export class AssertionError extends Error {}
/**
* Ensure that any given condition is true, adding basic support for design-by-contract pgoramming.
*
* When providing a function as opposed to a boolean as the first argument, the source code of the function will be
* included as part of the error message in case of failure, thus providing immediate feedback to help determine the
* the reason the assertion did not hold true.
*/
export function assert(assertion: boolean | (() => boolean), message: string = '') {
const assertionIsFunction = typeof assertion === 'function'
const ok = assertionIsFunction
? (assertion as () => boolean)()
: assertion
if (!ok) {
if (assertionIsFunction) {
message += ' | Assertion was: ' + assertion.toString()
}
throw new AssertionError(message)
}
} | Add basic support for contract programming | Add basic support for contract programming
| TypeScript | agpl-3.0 | inad9300/Soil,inad9300/Soil | ---
+++
@@ -0,0 +1,26 @@
+/**
+ * Specialized type of error to easily identify exceptions originated in `assert()` expressions.
+ */
+export class AssertionError extends Error {}
+
+/**
+ * Ensure that any given condition is true, adding basic support for design-by-contract pgoramming.
+ *
+ * When providing a function as opposed to a boolean as the first argument, the source code of the function will be
+ * included as part of the error message in case of failure, thus providing immediate feedback to help determine the
+ * the reason the assertion did not hold true.
+ */
+export function assert(assertion: boolean | (() => boolean), message: string = '') {
+ const assertionIsFunction = typeof assertion === 'function'
+
+ const ok = assertionIsFunction
+ ? (assertion as () => boolean)()
+ : assertion
+
+ if (!ok) {
+ if (assertionIsFunction) {
+ message += ' | Assertion was: ' + assertion.toString()
+ }
+ throw new AssertionError(message)
+ }
+} |
|
d0240ed204a02a5cd006295c3fa24b90bee75bf4 | test/reducers/slides/actions/moveSlideUp-spec.ts | test/reducers/slides/actions/moveSlideUp-spec.ts | import { expect } from 'chai';
import { MOVE_SLIDE_UP } from '../../../../app/constants/slides.constants';
export default function(initialState: any, reducer: any, slide: any) {
const dummySlide1 = {
plugins: ['plugin1'],
state: {
backgroundColor: { r: 255, g: 255, b: 255, a: 100 },
transition: {
right: 'rotate-push-left-move-from-right',
left: 'rotate-push-right-move-from-left',
}
}
};
describe('MOVE_SLIDE_UP', () => {
const _initialState = [slide, dummySlide1];
it('should not move the slide when the last slide is selected', () => {
expect(
reducer(_initialState, {
type: MOVE_SLIDE_UP,
slideNumber: 1
})
).to.deep.equal(_initialState);
});
it('should swap slide 0 and slide 1 when slide 0 is active', () => {
expect(
reducer(_initialState, {
type: MOVE_SLIDE_UP,
slideNumber: 0
})
).to.deep.equal([dummySlide1, slide]);
});
});
}
| Add test for MOVE_SLIDE_UP on slides reducer | test: Add test for MOVE_SLIDE_UP on slides reducer
| TypeScript | mit | DevDecks/devdecks,DevDecks/devdecks,DevDecks/devdecks,chengsieuly/devdecks,chengsieuly/devdecks,Team-CHAD/DevDecks,chengsieuly/devdecks,Team-CHAD/DevDecks,Team-CHAD/DevDecks | ---
+++
@@ -0,0 +1,36 @@
+import { expect } from 'chai';
+import { MOVE_SLIDE_UP } from '../../../../app/constants/slides.constants';
+
+export default function(initialState: any, reducer: any, slide: any) {
+ const dummySlide1 = {
+ plugins: ['plugin1'],
+ state: {
+ backgroundColor: { r: 255, g: 255, b: 255, a: 100 },
+ transition: {
+ right: 'rotate-push-left-move-from-right',
+ left: 'rotate-push-right-move-from-left',
+ }
+ }
+ };
+
+ describe('MOVE_SLIDE_UP', () => {
+ const _initialState = [slide, dummySlide1];
+ it('should not move the slide when the last slide is selected', () => {
+ expect(
+ reducer(_initialState, {
+ type: MOVE_SLIDE_UP,
+ slideNumber: 1
+ })
+ ).to.deep.equal(_initialState);
+ });
+
+ it('should swap slide 0 and slide 1 when slide 0 is active', () => {
+ expect(
+ reducer(_initialState, {
+ type: MOVE_SLIDE_UP,
+ slideNumber: 0
+ })
+ ).to.deep.equal([dummySlide1, slide]);
+ });
+ });
+} |
|
caa9467d8eadf5169f4239ca58da74a6d88e8993 | app/src/ui/changes/changed-file-details.tsx | app/src/ui/changes/changed-file-details.tsx | import * as React from 'react'
interface IChangedFileDetailsProps {
readonly fileName: string | null
}
export class ChangedFileDetails extends React.Component<IChangedFileDetailsProps, void> {
public render() {
const fullFileName = this.props.fileName ? this.props.fileName : undefined
return (
<div id='changed-file-details'>
{fullFileName}
</div>
)
}
} | Add component to display file details | Add component to display file details
Currently displays the file name, but no reason this cannot be expanded to display additional info.
| TypeScript | mit | hjobrien/desktop,BugTesterTest/desktops,shiftkey/desktop,BugTesterTest/desktops,BugTesterTest/desktops,gengjiawen/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,hjobrien/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,gengjiawen/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,gengjiawen/desktop,say25/desktop,artivilla/desktop,hjobrien/desktop,j-f1/forked-desktop,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,desktop/desktop | ---
+++
@@ -0,0 +1,17 @@
+import * as React from 'react'
+
+interface IChangedFileDetailsProps {
+ readonly fileName: string | null
+}
+
+export class ChangedFileDetails extends React.Component<IChangedFileDetailsProps, void> {
+ public render() {
+ const fullFileName = this.props.fileName ? this.props.fileName : undefined
+
+ return (
+ <div id='changed-file-details'>
+ {fullFileName}
+ </div>
+ )
+ }
+} |
|
8b5bece6c7a1cefb09a5601dcd87944e91e0dfff | saleor/static/dashboard-next/components/Debounce.tsx | saleor/static/dashboard-next/components/Debounce.tsx | import * as React from "react";
export interface DebounceProps {
children: ((props: () => void) => React.ReactNode);
debounceFn: (event: React.FormEvent<any>) => void;
time?: number;
}
export class Debounce extends React.Component<DebounceProps> {
timer = null;
handleDebounce = () => {
const { debounceFn, time } = this.props;
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(debounceFn, time || 200);
};
render() {
return this.props.children(this.handleDebounce);
}
}
export default Debounce;
| import * as React from "react";
export interface DebounceProps<T> {
children: ((props: (...args: T[]) => void) => React.ReactNode);
debounceFn: (...args: T[]) => void;
time?: number;
}
export class Debounce<T> extends React.Component<DebounceProps<T>> {
timer = null;
handleDebounce = (...args: T[]) => {
const { debounceFn, time } = this.props;
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => debounceFn(...args), time || 200);
};
render() {
return this.props.children(this.handleDebounce);
}
}
export default Debounce;
| Improve debounce types and pass function parameters | Improve debounce types and pass function parameters
| TypeScript | bsd-3-clause | maferelo/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,mociepka/saleor | ---
+++
@@ -1,20 +1,20 @@
import * as React from "react";
-export interface DebounceProps {
- children: ((props: () => void) => React.ReactNode);
- debounceFn: (event: React.FormEvent<any>) => void;
+export interface DebounceProps<T> {
+ children: ((props: (...args: T[]) => void) => React.ReactNode);
+ debounceFn: (...args: T[]) => void;
time?: number;
}
-export class Debounce extends React.Component<DebounceProps> {
+export class Debounce<T> extends React.Component<DebounceProps<T>> {
timer = null;
- handleDebounce = () => {
+ handleDebounce = (...args: T[]) => {
const { debounceFn, time } = this.props;
if (this.timer) {
clearTimeout(this.timer);
}
- this.timer = setTimeout(debounceFn, time || 200);
+ this.timer = setTimeout(() => debounceFn(...args), time || 200);
};
render() { |
1ebaf394eebe2b043af9769f3aef8f550af2352b | src/utils/creepPartCosts.ts | src/utils/creepPartCosts.ts | // Body part Build cost Effect per one body part
export const CreepPartMatrix: { [index: string]: number } = {
ATTACK: 80,
CARRY: 50,
CLAIM: 600,
HEAL: 250,
MOVE: 50,
RANGED_ATTACK: 150,
TOUGH: 10,
WORK: 100,
};
| Add costs matrix for creep parts | Add costs matrix for creep parts
| TypeScript | unlicense | ABitMoreDepth/screeps,ABitMoreDepth/screeps | ---
+++
@@ -0,0 +1,11 @@
+// Body part Build cost Effect per one body part
+export const CreepPartMatrix: { [index: string]: number } = {
+ ATTACK: 80,
+ CARRY: 50,
+ CLAIM: 600,
+ HEAL: 250,
+ MOVE: 50,
+ RANGED_ATTACK: 150,
+ TOUGH: 10,
+ WORK: 100,
+}; |
|
5dacd118f2ad04098fcdeff833f111b89a925307 | packages/safe-tools-subgraph/src/utils.ts | packages/safe-tools-subgraph/src/utils.ts | import { crypto, ByteArray, Address } from '@graphprotocol/graph-ts';
export function toChecksumAddress(address: Address): string {
let lowerCaseAddress = address.toHex().slice(2);
let hash = crypto
.keccak256(ByteArray.fromUTF8(address.toHex().slice(2)))
.toHex()
.slice(2);
let result = '';
for (let i = 0; i < lowerCaseAddress.length; i++) {
if (parseInt(hash.charAt(i), 16) >= 8) {
result += toUpper(lowerCaseAddress.charAt(i));
} else {
result += lowerCaseAddress.charAt(i);
}
}
return toHex(result);
}
function toUpper(str: string): string {
let result = '';
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
// only operate on lowercase 'a' thru lower case 'z'
if (charCode >= 97 && charCode <= 122) {
result += String.fromCharCode(charCode - 32);
} else {
result += str.charAt(i);
}
}
return result;
}
export function toHex(bytes: string): string {
return '0x' + bytes;
}
| Copy toChecksumAddress util from cardpay-subgraph | Copy toChecksumAddress util from cardpay-subgraph
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -0,0 +1,38 @@
+import { crypto, ByteArray, Address } from '@graphprotocol/graph-ts';
+
+export function toChecksumAddress(address: Address): string {
+ let lowerCaseAddress = address.toHex().slice(2);
+ let hash = crypto
+ .keccak256(ByteArray.fromUTF8(address.toHex().slice(2)))
+ .toHex()
+ .slice(2);
+ let result = '';
+
+ for (let i = 0; i < lowerCaseAddress.length; i++) {
+ if (parseInt(hash.charAt(i), 16) >= 8) {
+ result += toUpper(lowerCaseAddress.charAt(i));
+ } else {
+ result += lowerCaseAddress.charAt(i);
+ }
+ }
+
+ return toHex(result);
+}
+
+function toUpper(str: string): string {
+ let result = '';
+ for (let i = 0; i < str.length; i++) {
+ let charCode = str.charCodeAt(i);
+ // only operate on lowercase 'a' thru lower case 'z'
+ if (charCode >= 97 && charCode <= 122) {
+ result += String.fromCharCode(charCode - 32);
+ } else {
+ result += str.charAt(i);
+ }
+ }
+ return result;
+}
+
+export function toHex(bytes: string): string {
+ return '0x' + bytes;
+} |
|
608b813626754f878e759926db6bef91549e9999 | app/pages/login/login.component.ts | app/pages/login/login.component.ts | import {Component} from "angular2/core";
import {Router} from "angular2/router";
import {User} from "../../shared/user/user";
import {UserService} from "../../shared/user/user.service";
@Component({
selector: "login",
templateUrl: "pages/login/login.html",
providers: [UserService]
})
export class LoginPage {
user: User;
constructor(
private _router: Router,
private _userService: UserService) {
this.user = new User();
// Hardcode a few values to make testing easy
this.user.email = "[email protected]";
this.user.password = "password";
}
signIn() {
this._userService.login(this.user)
.subscribe(
() => this._router.navigate(["List"]),
(error) => alert(error)
);
}
register() {
this._router.navigate(["Register"]);
}
}
| import {Component} from "angular2/core";
import {Router} from "angular2/router";
import {User} from "../../shared/user/user";
import {UserService} from "../../shared/user/user.service";
@Component({
selector: "login",
templateUrl: "pages/login/login.html",
providers: [UserService]
})
export class LoginPage {
user: User;
constructor(
private _router: Router,
private _userService: UserService) {
this.user = new User();
// Hardcode a few values to make testing easy
this.user.email = "[email protected]";
this.user.password = "password";
}
signIn() {
this._userService.login(this.user)
.subscribe(
() => this._router.navigate(["List"]),
(error) => alert("Unfortunately we could not find your account.")
);
}
register() {
this._router.navigate(["Register"]);
}
}
| Use a better error message | Use a better error message
| TypeScript | mit | anhoev/cms-mobile,poly-mer/community,NativeScript/sample-Groceries,poly-mer/community,poly-mer/community,qtagtech/nativescript_tutorial,dzfweb/sample-groceries,NativeScript/sample-Groceries,qtagtech/nativescript_tutorial,tjvantoll/sample-Groceries,dzfweb/sample-groceries,tjvantoll/sample-Groceries,qtagtech/nativescript_tutorial,anhoev/cms-mobile,NativeScript/sample-Groceries,tjvantoll/sample-Groceries,anhoev/cms-mobile,dzfweb/sample-groceries,Icenium/nativescript-sample-groceries | ---
+++
@@ -27,7 +27,7 @@
this._userService.login(this.user)
.subscribe(
() => this._router.navigate(["List"]),
- (error) => alert(error)
+ (error) => alert("Unfortunately we could not find your account.")
);
}
|
74b5b43706136f7dfe7fa51c71474b148213e424 | chain-of-responsibility/solve-problem.ts | chain-of-responsibility/solve-problem.ts | class Trouble {
private number: number;
constructor(number: number) {
this.number = number;
}
getNumber(): number {
return this.number;
}
getProblemString(): string {
return `Trouble: ${this.number}`;
}
}
abstract class Support {
private name: string;
private next: Support;
constructor(name: string) {
this.name = name;
}
setNext(next: Support): Support {
this.next = next;
return next;
}
support(trouble: Trouble): void {
if (this.resolve(trouble)) {
this.done(trouble);
} else if (this.next != null) {
this.next.support(trouble);
} else {
this.fail(trouble);
}
}
done(trouble: Trouble): void {
console.log(`${trouble.getNumber()} was resolved.`);
}
fail(trouble: Trouble): void {
console.log(`${trouble.getNumber()} cannot be resolved.`);
}
abstract resolve(trouoble: Trouble): boolean;
}
class NoSupport extends Support {
resolve(trouble: Trouble): boolean {
return false;
}
}
class LimitSupport extends Support {
private limit: number;
constructor(name: string, limit: number) {
super(name);
this.limit = limit;
}
resolve(trouble: Trouble): boolean {
return trouble.getNumber() < this.limit;
}
}
class OddSupport extends Support {
resolve(trouble: Trouble): boolean {
return trouble.getNumber() % 2 === 1;
}
}
class SpecialSupport extends Support {
private num: number;
constructor(name: string, num: number) {
super(name);
this.num = num;
}
resolve(trouble: Trouble): boolean {
return trouble.getNumber() === this.num;
}
}
const alice: NoSupport = new NoSupport('Alice');
const bob: LimitSupport = new LimitSupport('Bob', 100);
const charlie: OddSupport = new OddSupport('Charlie');
const diana: SpecialSupport = new SpecialSupport('Diana', 134);
alice.setNext(bob).setNext(charlie).setNext(diana);
for (let i: number = 0; i < 400; i++) {
alice.support(new Trouble(i));
}
| Add implementation of Chain Of Responsibililty pattern | Add implementation of Chain Of Responsibililty pattern
| TypeScript | mit | Erichain/design-patterns-in-typescript,Erichain/design-patterns-in-typescript | ---
+++
@@ -0,0 +1,101 @@
+class Trouble {
+ private number: number;
+
+ constructor(number: number) {
+ this.number = number;
+ }
+
+ getNumber(): number {
+ return this.number;
+ }
+
+ getProblemString(): string {
+ return `Trouble: ${this.number}`;
+ }
+}
+
+abstract class Support {
+ private name: string;
+ private next: Support;
+
+ constructor(name: string) {
+ this.name = name;
+ }
+
+ setNext(next: Support): Support {
+ this.next = next;
+
+ return next;
+ }
+
+ support(trouble: Trouble): void {
+ if (this.resolve(trouble)) {
+ this.done(trouble);
+ } else if (this.next != null) {
+ this.next.support(trouble);
+ } else {
+ this.fail(trouble);
+ }
+ }
+
+ done(trouble: Trouble): void {
+ console.log(`${trouble.getNumber()} was resolved.`);
+ }
+
+ fail(trouble: Trouble): void {
+ console.log(`${trouble.getNumber()} cannot be resolved.`);
+ }
+
+ abstract resolve(trouoble: Trouble): boolean;
+}
+
+class NoSupport extends Support {
+ resolve(trouble: Trouble): boolean {
+ return false;
+ }
+}
+
+class LimitSupport extends Support {
+ private limit: number;
+
+ constructor(name: string, limit: number) {
+ super(name);
+
+ this.limit = limit;
+ }
+
+ resolve(trouble: Trouble): boolean {
+ return trouble.getNumber() < this.limit;
+ }
+}
+
+class OddSupport extends Support {
+ resolve(trouble: Trouble): boolean {
+ return trouble.getNumber() % 2 === 1;
+ }
+}
+
+class SpecialSupport extends Support {
+ private num: number;
+
+ constructor(name: string, num: number) {
+ super(name);
+
+ this.num = num;
+ }
+
+ resolve(trouble: Trouble): boolean {
+ return trouble.getNumber() === this.num;
+ }
+}
+
+const alice: NoSupport = new NoSupport('Alice');
+const bob: LimitSupport = new LimitSupport('Bob', 100);
+const charlie: OddSupport = new OddSupport('Charlie');
+const diana: SpecialSupport = new SpecialSupport('Diana', 134);
+
+alice.setNext(bob).setNext(charlie).setNext(diana);
+
+for (let i: number = 0; i < 400; i++) {
+ alice.support(new Trouble(i));
+} |
|
49f3cd04c1b5ecdc9fd8b198ffe71e12d753dc16 | typings/cordova-plugin-braintree-tests.ts | typings/cordova-plugin-braintree-tests.ts | /// <reference path="cordova-plugin-braintree.d.ts" />
BraintreePlugin.initialize("a");
BraintreePlugin.initialize("a", () => {});
BraintreePlugin.initialize("a", () => {}, () => {});
var paymentUIOptions: BraintreePlugin.PaymentUIOptions = {
cancelText: "Cancel",
title: "Title"
};
BraintreePlugin.presentDropInPaymentUI();
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions);
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions, (result: BraintreePlugin.PaymentUIResult) => {});
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions, (result: BraintreePlugin.PaymentUIResult) => {}, () => {});
| /// <reference path="cordova-plugin-braintree.d.ts" />
BraintreePlugin.initialize("a");
BraintreePlugin.initialize("a", () => {});
BraintreePlugin.initialize("a", () => {}, () => {});
var paymentUIOptions: BraintreePlugin.PaymentUIOptions = {
cancelText: "Cancel",
title: "Title",
ctaText: "Call to Action"
};
BraintreePlugin.presentDropInPaymentUI();
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions);
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions, (result: BraintreePlugin.PaymentUIResult) => {});
BraintreePlugin.presentDropInPaymentUI(paymentUIOptions, (result: BraintreePlugin.PaymentUIResult) => {}, () => {});
| Update type definition test with ctaText property | Update type definition test with ctaText property
| TypeScript | mit | Taracque/cordova-plugin-braintree,Justin-Credible/cordova-plugin-braintree,Taracque/cordova-plugin-braintree,btafel/cordova-plugin-braintree,btafel/cordova-plugin-braintree,LudwigEnglbrecht/cordova-plugin-braintree_new,btafel/cordova-plugin-braintree,Justin-Credible/cordova-plugin-braintree,Taracque/cordova-plugin-braintree,LudwigEnglbrecht/cordova-plugin-braintree_new,LudwigEnglbrecht/cordova-plugin-braintree_new,Justin-Credible/cordova-plugin-braintree,Taracque/cordova-plugin-braintree | ---
+++
@@ -6,7 +6,8 @@
var paymentUIOptions: BraintreePlugin.PaymentUIOptions = {
cancelText: "Cancel",
- title: "Title"
+ title: "Title",
+ ctaText: "Call to Action"
};
BraintreePlugin.presentDropInPaymentUI(); |
621227987b0faa7329c0f460102fe43f8bc49d50 | ui/src/shared/components/FuncSelectorInput.tsx | ui/src/shared/components/FuncSelectorInput.tsx | import React, {SFC, ChangeEvent, KeyboardEvent} from 'react'
type OnFilterChangeHandler = (e: ChangeEvent<HTMLInputElement>) => void
type OnFilterKeyPress = (e: KeyboardEvent<HTMLInputElement>) => void
interface Props {
searchTerm: string
onFilterChange: OnFilterChangeHandler
onFilterKeyPress: OnFilterKeyPress
}
const FuncSelectorInput: SFC<Props> = ({
searchTerm,
onFilterChange,
onFilterKeyPress,
}) => (
<input
className="form-control input-sm ifql-func--input"
type="text"
autoFocus={true}
placeholder="Add Function..."
spellCheck={false}
onChange={onFilterChange}
onKeyDown={onFilterKeyPress}
value={searchTerm}
/>
)
export default FuncSelectorInput
| Introduce input component specifically for IFQL function selection | Introduce input component specifically for IFQL function selection
| TypeScript | mit | nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,li-ang/influxdb | ---
+++
@@ -0,0 +1,29 @@
+import React, {SFC, ChangeEvent, KeyboardEvent} from 'react'
+
+type OnFilterChangeHandler = (e: ChangeEvent<HTMLInputElement>) => void
+type OnFilterKeyPress = (e: KeyboardEvent<HTMLInputElement>) => void
+
+interface Props {
+ searchTerm: string
+ onFilterChange: OnFilterChangeHandler
+ onFilterKeyPress: OnFilterKeyPress
+}
+
+const FuncSelectorInput: SFC<Props> = ({
+ searchTerm,
+ onFilterChange,
+ onFilterKeyPress,
+}) => (
+ <input
+ className="form-control input-sm ifql-func--input"
+ type="text"
+ autoFocus={true}
+ placeholder="Add Function..."
+ spellCheck={false}
+ onChange={onFilterChange}
+ onKeyDown={onFilterKeyPress}
+ value={searchTerm}
+ />
+)
+
+export default FuncSelectorInput |
|
5da9a00b93ad2c2a1b05a819dba75d562a14647d | ui/src/shared/components/Crosshair.tsx | ui/src/shared/components/Crosshair.tsx | import React, {PureComponent} from 'react'
import Dygraph from 'dygraphs'
import {connect} from 'react-redux'
import {DYGRAPH_CONTAINER_XLABEL_MARGIN} from 'src/shared/constants'
interface Props {
hoverTime: number
dygraph: Dygraph
staticLegendHeight: number
}
class Crosshair extends PureComponent<Props> {
public render() {
return (
<div className="crosshair-container">
<div
className="crosshair"
style={{
left: this.crosshairLeft,
height: this.crosshairHeight,
width: '1px',
}}
/>
</div>
)
}
private get crosshairLeft(): number {
const {dygraph, hoverTime} = this.props
const cursorOffset = 16
return dygraph.toDomXCoord(hoverTime) + cursorOffset
}
private get crosshairHeight(): string {
return `calc(100% - ${this.props.staticLegendHeight +
DYGRAPH_CONTAINER_XLABEL_MARGIN}px)`
}
}
const mapStateToProps = ({dashboardUI, annotations: {mode}}) => ({
mode,
hoverTime: +dashboardUI.hoverTime,
})
export default connect(mapStateToProps, null)(Crosshair)
| import React, {PureComponent} from 'react'
import Dygraph from 'dygraphs'
import {connect} from 'react-redux'
import {ErrorHandling} from 'src/shared/decorators/errors'
import {DYGRAPH_CONTAINER_XLABEL_MARGIN} from 'src/shared/constants'
interface Props {
hoverTime: number
dygraph: Dygraph
staticLegendHeight: number
}
@ErrorHandling
class Crosshair extends PureComponent<Props> {
public render() {
return (
<div className="crosshair-container">
<div
className="crosshair"
style={{
left: this.crosshairLeft,
height: this.crosshairHeight,
width: '1px',
}}
/>
</div>
)
}
private get crosshairLeft(): number {
const {dygraph, hoverTime} = this.props
const cursorOffset = 16
return dygraph.toDomXCoord(hoverTime) + cursorOffset
}
private get crosshairHeight(): string {
return `calc(100% - ${this.props.staticLegendHeight +
DYGRAPH_CONTAINER_XLABEL_MARGIN}px)`
}
}
const mapStateToProps = ({dashboardUI, annotations: {mode}}) => ({
mode,
hoverTime: +dashboardUI.hoverTime,
})
export default connect(mapStateToProps, null)(Crosshair)
| Add ErrorHandling decorator to crosshairs | Add ErrorHandling decorator to crosshairs
| TypeScript | mit | nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -1,6 +1,7 @@
import React, {PureComponent} from 'react'
import Dygraph from 'dygraphs'
import {connect} from 'react-redux'
+import {ErrorHandling} from 'src/shared/decorators/errors'
import {DYGRAPH_CONTAINER_XLABEL_MARGIN} from 'src/shared/constants'
@@ -10,6 +11,7 @@
staticLegendHeight: number
}
+@ErrorHandling
class Crosshair extends PureComponent<Props> {
public render() {
return ( |
95c80f83d5bbcd04bb0b9b07be0b2e8f91f566b6 | src/js/ui/tournament/index.ts | src/js/ui/tournament/index.ts | import * as helper from '../helper';
import oninit from './tournamentCtrl';
import view from './tournamentView';
export default {
oncreate: helper.viewFadeIn,
oninit,
view
};
| Add back file deleted in error | Add back file deleted in error
| TypeScript | mit | btrent/lichobile,btrent/lichobile,btrent/lichobile,btrent/lichobile | ---
+++
@@ -0,0 +1,9 @@
+import * as helper from '../helper';
+import oninit from './tournamentCtrl';
+import view from './tournamentView';
+
+export default {
+ oncreate: helper.viewFadeIn,
+ oninit,
+ view
+}; |
|
01f2cce8cf20aa87d8174439a3db3a78ccb186b4 | tests/cases/fourslash/completionWithNamespaceInsideFunction.ts | tests/cases/fourslash/completionWithNamespaceInsideFunction.ts | /// <reference path='fourslash.ts'/>
////function f() {
//// namespace n {
//// interface I {
//// x: number
//// }
//// /*1*/
//// }
//// /*2*/
////}
/////*3*/
goTo.marker('1');
verify.completionListContains("f", "function f(): void");
verify.completionListContains("n", "namespace n");
verify.completionListContains("I", "interface I");
goTo.marker('2');
verify.completionListContains("f", "function f(): void");
verify.completionListContains("n", "namespace n");
goTo.marker('3');
verify.completionListContains("f", "function f(): void"); | Add fourslash test for in scope completion | Add fourslash test for in scope completion
| TypeScript | apache-2.0 | kumikumi/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,fabioparra/TypeScript,bpowers/TypeScript,keir-rex/TypeScript,hoanhtien/TypeScript,mcanthony/TypeScript,impinball/TypeScript,msynk/TypeScript,fabioparra/TypeScript,abbasmhd/TypeScript,ionux/TypeScript,moander/TypeScript,SmallAiTT/TypeScript,germ13/TypeScript,mmoskal/TypeScript,jteplitz602/TypeScript,Microsoft/TypeScript,jteplitz602/TypeScript,ziacik/TypeScript,shiftkey/TypeScript,jbondc/TypeScript,zmaruo/TypeScript,basarat/TypeScript,sassson/TypeScript,SmallAiTT/TypeScript,zmaruo/TypeScript,progre/TypeScript,TukekeSoft/TypeScript,Viromo/TypeScript,samuelhorwitz/typescript,kpreisser/TypeScript,mmoskal/TypeScript,JohnZ622/TypeScript,SaschaNaz/TypeScript,moander/TypeScript,hoanhtien/TypeScript,ziacik/TypeScript,synaptek/TypeScript,plantain-00/TypeScript,erikmcc/TypeScript,abbasmhd/TypeScript,chuckjaz/TypeScript,mcanthony/TypeScript,zhengbli/TypeScript,zhengbli/TypeScript,yazeng/TypeScript,shanexu/TypeScript,mcanthony/TypeScript,germ13/TypeScript,pcan/TypeScript,Viromo/TypeScript,JohnZ622/TypeScript,tempbottle/TypeScript,RReverser/TypeScript,nojvek/TypeScript,kimamula/TypeScript,weswigham/TypeScript,hitesh97/TypeScript,Mqgh2013/TypeScript,nycdotnet/TypeScript,mihailik/TypeScript,DLehenbauer/TypeScript,DanielRosenwasser/TypeScript,tinganho/TypeScript,fabioparra/TypeScript,chuckjaz/TypeScript,OlegDokuka/TypeScript,basarat/TypeScript,thr0w/Thr0wScript,kingland/TypeScript,germ13/TypeScript,shovon/TypeScript,vilic/TypeScript,thr0w/Thr0wScript,basarat/TypeScript,tinganho/TypeScript,AbubakerB/TypeScript,HereSinceres/TypeScript,ZLJASON/TypeScript,Mqgh2013/TypeScript,mihailik/TypeScript,synaptek/TypeScript,sassson/TypeScript,jeremyepling/TypeScript,HereSinceres/TypeScript,suto/TypeScript,SaschaNaz/TypeScript,rgbkrk/TypeScript,samuelhorwitz/typescript,fabioparra/TypeScript,chocolatechipui/TypeScript,webhost/TypeScript,jbondc/TypeScript,jamesrmccallum/TypeScript,yazeng/TypeScript,SaschaNaz/TypeScript,JohnZ622/TypeScript,tempbottle/TypeScript,AbubakerB/TypeScript,kitsonk/TypeScript,DanielRosenwasser/TypeScript,nojvek/TypeScript,enginekit/TypeScript,jdavidberger/TypeScript,mihailik/TypeScript,billti/TypeScript,shiftkey/TypeScript,yortus/TypeScript,matthewjh/TypeScript,msynk/TypeScript,mmoskal/TypeScript,ziacik/TypeScript,nagyistoce/TypeScript,minestarks/TypeScript,chocolatechipui/TypeScript,Eyas/TypeScript,jamesrmccallum/TypeScript,thr0w/Thr0wScript,zmaruo/TypeScript,hitesh97/TypeScript,samuelhorwitz/typescript,vilic/TypeScript,nycdotnet/TypeScript,shanexu/TypeScript,SimoneGianni/TypeScript,gonifade/TypeScript,DLehenbauer/TypeScript,blakeembrey/TypeScript,OlegDokuka/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,fearthecowboy/TypeScript,impinball/TypeScript,kumikumi/TypeScript,bpowers/TypeScript,erikmcc/TypeScript,vilic/TypeScript,nycdotnet/TypeScript,basarat/TypeScript,DanielRosenwasser/TypeScript,MartyIX/TypeScript,jeremyepling/TypeScript,sassson/TypeScript,vilic/TypeScript,shiftkey/TypeScript,mszczepaniak/TypeScript,Viromo/TypeScript,chuckjaz/TypeScript,minestarks/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,billti/TypeScript,fearthecowboy/TypeScript,fearthecowboy/TypeScript,mcanthony/TypeScript,yazeng/TypeScript,ionux/TypeScript,thr0w/Thr0wScript,mszczepaniak/TypeScript,shanexu/TypeScript,rgbkrk/TypeScript,matthewjh/TypeScript,evgrud/TypeScript,MartyIX/TypeScript,rodrigues-daniel/TypeScript,Viromo/TypeScript,erikmcc/TypeScript,ionux/TypeScript,synaptek/TypeScript,alexeagle/TypeScript,mmoskal/TypeScript,chocolatechipui/TypeScript,bpowers/TypeScript,plantain-00/TypeScript,msynk/TypeScript,TukekeSoft/TypeScript,gonifade/TypeScript,gonifade/TypeScript,tinganho/TypeScript,synaptek/TypeScript,pcan/TypeScript,keir-rex/TypeScript,Eyas/TypeScript,moander/TypeScript,ziacik/TypeScript,SimoneGianni/TypeScript,JohnZ622/TypeScript,RyanCavanaugh/TypeScript,jdavidberger/TypeScript,tempbottle/TypeScript,progre/TypeScript,jwbay/TypeScript,donaldpipowitch/TypeScript,webhost/TypeScript,nagyistoce/TypeScript,zhengbli/TypeScript,jwbay/TypeScript,plantain-00/TypeScript,hitesh97/TypeScript,OlegDokuka/TypeScript,HereSinceres/TypeScript,kitsonk/TypeScript,jamesrmccallum/TypeScript,nycdotnet/TypeScript,kimamula/TypeScript,impinball/TypeScript,microsoft/TypeScript,kimamula/TypeScript,blakeembrey/TypeScript,rgbkrk/TypeScript,yortus/TypeScript,TukekeSoft/TypeScript,rodrigues-daniel/TypeScript,donaldpipowitch/TypeScript,yortus/TypeScript,RyanCavanaugh/TypeScript,hoanhtien/TypeScript,erikmcc/TypeScript,ZLJASON/TypeScript,RReverser/TypeScript,billti/TypeScript,pcan/TypeScript,RReverser/TypeScript,mszczepaniak/TypeScript,jdavidberger/TypeScript,yortus/TypeScript,evgrud/TypeScript,abbasmhd/TypeScript,kimamula/TypeScript,MartyIX/TypeScript,ZLJASON/TypeScript,suto/TypeScript,keir-rex/TypeScript,nojvek/TypeScript,shanexu/TypeScript,jwbay/TypeScript,SmallAiTT/TypeScript,progre/TypeScript,alexeagle/TypeScript,Microsoft/TypeScript,minestarks/TypeScript,Eyas/TypeScript,SaschaNaz/TypeScript,jwbay/TypeScript,donaldpipowitch/TypeScript,DanielRosenwasser/TypeScript,Mqgh2013/TypeScript,shovon/TypeScript,Eyas/TypeScript,evgrud/TypeScript,kumikumi/TypeScript,jbondc/TypeScript,blakeembrey/TypeScript,webhost/TypeScript,matthewjh/TypeScript,chuckjaz/TypeScript,jteplitz602/TypeScript,weswigham/TypeScript,Microsoft/TypeScript,plantain-00/TypeScript,blakeembrey/TypeScript,AbubakerB/TypeScript,weswigham/TypeScript,microsoft/TypeScript,DLehenbauer/TypeScript,MartyIX/TypeScript,enginekit/TypeScript,mihailik/TypeScript,shovon/TypeScript,jeremyepling/TypeScript,samuelhorwitz/typescript,ionux/TypeScript,AbubakerB/TypeScript,microsoft/TypeScript,kingland/TypeScript,evgrud/TypeScript,kingland/TypeScript,enginekit/TypeScript,nagyistoce/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,SimoneGianni/TypeScript,moander/TypeScript,rodrigues-daniel/TypeScript,rodrigues-daniel/TypeScript,suto/TypeScript | ---
+++
@@ -0,0 +1,24 @@
+/// <reference path='fourslash.ts'/>
+
+////function f() {
+//// namespace n {
+//// interface I {
+//// x: number
+//// }
+//// /*1*/
+//// }
+//// /*2*/
+////}
+/////*3*/
+
+goTo.marker('1');
+verify.completionListContains("f", "function f(): void");
+verify.completionListContains("n", "namespace n");
+verify.completionListContains("I", "interface I");
+
+goTo.marker('2');
+verify.completionListContains("f", "function f(): void");
+verify.completionListContains("n", "namespace n");
+
+goTo.marker('3');
+verify.completionListContains("f", "function f(): void"); |
|
1472b654db1d5f631f239f250ffc92ee12f5e07e | tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts | tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts | /// <reference path='fourslash.ts' />
////class C2 {
////}
////let I: {
//// /*constructSignature*/new(): C2;
////};
////let C = new [|/*invokeExpression*/I|]();
verify.goToDefinition("invokeExpression", "constructSignature");
| Add test case when new expression target is not Class declaration | Add test case when new expression target is not Class declaration
| TypeScript | apache-2.0 | kitsonk/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,nojvek/TypeScript,basarat/TypeScript,weswigham/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,alexeagle/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,RyanCavanaugh/TypeScript,alexeagle/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,microsoft/TypeScript,microsoft/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,minestarks/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,basarat/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,kitsonk/TypeScript,basarat/TypeScript,minestarks/TypeScript,weswigham/TypeScript | ---
+++
@@ -0,0 +1,10 @@
+/// <reference path='fourslash.ts' />
+
+////class C2 {
+////}
+////let I: {
+//// /*constructSignature*/new(): C2;
+////};
+////let C = new [|/*invokeExpression*/I|]();
+
+verify.goToDefinition("invokeExpression", "constructSignature"); |
|
4a9b1209aeffb33ddbc6c7358e2a0e901cb8eee9 | tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts | tests/cases/fourslash/salsaMethodsOnAssignedFunctionExpressions.ts | /// <reference path="fourslash.ts" />
// @allowJs: true
// @Filename: something.js
////var C = function () { }
/////**
//// * The prototype method.
//// * @param {string} a Parameter definition.
//// */
////function f(a) {}
////C.prototype.m = f;
////
////var x = new C();
////x/*1*/./*2*/m();
goTo.marker('1');
verify.quickInfoIs('var x: {\n m: (a: string) => void;\n}');
goTo.marker('2');
verify.completionListContains('m', '(property) C.m: (a: string) => void', 'The prototype method.');
| Test adding members to JS variables whose initialisers are functions | Test adding members to JS variables whose initialisers are functions
| TypeScript | apache-2.0 | jeremyepling/TypeScript,Eyas/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,thr0w/Thr0wScript,nojvek/TypeScript,jwbay/TypeScript,kitsonk/TypeScript,thr0w/Thr0wScript,kpreisser/TypeScript,alexeagle/TypeScript,weswigham/TypeScript,minestarks/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,vilic/TypeScript,minestarks/TypeScript,basarat/TypeScript,Eyas/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,vilic/TypeScript,DLehenbauer/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,DLehenbauer/TypeScript,synaptek/TypeScript,Eyas/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,erikmcc/TypeScript,jwbay/TypeScript,jeremyepling/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,thr0w/Thr0wScript,alexeagle/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,chuckjaz/TypeScript,nojvek/TypeScript,TukekeSoft/TypeScript,mihailik/TypeScript,chuckjaz/TypeScript,jwbay/TypeScript,erikmcc/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,erikmcc/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,jwbay/TypeScript,kpreisser/TypeScript,vilic/TypeScript,DLehenbauer/TypeScript,microsoft/TypeScript,basarat/TypeScript,weswigham/TypeScript,chuckjaz/TypeScript,donaldpipowitch/TypeScript,mihailik/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,RyanCavanaugh/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,chuckjaz/TypeScript,Eyas/TypeScript,donaldpipowitch/TypeScript,kpreisser/TypeScript,synaptek/TypeScript,thr0w/Thr0wScript,RyanCavanaugh/TypeScript,TukekeSoft/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,basarat/TypeScript | ---
+++
@@ -0,0 +1,17 @@
+/// <reference path="fourslash.ts" />
+// @allowJs: true
+// @Filename: something.js
+////var C = function () { }
+/////**
+//// * The prototype method.
+//// * @param {string} a Parameter definition.
+//// */
+////function f(a) {}
+////C.prototype.m = f;
+////
+////var x = new C();
+////x/*1*/./*2*/m();
+goTo.marker('1');
+verify.quickInfoIs('var x: {\n m: (a: string) => void;\n}');
+goTo.marker('2');
+verify.completionListContains('m', '(property) C.m: (a: string) => void', 'The prototype method.'); |
|
e09ef3124b3f5a22f5ed6e72659c3ef7090de0a3 | analysis/monkwindwalker/src/modules/talents/DoCJ.tsx | analysis/monkwindwalker/src/modules/talents/DoCJ.tsx | import { t } from '@lingui/macro';
import { formatNumber, formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import UptimeIcon from 'interface/icons/Uptime';
import Analyzer, { Options } from 'parser/core/Analyzer';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import { SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/EventFilter';
import Events, { DamageEvent } from 'parser/core/Events';
import { ThresholdStyle, When } from 'parser/core/ParseResults';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from 'parser/ui/Statistic';
import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import React from 'react';
import { ABILITIES_AFFECTED_BY_DAMAGE_INCREASES } from '../../constants';
const DAMAGE_MULTIPLIER = 2
class DANCE_OF_CHI_JI extends Analyzer {
constructor( options: Options) {
super(options);
this.addEventListener(
Events.damage.by(SELECTED_PLAYER).spell(SPELLS.SPINNING_CRANE_KICK),
this.SpinningCraneKickDamage,
);
}
totalDamage = 0;
SpinningCraneKickDamage(even: DamageEvent) {
const buffInfo = this.selectedCombatant.getBuff(SPELLS.DANCE_OF_CHI_JI_BUFF.id);
if(!buffInfo) {
return;
}
this.totalDamage += calculateEffectiveDamage(event, DAMAGE_MULTIPLIER);
}
get dps() {
return (this.totalDamage / this.owner.fightDuration) * 1000;
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.CORE(11)}
size="flexible"
tooltip={
<>
Total damage increase: {formatNumber(this.totalDamage)}
</>
}
>
<BoringSpellValueText spell={SPELLS.DANCE_OF_CHI_JI_TALENT}>
<img src="/img/sword.png" alt="Damage" className="icon" /> {formatNumber(this.dps)} DPS{' '}
<small>
{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.totalDamage))} % of
total
</small>
</BoringSpellValueText>
</Statistic>
);
}
}
export default DANCE_OF_CHI_JI; | Add SCK damage event tracker | Add SCK damage event tracker
First attempt at tracking DPS contribution of DoCJ | TypeScript | agpl-3.0 | sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer | ---
+++
@@ -0,0 +1,66 @@
+import { t } from '@lingui/macro';
+import { formatNumber, formatPercentage } from 'common/format';
+import SPELLS from 'common/SPELLS';
+import { SpellLink } from 'interface';
+import UptimeIcon from 'interface/icons/Uptime';
+import Analyzer, { Options } from 'parser/core/Analyzer';
+import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
+import { SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/EventFilter';
+import Events, { DamageEvent } from 'parser/core/Events';
+import { ThresholdStyle, When } from 'parser/core/ParseResults';
+import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
+import Statistic from 'parser/ui/Statistic';
+import { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
+import React from 'react';
+
+import { ABILITIES_AFFECTED_BY_DAMAGE_INCREASES } from '../../constants';
+
+const DAMAGE_MULTIPLIER = 2
+
+class DANCE_OF_CHI_JI extends Analyzer {
+constructor( options: Options) {
+ super(options);
+ this.addEventListener(
+ Events.damage.by(SELECTED_PLAYER).spell(SPELLS.SPINNING_CRANE_KICK),
+ this.SpinningCraneKickDamage,
+ );
+}
+ totalDamage = 0;
+
+ SpinningCraneKickDamage(even: DamageEvent) {
+ const buffInfo = this.selectedCombatant.getBuff(SPELLS.DANCE_OF_CHI_JI_BUFF.id);
+ if(!buffInfo) {
+ return;
+ }
+ this.totalDamage += calculateEffectiveDamage(event, DAMAGE_MULTIPLIER);
+ }
+
+ get dps() {
+ return (this.totalDamage / this.owner.fightDuration) * 1000;
+ }
+
+
+ statistic() {
+ return (
+ <Statistic
+ position={STATISTIC_ORDER.CORE(11)}
+ size="flexible"
+ tooltip={
+ <>
+ Total damage increase: {formatNumber(this.totalDamage)}
+ </>
+ }
+ >
+ <BoringSpellValueText spell={SPELLS.DANCE_OF_CHI_JI_TALENT}>
+ <img src="/img/sword.png" alt="Damage" className="icon" /> {formatNumber(this.dps)} DPS{' '}
+ <small>
+ {formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.totalDamage))} % of
+ total
+ </small>
+ </BoringSpellValueText>
+ </Statistic>
+ );
+ }
+}
+
+export default DANCE_OF_CHI_JI; |
|
432eb9979afb804c7cdec6cc00ff65e09e83026d | resource/classes/Extensions.ts | resource/classes/Extensions.ts | export class XArray<T> extends Array<T> {
public randomize(prng?: () => number): Array<T> {
var t: T, j: number, ret = this.slice(0), i = ret.length;
prng = prng || Math.random;
while(--i > 0) {
t = ret[j = Math.round(prng() * i)];
ret[j] = ret[i];
ret[i] = t;
}
return ret;
}
public static fromArray<T1>(arr: Array<T1>): XArray<T1> {
const xarr = new XArray<T1>();
xarr.push.apply(xarr, arr);
return xarr;
}
}
| Add an extension for Array<T> | Add an extension for Array<T>
| TypeScript | mit | MrShoenel/node-temporary-short-urls,MrShoenel/node-temporary-short-urls | ---
+++
@@ -0,0 +1,18 @@
+export class XArray<T> extends Array<T> {
+ public randomize(prng?: () => number): Array<T> {
+ var t: T, j: number, ret = this.slice(0), i = ret.length;
+ prng = prng || Math.random;
+ while(--i > 0) {
+ t = ret[j = Math.round(prng() * i)];
+ ret[j] = ret[i];
+ ret[i] = t;
+ }
+ return ret;
+ }
+
+ public static fromArray<T1>(arr: Array<T1>): XArray<T1> {
+ const xarr = new XArray<T1>();
+ xarr.push.apply(xarr, arr);
+ return xarr;
+ }
+} |
|
d75a5b2937988558102625f3d79b7691ab054494 | src/parser/hunter/shared/modules/spells/KillShot.tsx | src/parser/hunter/shared/modules/spells/KillShot.tsx | import Analyzer from 'parser/core/Analyzer';
//TODO Add something akin to ExecuteRange.js in arms/modules/core/Execute to track proper ABC of Kill Shot
class KillShot extends Analyzer {
}
export default KillShot;
| Add Kill Shot for all specs for SL | [Hunter] Add Kill Shot for all specs for SL
| TypeScript | agpl-3.0 | anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer | ---
+++
@@ -0,0 +1,8 @@
+import Analyzer from 'parser/core/Analyzer';
+
+//TODO Add something akin to ExecuteRange.js in arms/modules/core/Execute to track proper ABC of Kill Shot
+class KillShot extends Analyzer {
+
+}
+
+export default KillShot; |
|
41d2c582ebebd827e2618fbc433fd00f654462be | plugin/index.ts | plugin/index.ts | export * from './battery-status';
export * from './camera';
export * from './device';
export * from './device-motion';
export * from './device-orientation';
export * from './dialogs';
export * from './facebook';
export * from './firebase';
export * from './geolocation';
export * from './keyboard';
export * from './media';
export * from './network-information';
export * from './splashscreen';
export * from './statusbar';
export * from './stripe';
export * from './vibration'; | Add barrel for plugin so that you can easily import multiple services | Add barrel for plugin so that you can easily import multiple services
| TypeScript | mit | arnesson/angular-cordova,arnesson/angular-cordova | ---
+++
@@ -0,0 +1,16 @@
+export * from './battery-status';
+export * from './camera';
+export * from './device';
+export * from './device-motion';
+export * from './device-orientation';
+export * from './dialogs';
+export * from './facebook';
+export * from './firebase';
+export * from './geolocation';
+export * from './keyboard';
+export * from './media';
+export * from './network-information';
+export * from './splashscreen';
+export * from './statusbar';
+export * from './stripe';
+export * from './vibration'; |
|
1a8fad665dd7379515b5f037fa3bb70e19f5cc0d | src/smc-webapp/tracker/index.ts | src/smc-webapp/tracker/index.ts | // `analytics` is a generalized wrapper for reporting data to google analytics, pwiki, parsley, ...
// for now, it either does nothing or works with GA
// this API basically allows to send off events by name and category
const analytics = function(type, ...args) {
// GoogleAnalyticsObject contains the possibly customized function name of GA.
// It's a good idea to call it differently from the default 'ga' to avoid name clashes...
if (window.GoogleAnalyticsObject != undefined) {
const ga = window[window.GoogleAnalyticsObject];
if (ga != undefined) {
switch (type) {
case "event":
case "pageview":
return ga("send", type, ...args);
default:
return console.warn(`unknown analytics event '${type}'`);
}
}
}
};
export const analytics_pageview = (...args) => analytics("pageview", ...args);
export const analytics_event = (...args) => analytics("event", ...args);
| Convert misc_page analytics to ts | Convert misc_page analytics to ts
| TypeScript | agpl-3.0 | sagemathinc/smc,tscholl2/smc,tscholl2/smc,sagemathinc/smc,tscholl2/smc,tscholl2/smc,sagemathinc/smc,DrXyzzy/smc,tscholl2/smc,sagemathinc/smc,DrXyzzy/smc,DrXyzzy/smc,DrXyzzy/smc | ---
+++
@@ -0,0 +1,23 @@
+// `analytics` is a generalized wrapper for reporting data to google analytics, pwiki, parsley, ...
+// for now, it either does nothing or works with GA
+// this API basically allows to send off events by name and category
+
+const analytics = function(type, ...args) {
+ // GoogleAnalyticsObject contains the possibly customized function name of GA.
+ // It's a good idea to call it differently from the default 'ga' to avoid name clashes...
+ if (window.GoogleAnalyticsObject != undefined) {
+ const ga = window[window.GoogleAnalyticsObject];
+ if (ga != undefined) {
+ switch (type) {
+ case "event":
+ case "pageview":
+ return ga("send", type, ...args);
+ default:
+ return console.warn(`unknown analytics event '${type}'`);
+ }
+ }
+ }
+};
+
+export const analytics_pageview = (...args) => analytics("pageview", ...args);
+export const analytics_event = (...args) => analytics("event", ...args); |
|
ff5a019d9cf2eb21ea49dc31488f2c3e4a386ef3 | src/Unosquare.Tubular2.Web/e2e/gridPagerInfo.e2e-spec.ts | src/Unosquare.Tubular2.Web/e2e/gridPagerInfo.e2e-spec.ts | import { browser, element, by } from '../node_modules/protractor/built';
describe('grid pager info', () => {
let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'),
gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'),
pageSizeSelector = element(by.tagName('page-size-selector')).$$('select'),
gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input');
beforeEach(() => {
browser.refresh();
});
it('should show text in accordance to numbered of filter rows and current results-page',() => {
expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records');
paginator.get(7).$$('a').click();
pageSizeSelector.$$('option').get(1).click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records');
paginator.get(5).$$('a').click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records');
});
it('should show count in footer', () => {
gridSearchInput.sendKeys('a');
expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)');
});
}); | Add grid pager info test | Add grid pager info test
| TypeScript | mit | unosquare/tubular2,unosquare/tubular2,unosquare/tubular2,unosquare/tubular2 | ---
+++
@@ -0,0 +1,29 @@
+import { browser, element, by } from '../node_modules/protractor/built';
+
+describe('grid pager info', () => {
+
+ let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'),
+ gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'),
+ pageSizeSelector = element(by.tagName('page-size-selector')).$$('select'),
+ gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input');
+
+
+ beforeEach(() => {
+ browser.refresh();
+ });
+
+ it('should show text in accordance to numbered of filter rows and current results-page',() => {
+ expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records');
+ paginator.get(7).$$('a').click();
+ pageSizeSelector.$$('option').get(1).click();
+ expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records');
+ paginator.get(5).$$('a').click();
+ expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records');
+ });
+
+ it('should show count in footer', () => {
+ gridSearchInput.sendKeys('a');
+ expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)');
+ });
+
+}); |
|
552f6fa787d803abf60a6e2b756162bb52820799 | test/helpers/crypto.ts | test/helpers/crypto.ts | import "../../helpers/require";
import { expect } from "chai";
import HelperCrypto from "@eta/helpers/crypto";
describe("helpers/crypto", () => {
const password = "testing";
const salt = HelperCrypto.generateSalt();
const key = "test";
describe("#hashPassword", () => {
let output: string;
beforeEach(() => {
output = HelperCrypto.hashPassword(password, salt);
});
it("should return a string with 64 characters", () => {
expect(output).to.have.lengthOf(64);
});
it("should return a consistent value", () => {
expect(output).to.equal(HelperCrypto.hashPassword(password, salt));
});
});
describe("#generateSalt", () => {
let output: string;
beforeEach(() => {
output = HelperCrypto.generateSalt();
});
it("should return a string with 20 characters", () => {
expect(output).to.have.lengthOf(20);
});
it("should return an inconsistent value", () => {
expect(output).to.not.equal(HelperCrypto.generateSalt());
});
});
describe("#getUnique", () => {
let output: string;
beforeEach(() => {
output = HelperCrypto.getUnique(Buffer.from(password));
});
it("should return a string with 32 characters", () => {
expect(output).to.have.lengthOf(32);
});
it("should return a consistent value given the same input", () => {
expect(output).to.equal(HelperCrypto.getUnique(Buffer.from(password)));
});
it("should return an inconsistent value given a different input", () => {
expect(output).to.not.equal(HelperCrypto.getUnique(Buffer.from(salt)));
});
});
describe("#encrypt", () => {
const output: string = HelperCrypto.encrypt(password, key);
it("should return a string with 2x characters of the original", () => {
expect(output).to.have.lengthOf(2 * password.length);
});
it("should return a consistent value given the same inputs", () => {
expect(output).to.equal(HelperCrypto.encrypt(password, key));
});
it("should return an inconsistent value given a different key", () => {
expect(output).to.not.equal(HelperCrypto.encrypt(password, salt));
});
it("should return an inconsistent value given different data", () => {
expect(output).to.not.equal(HelperCrypto.encrypt(salt, key));
});
});
describe("#decrypt", () => {
const encrypted: string = HelperCrypto.encrypt(password, key);
const decrypted: string = HelperCrypto.decrypt(encrypted, key);
it("should return the original string given the correct key", () => {
expect(decrypted).to.equal(password);
});
it("should return a different string given an incorrect key", () => {
expect(HelperCrypto.decrypt(encrypted, salt)).to.not.equal(password);
});
});
});
| Implement unit tests for HelperCrypto | Implement unit tests for HelperCrypto
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -0,0 +1,78 @@
+import "../../helpers/require";
+import { expect } from "chai";
+import HelperCrypto from "@eta/helpers/crypto";
+
+describe("helpers/crypto", () => {
+ const password = "testing";
+ const salt = HelperCrypto.generateSalt();
+ const key = "test";
+
+ describe("#hashPassword", () => {
+ let output: string;
+ beforeEach(() => {
+ output = HelperCrypto.hashPassword(password, salt);
+ });
+ it("should return a string with 64 characters", () => {
+ expect(output).to.have.lengthOf(64);
+ });
+ it("should return a consistent value", () => {
+ expect(output).to.equal(HelperCrypto.hashPassword(password, salt));
+ });
+ });
+
+ describe("#generateSalt", () => {
+ let output: string;
+ beforeEach(() => {
+ output = HelperCrypto.generateSalt();
+ });
+ it("should return a string with 20 characters", () => {
+ expect(output).to.have.lengthOf(20);
+ });
+ it("should return an inconsistent value", () => {
+ expect(output).to.not.equal(HelperCrypto.generateSalt());
+ });
+ });
+
+ describe("#getUnique", () => {
+ let output: string;
+ beforeEach(() => {
+ output = HelperCrypto.getUnique(Buffer.from(password));
+ });
+ it("should return a string with 32 characters", () => {
+ expect(output).to.have.lengthOf(32);
+ });
+ it("should return a consistent value given the same input", () => {
+ expect(output).to.equal(HelperCrypto.getUnique(Buffer.from(password)));
+ });
+ it("should return an inconsistent value given a different input", () => {
+ expect(output).to.not.equal(HelperCrypto.getUnique(Buffer.from(salt)));
+ });
+ });
+
+ describe("#encrypt", () => {
+ const output: string = HelperCrypto.encrypt(password, key);
+ it("should return a string with 2x characters of the original", () => {
+ expect(output).to.have.lengthOf(2 * password.length);
+ });
+ it("should return a consistent value given the same inputs", () => {
+ expect(output).to.equal(HelperCrypto.encrypt(password, key));
+ });
+ it("should return an inconsistent value given a different key", () => {
+ expect(output).to.not.equal(HelperCrypto.encrypt(password, salt));
+ });
+ it("should return an inconsistent value given different data", () => {
+ expect(output).to.not.equal(HelperCrypto.encrypt(salt, key));
+ });
+ });
+
+ describe("#decrypt", () => {
+ const encrypted: string = HelperCrypto.encrypt(password, key);
+ const decrypted: string = HelperCrypto.decrypt(encrypted, key);
+ it("should return the original string given the correct key", () => {
+ expect(decrypted).to.equal(password);
+ });
+ it("should return a different string given an incorrect key", () => {
+ expect(HelperCrypto.decrypt(encrypted, salt)).to.not.equal(password);
+ });
+ });
+}); |
|
877142ee3d0ad9153480a982f41f7295144ba4e3 | src/selectors/databaseFilterSettings.ts | src/selectors/databaseFilterSettings.ts | import { hitDatabaseSelector, databaseFIlterSettingsSelector } from './index';
import { createSelector } from 'reselect';
import { HitDatabaseEntry } from 'types';
export const hitDatabaseFilteredBySearchTerm = createSelector(
[hitDatabaseSelector, databaseFIlterSettingsSelector],
(hitDatabase, { searchTerm }) =>
hitDatabase
.filter((hit: HitDatabaseEntry) => hit.title.search(searchTerm) !== -1)
.map((el: HitDatabaseEntry) => el.id)
);
| Add selector for filtering hitDatabase entries by title. | Add selector for filtering hitDatabase entries by title.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,11 @@
+import { hitDatabaseSelector, databaseFIlterSettingsSelector } from './index';
+import { createSelector } from 'reselect';
+import { HitDatabaseEntry } from 'types';
+
+export const hitDatabaseFilteredBySearchTerm = createSelector(
+ [hitDatabaseSelector, databaseFIlterSettingsSelector],
+ (hitDatabase, { searchTerm }) =>
+ hitDatabase
+ .filter((hit: HitDatabaseEntry) => hit.title.search(searchTerm) !== -1)
+ .map((el: HitDatabaseEntry) => el.id)
+); |
|
2c9009676721480734cc567afd2b35e78d43a70d | src/app/Utils/ConfigProvider.ts | src/app/Utils/ConfigProvider.ts | import * as fs from 'fs';
import * as path from 'path';
import {Config} from '../Configuration/Config';
import {ModuleProvider} from './ModuleProvider';
export class ConfigProvider {
private static instance: ConfigProvider = null;
protected config: Config;
private constructor() {}
public static getInstance() {
if (this.instance === null) {
this.instance = new ConfigProvider();
}
return this.instance;
}
public getAppConfig(dir: string, env: string = 'dev') {
let moduleProvider = ModuleProvider.getInstance();
let modules = moduleProvider.getModules();
let data = {};
let config = new Config('config');
// TODO: load file according to environment
let configFile = path.join(dir, 'config', 'config.json');
modules.map(m => {
let c = m.addConfiguration();
if (c !== null) {
config.push(c);
}
});
if (fs.existsSync(configFile)
&& fs.lstatSync(configFile).isFile()) {
data = require(configFile);
}
config.readConfiguration(data);
this.config = config;
}
public get(key: string) {
let keys = key.split('.');
let config = this.config;
keys.map(key => config = config.getKey(key));
return config.getValue();
}
}
| Add config provider to read all module configurartions and read specific value | Add config provider to read all module configurartions and read specific value
| TypeScript | mit | vincent-chapron/resonance-js,vincent-chapron/resonance-js,vincent-chapron/resonance-js | ---
+++
@@ -0,0 +1,48 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import {Config} from '../Configuration/Config';
+import {ModuleProvider} from './ModuleProvider';
+
+export class ConfigProvider {
+ private static instance: ConfigProvider = null;
+
+ protected config: Config;
+
+ private constructor() {}
+
+ public static getInstance() {
+ if (this.instance === null) {
+ this.instance = new ConfigProvider();
+ }
+ return this.instance;
+ }
+
+ public getAppConfig(dir: string, env: string = 'dev') {
+ let moduleProvider = ModuleProvider.getInstance();
+ let modules = moduleProvider.getModules();
+ let data = {};
+ let config = new Config('config');
+ // TODO: load file according to environment
+ let configFile = path.join(dir, 'config', 'config.json');
+
+ modules.map(m => {
+ let c = m.addConfiguration();
+ if (c !== null) {
+ config.push(c);
+ }
+ });
+ if (fs.existsSync(configFile)
+ && fs.lstatSync(configFile).isFile()) {
+ data = require(configFile);
+ }
+ config.readConfiguration(data);
+ this.config = config;
+ }
+
+ public get(key: string) {
+ let keys = key.split('.');
+ let config = this.config;
+ keys.map(key => config = config.getKey(key));
+ return config.getValue();
+ }
+} |
|
bfc68a72a8f372711842e52caeda7f0a063315e8 | angular-i18next/angular-i18next-tests.ts | angular-i18next/angular-i18next-tests.ts | /// <reference path="angular-i18next.d.ts" />
/**
* @summary Test for "angular-i18next" with options.
*/
function testOptions() {
var $provider: I18nextProvider;
$provider.options = {};
}
| Add test for "angular-i18next" definition. | Add test for "angular-i18next" definition.
| TypeScript | mit | bluong/DefinitelyTyped,Zzzen/DefinitelyTyped,brainded/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,alexdresko/DefinitelyTyped,manekovskiy/DefinitelyTyped,bilou84/DefinitelyTyped,bdoss/DefinitelyTyped,pocesar/DefinitelyTyped,zalamtech/DefinitelyTyped,Syati/DefinitelyTyped,Pipe-shen/DefinitelyTyped,Garciat/DefinitelyTyped,florentpoujol/DefinitelyTyped,georgemarshall/DefinitelyTyped,hiraash/DefinitelyTyped,damianog/DefinitelyTyped,onecentlin/DefinitelyTyped,progre/DefinitelyTyped,Pro/DefinitelyTyped,eugenpodaru/DefinitelyTyped,JaminFarr/DefinitelyTyped,teves-castro/DefinitelyTyped,masonkmeyer/DefinitelyTyped,syuilo/DefinitelyTyped,schmuli/DefinitelyTyped,jsaelhof/DefinitelyTyped,shovon/DefinitelyTyped,dsebastien/DefinitelyTyped,cvrajeesh/DefinitelyTyped,PascalSenn/DefinitelyTyped,wbuchwalter/DefinitelyTyped,pocke/DefinitelyTyped,billccn/DefinitelyTyped,Ptival/DefinitelyTyped,chrilith/DefinitelyTyped,martinduparc/DefinitelyTyped,theyelllowdart/DefinitelyTyped,subjectix/DefinitelyTyped,dmoonfire/DefinitelyTyped,xswordsx/DefinitelyTyped,lekaha/DefinitelyTyped,frogcjn/DefinitelyTyped,DeluxZ/DefinitelyTyped,Syati/DefinitelyTyped,elisee/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,musically-ut/DefinitelyTyped,egeland/DefinitelyTyped,ashwinr/DefinitelyTyped,mvarblow/DefinitelyTyped,bpowers/DefinitelyTyped,ducin/DefinitelyTyped,benliddicott/DefinitelyTyped,Dashlane/DefinitelyTyped,Ptival/DefinitelyTyped,Dominator008/DefinitelyTyped,brentonhouse/DefinitelyTyped,use-strict/DefinitelyTyped,rockclimber90/DefinitelyTyped,lightswitch05/DefinitelyTyped,PopSugar/DefinitelyTyped,nitintutlani/DefinitelyTyped,mshmelev/DefinitelyTyped,DustinWehr/DefinitelyTyped,greglo/DefinitelyTyped,pocesar/DefinitelyTyped,hx0day/DefinitelyTyped,vsavkin/DefinitelyTyped,drillbits/DefinitelyTyped,georgemarshall/DefinitelyTyped,ajtowf/DefinitelyTyped,benishouga/DefinitelyTyped,pocesar/DefinitelyTyped,Karabur/DefinitelyTyped,syntax42/DefinitelyTyped,amanmahajan7/DefinitelyTyped,shlomiassaf/DefinitelyTyped,Gmulti/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,glenndierckx/DefinitelyTyped,mjjames/DefinitelyTyped,nseckinoral/DefinitelyTyped,vagarenko/DefinitelyTyped,chocolatechipui/DefinitelyTyped,Seltzer/DefinitelyTyped,subash-a/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,aqua89/DefinitelyTyped,micurs/DefinitelyTyped,behzad888/DefinitelyTyped,dreampulse/DefinitelyTyped,psnider/DefinitelyTyped,moonpyk/DefinitelyTyped,EnableSoftware/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,lucyhe/DefinitelyTyped,robert-voica/DefinitelyTyped,tan9/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,Zzzen/DefinitelyTyped,stacktracejs/DefinitelyTyped,M-Zuber/DefinitelyTyped,arusakov/DefinitelyTyped,YousefED/DefinitelyTyped,zhiyiting/DefinitelyTyped,jaysoo/DefinitelyTyped,maglar0/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,gdi2290/DefinitelyTyped,Minishlink/DefinitelyTyped,sledorze/DefinitelyTyped,amanmahajan7/DefinitelyTyped,jacqt/DefinitelyTyped,QuatroCode/DefinitelyTyped,philippstucki/DefinitelyTyped,alainsahli/DefinitelyTyped,chrismbarr/DefinitelyTyped,drinchev/DefinitelyTyped,GregOnNet/DefinitelyTyped,rcchen/DefinitelyTyped,isman-usoh/DefinitelyTyped,nakakura/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,RX14/DefinitelyTyped,acepoblete/DefinitelyTyped,olemp/DefinitelyTyped,eekboom/DefinitelyTyped,yuit/DefinitelyTyped,jsaelhof/DefinitelyTyped,gregoryagu/DefinitelyTyped,gyohk/DefinitelyTyped,olivierlemasle/DefinitelyTyped,florentpoujol/DefinitelyTyped,rushi216/DefinitelyTyped,munxar/DefinitelyTyped,MugeSo/DefinitelyTyped,georgemarshall/DefinitelyTyped,HPFOD/DefinitelyTyped,pafflique/DefinitelyTyped,nycdotnet/DefinitelyTyped,hellopao/DefinitelyTyped,lbguilherme/DefinitelyTyped,uestcNaldo/DefinitelyTyped,Bobjoy/DefinitelyTyped,innerverse/DefinitelyTyped,OpenMaths/DefinitelyTyped,hellopao/DefinitelyTyped,jiaz/DefinitelyTyped,teves-castro/DefinitelyTyped,mjjames/DefinitelyTyped,alextkachman/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,onecentlin/DefinitelyTyped,amir-arad/DefinitelyTyped,chrootsu/DefinitelyTyped,frogcjn/DefinitelyTyped,mcrawshaw/DefinitelyTyped,scriby/DefinitelyTyped,quantumman/DefinitelyTyped,HPFOD/DefinitelyTyped,trystanclarke/DefinitelyTyped,corps/DefinitelyTyped,fredgalvao/DefinitelyTyped,donnut/DefinitelyTyped,wkrueger/DefinitelyTyped,Litee/DefinitelyTyped,YousefED/DefinitelyTyped,sledorze/DefinitelyTyped,scatcher/DefinitelyTyped,stacktracejs/DefinitelyTyped,mattblang/DefinitelyTyped,emanuelhp/DefinitelyTyped,Pro/DefinitelyTyped,AgentME/DefinitelyTyped,Almouro/DefinitelyTyped,QuatroCode/DefinitelyTyped,davidsidlinger/DefinitelyTyped,Karabur/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,vincentw56/DefinitelyTyped,raijinsetsu/DefinitelyTyped,Fraegle/DefinitelyTyped,olemp/DefinitelyTyped,tigerxy/DefinitelyTyped,sclausen/DefinitelyTyped,TildaLabs/DefinitelyTyped,sandersky/DefinitelyTyped,gorcz/DefinitelyTyped,omidkrad/DefinitelyTyped,Kuniwak/DefinitelyTyped,Lorisu/DefinitelyTyped,bennett000/DefinitelyTyped,applesaucers/lodash-invokeMap,nobuoka/DefinitelyTyped,Chris380/DefinitelyTyped,haskellcamargo/DefinitelyTyped,donnut/DefinitelyTyped,nainslie/DefinitelyTyped,fnipo/DefinitelyTyped,abbasmhd/DefinitelyTyped,dwango-js/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,greglo/DefinitelyTyped,dpsthree/DefinitelyTyped,igorsechyn/DefinitelyTyped,arma-gast/DefinitelyTyped,angelobelchior8/DefinitelyTyped,drinchev/DefinitelyTyped,AgentME/DefinitelyTyped,emanuelhp/DefinitelyTyped,timjk/DefinitelyTyped,progre/DefinitelyTyped,furny/DefinitelyTyped,mareek/DefinitelyTyped,takenet/DefinitelyTyped,ryan10132/DefinitelyTyped,optical/DefinitelyTyped,gandjustas/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,schmuli/DefinitelyTyped,danfma/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,leoromanovsky/DefinitelyTyped,Zenorbi/DefinitelyTyped,johan-gorter/DefinitelyTyped,Carreau/DefinitelyTyped,algorithme/DefinitelyTyped,laball/DefinitelyTyped,IAPark/DefinitelyTyped,HereSinceres/DefinitelyTyped,hor-crux/DefinitelyTyped,jeremyhayes/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,Litee/DefinitelyTyped,psnider/DefinitelyTyped,philippstucki/DefinitelyTyped,nobuoka/DefinitelyTyped,CSharpFan/DefinitelyTyped,greglockwood/DefinitelyTyped,lbesson/DefinitelyTyped,aldo-roman/DefinitelyTyped,muenchdo/DefinitelyTyped,arusakov/DefinitelyTyped,axelcostaspena/DefinitelyTyped,daptiv/DefinitelyTyped,nmalaguti/DefinitelyTyped,EnableSoftware/DefinitelyTyped,ciriarte/DefinitelyTyped,biomassives/DefinitelyTyped,aciccarello/DefinitelyTyped,pkhayundi/DefinitelyTyped,superduper/DefinitelyTyped,esperco/DefinitelyTyped,tdmckinn/DefinitelyTyped,UzEE/DefinitelyTyped,Ridermansb/DefinitelyTyped,Trapulo/DefinitelyTyped,aciccarello/DefinitelyTyped,timramone/DefinitelyTyped,paulmorphy/DefinitelyTyped,hatz48/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,aciccarello/DefinitelyTyped,mcliment/DefinitelyTyped,DenEwout/DefinitelyTyped,the41/DefinitelyTyped,NCARalph/DefinitelyTyped,sclausen/DefinitelyTyped,blink1073/DefinitelyTyped,nodeframe/DefinitelyTyped,smrq/DefinitelyTyped,hatz48/DefinitelyTyped,richardTowers/DefinitelyTyped,LordJZ/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,syuilo/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,tjoskar/DefinitelyTyped,markogresak/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,abmohan/DefinitelyTyped,tscho/DefinitelyTyped,bruennijs/DefinitelyTyped,GodsBreath/DefinitelyTyped,adammartin1981/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,whoeverest/DefinitelyTyped,almstrand/DefinitelyTyped,jraymakers/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,aroder/DefinitelyTyped,paulmorphy/DefinitelyTyped,schmuli/DefinitelyTyped,newclear/DefinitelyTyped,lseguin42/DefinitelyTyped,RedSeal-co/DefinitelyTyped,xica/DefinitelyTyped,jasonswearingen/DefinitelyTyped,kanreisa/DefinitelyTyped,mweststrate/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,tarruda/DefinitelyTyped,borisyankov/DefinitelyTyped,bjfletcher/DefinitelyTyped,mhegazy/DefinitelyTyped,smrq/DefinitelyTyped,jtlan/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,tboyce/DefinitelyTyped,michalczukm/DefinitelyTyped,martinduparc/DefinitelyTyped,one-pieces/DefinitelyTyped,UzEE/DefinitelyTyped,reppners/DefinitelyTyped,ayanoin/DefinitelyTyped,mcrawshaw/DefinitelyTyped,chrismbarr/DefinitelyTyped,basp/DefinitelyTyped,mhegazy/DefinitelyTyped,shlomiassaf/DefinitelyTyped,alexdresko/DefinitelyTyped,rcchen/DefinitelyTyped,digitalpixies/DefinitelyTyped,MarlonFan/DefinitelyTyped,johan-gorter/DefinitelyTyped,rerezz/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,musakarakas/DefinitelyTyped,ml-workshare/DefinitelyTyped,trystanclarke/DefinitelyTyped,reppners/DefinitelyTyped,AgentME/DefinitelyTyped,Zorgatone/DefinitelyTyped,dmoonfire/DefinitelyTyped,alextkachman/DefinitelyTyped,behzad888/DefinitelyTyped,nabeix/DefinitelyTyped,mareek/DefinitelyTyped,egeland/DefinitelyTyped,pwelter34/DefinitelyTyped,raijinsetsu/DefinitelyTyped,sixinli/DefinitelyTyped,yuit/DefinitelyTyped,Seikho/DefinitelyTyped,gyohk/DefinitelyTyped,alvarorahul/DefinitelyTyped,tan9/DefinitelyTyped,takfjt/DefinitelyTyped,zensh/DefinitelyTyped,arcticwaters/DefinitelyTyped,benishouga/DefinitelyTyped,vagarenko/DefinitelyTyped,rschmukler/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,unknownloner/DefinitelyTyped,icereed/DefinitelyTyped,nmalaguti/DefinitelyTyped,deeleman/DefinitelyTyped,fredgalvao/DefinitelyTyped,bdoss/DefinitelyTyped,Deathspike/DefinitelyTyped,jimthedev/DefinitelyTyped,Saneyan/DefinitelyTyped,esperco/DefinitelyTyped,zuohaocheng/DefinitelyTyped,spearhead-ea/DefinitelyTyped,jbrantly/DefinitelyTyped,rschmukler/DefinitelyTyped,mszczepaniak/DefinitelyTyped,Penryn/DefinitelyTyped,wcomartin/DefinitelyTyped,applesaucers/lodash-invokeMap,maxlang/DefinitelyTyped,subash-a/DefinitelyTyped,mattblang/DefinitelyTyped,ErykB2000/DefinitelyTyped,Penryn/DefinitelyTyped,chbrown/DefinitelyTyped,ajtowf/DefinitelyTyped,scriby/DefinitelyTyped,TheBay0r/DefinitelyTyped,forumone/DefinitelyTyped,scsouthw/DefinitelyTyped,dsebastien/DefinitelyTyped,laco0416/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,jimthedev/DefinitelyTyped,xStrom/DefinitelyTyped,minodisk/DefinitelyTyped,duongphuhiep/DefinitelyTyped,alvarorahul/DefinitelyTyped,jraymakers/DefinitelyTyped,mwain/DefinitelyTyped,jeffbcross/DefinitelyTyped,zuzusik/DefinitelyTyped,gandjustas/DefinitelyTyped,vasek17/DefinitelyTyped,Dashlane/DefinitelyTyped,nojaf/DefinitelyTyped,gildorwang/DefinitelyTyped,teddyward/DefinitelyTyped,evandrewry/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,davidpricedev/DefinitelyTyped,herrmanno/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,abner/DefinitelyTyped,vpineda1996/DefinitelyTyped,grahammendick/DefinitelyTyped,fearthecowboy/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,AGBrown/DefinitelyTyped-ABContrib,abbasmhd/DefinitelyTyped,hafenr/DefinitelyTyped,wilfrem/DefinitelyTyped,flyfishMT/DefinitelyTyped,DeadAlready/DefinitelyTyped,adamcarr/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,xStrom/DefinitelyTyped,shahata/DefinitelyTyped,goaty92/DefinitelyTyped,hellopao/DefinitelyTyped,kalloc/DefinitelyTyped,KonaTeam/DefinitelyTyped,mshmelev/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,newclear/DefinitelyTyped,paxibay/DefinitelyTyped,OfficeDev/DefinitelyTyped,MugeSo/DefinitelyTyped,kuon/DefinitelyTyped,optical/DefinitelyTyped,dariajung/DefinitelyTyped,zuzusik/DefinitelyTyped,Mek7/DefinitelyTyped,bardt/DefinitelyTyped,AgentME/DefinitelyTyped,dragouf/DefinitelyTyped,isman-usoh/DefinitelyTyped,abner/DefinitelyTyped,brettle/DefinitelyTyped,dflor003/DefinitelyTyped,bencoveney/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,ashwinr/DefinitelyTyped,use-strict/DefinitelyTyped,dumbmatter/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,Zorgatone/DefinitelyTyped,gedaiu/DefinitelyTyped,glenndierckx/DefinitelyTyped,tomtarrot/DefinitelyTyped,gcastre/DefinitelyTyped,kmeurer/DefinitelyTyped,mendix/DefinitelyTyped,benishouga/DefinitelyTyped,Dominator008/DefinitelyTyped,MidnightDesign/DefinitelyTyped,damianog/DefinitelyTyped,nainslie/DefinitelyTyped,nfriend/DefinitelyTyped,stanislavHamara/DefinitelyTyped,robl499/DefinitelyTyped,nelsonmorais/DefinitelyTyped,psnider/DefinitelyTyped,Shiak1/DefinitelyTyped,nitintutlani/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jesseschalken/DefinitelyTyped,felipe3dfx/DefinitelyTyped,magny/DefinitelyTyped,nycdotnet/DefinitelyTyped,jimthedev/DefinitelyTyped,elisee/DefinitelyTyped,mattanja/DefinitelyTyped,magny/DefinitelyTyped,erosb/DefinitelyTyped,davidpricedev/DefinitelyTyped,gcastre/DefinitelyTyped,mrk21/DefinitelyTyped,tinganho/DefinitelyTyped,aindlq/DefinitelyTyped,igorraush/DefinitelyTyped,flyfishMT/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,musicist288/DefinitelyTyped,jasonswearingen/DefinitelyTyped,RX14/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,minodisk/DefinitelyTyped,arcticwaters/DefinitelyTyped,WritingPanda/DefinitelyTyped,takenet/DefinitelyTyped,stephenjelfs/DefinitelyTyped,rolandzwaga/DefinitelyTyped,Jwsonic/DefinitelyTyped,danfma/DefinitelyTyped,nakakura/DefinitelyTyped,Nemo157/DefinitelyTyped,giggio/DefinitelyTyped,arma-gast/DefinitelyTyped,bennett000/DefinitelyTyped,stylelab-io/DefinitelyTyped,mattanja/DefinitelyTyped,bkristensen/DefinitelyTyped,robertbaker/DefinitelyTyped,wilfrem/DefinitelyTyped,cherrydev/DefinitelyTyped,martinduparc/DefinitelyTyped,pwelter34/DefinitelyTyped,opichals/DefinitelyTyped,Riron/DefinitelyTyped,ecramer89/DefinitelyTyped,dydek/DefinitelyTyped,georgemarshall/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,dydek/DefinitelyTyped,hesselink/DefinitelyTyped,samwgoldman/DefinitelyTyped,zuzusik/DefinitelyTyped,OpenMaths/DefinitelyTyped,stephenjelfs/DefinitelyTyped,borisyankov/DefinitelyTyped,chadoliver/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions | ---
+++
@@ -0,0 +1,8 @@
+/// <reference path="angular-i18next.d.ts" />
+/**
+* @summary Test for "angular-i18next" with options.
+*/
+function testOptions() {
+ var $provider: I18nextProvider;
+ $provider.options = {};
+} |
|
5b75c217b2bfc753c94d4c1afb288fd069a8e312 | src/Test/Html/Escaping/Content.ts | src/Test/Html/Escaping/Content.ts | import { expect } from 'chai'
import Up from '../../../index'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
describe('All instances of "<" and "&" inside a plain text node', () => {
it('are replaced with "<" and "&", respectively', () => {
const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
})
})
| Add failing html escaping test | Add failing html escaping test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,11 @@
+import { expect } from 'chai'
+import Up from '../../../index'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+
+
+describe('All instances of "<" and "&" inside a plain text node', () => {
+ it('are replaced with "<" and "&", respectively', () => {
+ const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
+ expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
+ })
+}) |
|
2f9e9269c6cafbb58ef61cbdb2b3a6e18f65f19e | generator/processors/Microsoft.Authorization.ts | generator/processors/Microsoft.Authorization.ts | import { SchemaPostProcessor } from '../models';
export const postProcessor: SchemaPostProcessor = (_namespace: string, _apiVersion: string, schema: any) => {
const allowedValues = schema.definitions?.ParameterDefinitionsValue?.properties?.allowedValues;
if (allowedValues) {
const allowedValuesItems = allowedValues.oneOf[0]?.items
removeObjectType(allowedValuesItems);
}
const defaultValue = schema.definitions?.ParameterDefinitionsValue?.properties?.defaultValue;
removeObjectType(defaultValue);
const assignmentParameter = schema.definitions?.PolicyAssignmentProperties?.properties?.parameters;
removeObjectType(assignmentParameter);
const definitionParameter = schema.definitions?.PolicyDefinitionProperties?.properties?.parameters;
removeObjectType(definitionParameter);
const definitionReferenceParameter = schema.definitions?.PolicyDefinitionReference?.properties?.parameters;
removeObjectType(definitionReferenceParameter);
const setDefinitionParameter = schema.definitions?.PolicySetDefinitionProperties?.properties?.parameters;
removeObjectType(setDefinitionParameter);
}
function removeObjectType(property: any) {
if (property && property['type'] && property['type'] === 'object') {
delete property['type'];
delete property['properties'];
}
}
| Add post processor for policy | Add post processor for policy
| TypeScript | mit | Azure/azure-resource-manager-schemas,Azure/azure-resource-manager-schemas,Azure/azure-resource-manager-schemas,Azure/azure-resource-manager-schemas | ---
+++
@@ -0,0 +1,32 @@
+import { SchemaPostProcessor } from '../models';
+
+export const postProcessor: SchemaPostProcessor = (_namespace: string, _apiVersion: string, schema: any) => {
+ const allowedValues = schema.definitions?.ParameterDefinitionsValue?.properties?.allowedValues;
+ if (allowedValues) {
+ const allowedValuesItems = allowedValues.oneOf[0]?.items
+ removeObjectType(allowedValuesItems);
+ }
+
+ const defaultValue = schema.definitions?.ParameterDefinitionsValue?.properties?.defaultValue;
+ removeObjectType(defaultValue);
+
+ const assignmentParameter = schema.definitions?.PolicyAssignmentProperties?.properties?.parameters;
+ removeObjectType(assignmentParameter);
+
+ const definitionParameter = schema.definitions?.PolicyDefinitionProperties?.properties?.parameters;
+ removeObjectType(definitionParameter);
+
+ const definitionReferenceParameter = schema.definitions?.PolicyDefinitionReference?.properties?.parameters;
+ removeObjectType(definitionReferenceParameter);
+
+ const setDefinitionParameter = schema.definitions?.PolicySetDefinitionProperties?.properties?.parameters;
+ removeObjectType(setDefinitionParameter);
+}
+
+function removeObjectType(property: any) {
+ if (property && property['type'] && property['type'] === 'object') {
+ delete property['type'];
+ delete property['properties'];
+ }
+}
+ |
|
29ad6f9bbb72868b3fc17f3c9693f180bad40b99 | src/components/Avatar/index.ts | src/components/Avatar/index.ts | import { UIComponentSources, UIComponentSinks } from '../';
import xs, { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import { SvgIconSinks } from '../SvgIcon';
import { FontIconSinks } from '../FontIcon';
export interface AvatarSources extends UIComponentSources {
backgroundColor$?: Stream<string>;
children$?: Stream<VNode | string>;
color$?: Stream<string>;
icon$?: Stream<SvgIconSinks | FontIconSinks>;
size$?: Stream<number>;
src$?: Stream<string>;
}
export interface AvatarSinks extends UIComponentSinks { }
| Add structure to Avatar as a component | Add structure to Avatar as a component
| TypeScript | mit | cyclic-ui/cyclic-ui,cyclic-ui/cyclic-ui | ---
+++
@@ -0,0 +1,16 @@
+import { UIComponentSources, UIComponentSinks } from '../';
+import xs, { Stream } from 'xstream';
+import { VNode } from '@cycle/dom';
+import { SvgIconSinks } from '../SvgIcon';
+import { FontIconSinks } from '../FontIcon';
+
+export interface AvatarSources extends UIComponentSources {
+ backgroundColor$?: Stream<string>;
+ children$?: Stream<VNode | string>;
+ color$?: Stream<string>;
+ icon$?: Stream<SvgIconSinks | FontIconSinks>;
+ size$?: Stream<number>;
+ src$?: Stream<string>;
+}
+
+export interface AvatarSinks extends UIComponentSinks { } |
|
b9e49a45f5441fd1a2d49a10b88aaf4d425dc992 | scripts/simulate-many-viewers.ts | scripts/simulate-many-viewers.ts | import Bluebird from 'bluebird'
import { wait } from '@shared/core-utils'
import { createSingleServer, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/server-commands'
let servers: PeerTubeServer[]
const viewers: { xForwardedFor: string }[] = []
let videoId: string
run()
.then(() => process.exit(0))
.catch(err => console.error(err))
async function run () {
await prepare()
while (true) {
await runViewers()
}
}
async function prepare () {
console.log('Preparing servers...')
const config = {
log: {
level: 'info'
},
rates_limit: {
api: {
max: 5_000_000
}
},
views: {
videos: {
local_buffer_update_interval: '30 minutes',
ip_view_expiration: '1 hour'
}
}
}
servers = await Promise.all([
createSingleServer(1, config, { nodeArgs: [ '--inspect' ] }),
createSingleServer(2, config),
createSingleServer(3, config)
])
await setAccessTokensToServers(servers)
await doubleFollow(servers[0], servers[1])
await doubleFollow(servers[0], servers[2])
const { uuid } = await servers[0].videos.quickUpload({ name: 'video' })
videoId = uuid
await waitJobs(servers)
const THOUSAND_VIEWERS = 2
for (let i = 2; i < 252; i++) {
for (let j = 2; j < 6; j++) {
for (let k = 2; k < THOUSAND_VIEWERS + 2; k++) {
viewers.push({ xForwardedFor: `0.${k}.${j}.${i},127.0.0.1` })
}
}
}
console.log('Servers preparation finished.')
}
async function runViewers () {
console.log('Will run views of %d viewers.', viewers.length)
await Bluebird.map(viewers, viewer => {
return servers[0].views.simulateView({ id: videoId, xForwardedFor: viewer.xForwardedFor })
}, { concurrency: 100 })
await wait(5000)
}
| Add simulate many viewers script | Add simulate many viewers script
Helps us to improve views scalability on peertube
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -0,0 +1,77 @@
+import Bluebird from 'bluebird'
+import { wait } from '@shared/core-utils'
+import { createSingleServer, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/server-commands'
+
+let servers: PeerTubeServer[]
+const viewers: { xForwardedFor: string }[] = []
+let videoId: string
+
+run()
+ .then(() => process.exit(0))
+ .catch(err => console.error(err))
+
+async function run () {
+ await prepare()
+
+ while (true) {
+ await runViewers()
+ }
+}
+
+async function prepare () {
+ console.log('Preparing servers...')
+
+ const config = {
+ log: {
+ level: 'info'
+ },
+ rates_limit: {
+ api: {
+ max: 5_000_000
+ }
+ },
+ views: {
+ videos: {
+ local_buffer_update_interval: '30 minutes',
+ ip_view_expiration: '1 hour'
+ }
+ }
+ }
+
+ servers = await Promise.all([
+ createSingleServer(1, config, { nodeArgs: [ '--inspect' ] }),
+ createSingleServer(2, config),
+ createSingleServer(3, config)
+ ])
+
+ await setAccessTokensToServers(servers)
+ await doubleFollow(servers[0], servers[1])
+ await doubleFollow(servers[0], servers[2])
+
+ const { uuid } = await servers[0].videos.quickUpload({ name: 'video' })
+ videoId = uuid
+
+ await waitJobs(servers)
+
+ const THOUSAND_VIEWERS = 2
+
+ for (let i = 2; i < 252; i++) {
+ for (let j = 2; j < 6; j++) {
+ for (let k = 2; k < THOUSAND_VIEWERS + 2; k++) {
+ viewers.push({ xForwardedFor: `0.${k}.${j}.${i},127.0.0.1` })
+ }
+ }
+ }
+
+ console.log('Servers preparation finished.')
+}
+
+async function runViewers () {
+ console.log('Will run views of %d viewers.', viewers.length)
+
+ await Bluebird.map(viewers, viewer => {
+ return servers[0].views.simulateView({ id: videoId, xForwardedFor: viewer.xForwardedFor })
+ }, { concurrency: 100 })
+
+ await wait(5000)
+} |
|
b77004a09fc73e13d1e697279ba670cebe2ac34e | src/Test/Html/Config/Changes.ts | src/Test/Html/Config/Changes.ts | import { expect } from 'chai'
import { UpConfigArgs } from '../../../UpConfigArgs'
import { Up } from '../../../index'
import { SyntaxNode } from '../../../SyntaxNodes/SyntaxNode'
import { FootnoteNode } from '../../../SyntaxNodes/FootnoteNode'
function canBeProvidedMultipleWaysWithTheSameResult(
args: {
node: SyntaxNode,
htmlFromDefaultSettings: string
configChanges: UpConfigArgs,
conflictingConfigChanges: UpConfigArgs
}
): void {
const { node, htmlFromDefaultSettings, configChanges, conflictingConfigChanges } = args
describe("when provided to the default (static) toHtml method", () => {
it("does not alter subsequent calls to the default method", () => {
expect(Up.toHtml(node, configChanges)).to.be.eql(htmlFromDefaultSettings)
})
})
const whenProvidingConfigAtCreation =
new Up(configChanges).toHtml(node)
const whenProvidingChangesWhenCallingDefaultMethod =
Up.toHtml(node, configChanges)
const whenProvidingChangesWhenCallingtMethodOnObject =
new Up().toHtml(node, configChanges)
const whenOverwritingChangesProvidedAtCreation =
new Up(conflictingConfigChanges).toHtml(node, configChanges)
describe("when provided to an Up object's toHtml method", () => {
it("does not alter the Up object's original settings", () => {
const up = new Up(configChanges)
// We don't care about the result! We only care to ensure the original config settings weren't overwritten.
up.toHtml(node, conflictingConfigChanges)
expect(whenProvidingConfigAtCreation).to.be.eql(up.toHtml(node, configChanges))
})
})
describe('when provided to an Up object at creation', () => {
it('has the same result as providing the term when calling the (default) static toHtml method', () => {
expect(whenProvidingConfigAtCreation).to.be.eql(whenProvidingChangesWhenCallingDefaultMethod)
})
it("has the same result as providing the term when calling the Up object's toHtml method", () => {
expect(whenProvidingConfigAtCreation).to.be.eql(whenProvidingChangesWhenCallingtMethodOnObject)
})
it("has the same result as providing the term when calling the Up object's toHtml method, overwriting the term provided at creation", () => {
expect(whenProvidingConfigAtCreation).to.be.eql(whenOverwritingChangesProvidedAtCreation)
})
})
} | Add file/helper for config-change html tests | Add file/helper for config-change html tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,62 @@
+import { expect } from 'chai'
+import { UpConfigArgs } from '../../../UpConfigArgs'
+import { Up } from '../../../index'
+import { SyntaxNode } from '../../../SyntaxNodes/SyntaxNode'
+import { FootnoteNode } from '../../../SyntaxNodes/FootnoteNode'
+
+
+function canBeProvidedMultipleWaysWithTheSameResult(
+ args: {
+ node: SyntaxNode,
+ htmlFromDefaultSettings: string
+ configChanges: UpConfigArgs,
+ conflictingConfigChanges: UpConfigArgs
+ }
+): void {
+
+ const { node, htmlFromDefaultSettings, configChanges, conflictingConfigChanges } = args
+
+
+ describe("when provided to the default (static) toHtml method", () => {
+ it("does not alter subsequent calls to the default method", () => {
+ expect(Up.toHtml(node, configChanges)).to.be.eql(htmlFromDefaultSettings)
+ })
+ })
+
+ const whenProvidingConfigAtCreation =
+ new Up(configChanges).toHtml(node)
+
+ const whenProvidingChangesWhenCallingDefaultMethod =
+ Up.toHtml(node, configChanges)
+
+ const whenProvidingChangesWhenCallingtMethodOnObject =
+ new Up().toHtml(node, configChanges)
+
+ const whenOverwritingChangesProvidedAtCreation =
+ new Up(conflictingConfigChanges).toHtml(node, configChanges)
+
+ describe("when provided to an Up object's toHtml method", () => {
+ it("does not alter the Up object's original settings", () => {
+ const up = new Up(configChanges)
+
+ // We don't care about the result! We only care to ensure the original config settings weren't overwritten.
+ up.toHtml(node, conflictingConfigChanges)
+
+ expect(whenProvidingConfigAtCreation).to.be.eql(up.toHtml(node, configChanges))
+ })
+ })
+
+ describe('when provided to an Up object at creation', () => {
+ it('has the same result as providing the term when calling the (default) static toHtml method', () => {
+ expect(whenProvidingConfigAtCreation).to.be.eql(whenProvidingChangesWhenCallingDefaultMethod)
+ })
+
+ it("has the same result as providing the term when calling the Up object's toHtml method", () => {
+ expect(whenProvidingConfigAtCreation).to.be.eql(whenProvidingChangesWhenCallingtMethodOnObject)
+ })
+
+ it("has the same result as providing the term when calling the Up object's toHtml method, overwriting the term provided at creation", () => {
+ expect(whenProvidingConfigAtCreation).to.be.eql(whenOverwritingChangesProvidedAtCreation)
+ })
+ })
+} |
|
7ff81196eb4ea9a1b6c2be91ee68ea36b326df20 | src/dropzone/DropzoneDirective.ts | src/dropzone/DropzoneDirective.ts | import * as angular from 'angular';
import Dropzone = require('dropzone');
/**
* Define new interface to allow accessing '$ctrl' from scope
* https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18196
*/
interface IDropzoneDirectiveScope extends ng.IScope {
$ctrl: any;
}
export class DropzoneDirective implements ng.IDirective {
/**
* Match class name.
*/
public restrict: string = 'C';
/**
* Update the DOM to implement the directive.
*/
public link(
scope: IDropzoneDirectiveScope,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes
) {
let dropzoneConfig = {
url: scope.$ctrl.config.url
};
let eventHandlers = {
'sending': (file, xhr, formData) => {
// append AWS upload key to the form data
// needed in order to have a valid POST
formData.append('key', file.name);
}
};
let dropzone = new Dropzone(element[0], dropzoneConfig);
angular.forEach(eventHandlers, (handler, event) => {
dropzone.on(event, handler);
});
}
}
| Create a dropzone directive to handle dropzone events. | Create a dropzone directive to handle dropzone events.
Initialize the dropzone element in the directive and add event
handlers to handle the 'sending' event which triggers on each
file upload.
Modify the 'sending' event to append the 'key' form data required
for aws POSTs.
| TypeScript | bsd-3-clause | nimbis/s3commander,nimbis/s3commander,nimbis/s3commander,nimbis/s3commander | ---
+++
@@ -0,0 +1,45 @@
+import * as angular from 'angular';
+
+import Dropzone = require('dropzone');
+
+/**
+ * Define new interface to allow accessing '$ctrl' from scope
+ * https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18196
+ */
+interface IDropzoneDirectiveScope extends ng.IScope {
+ $ctrl: any;
+}
+
+export class DropzoneDirective implements ng.IDirective {
+ /**
+ * Match class name.
+ */
+ public restrict: string = 'C';
+
+ /**
+ * Update the DOM to implement the directive.
+ */
+ public link(
+ scope: IDropzoneDirectiveScope,
+ element: ng.IAugmentedJQuery,
+ attrs: ng.IAttributes
+ ) {
+ let dropzoneConfig = {
+ url: scope.$ctrl.config.url
+ };
+
+ let eventHandlers = {
+ 'sending': (file, xhr, formData) => {
+ // append AWS upload key to the form data
+ // needed in order to have a valid POST
+ formData.append('key', file.name);
+ }
+ };
+
+ let dropzone = new Dropzone(element[0], dropzoneConfig);
+
+ angular.forEach(eventHandlers, (handler, event) => {
+ dropzone.on(event, handler);
+ });
+ }
+} |
|
50b19c611f31b716b0281b9fe9a4ef0c1711c3e3 | test/helpers/string.ts | test/helpers/string.ts | import * as assert from "assert";
import * as mocha from "mocha";
import HelperString from "../../helpers/string";
describe("HelperString", function(): void {
describe("#toCamelCase", function(): void {
it("should lowercase single leading character", function(): void {
const result: string = HelperString.toCamelCase("Foo");
assert.equal(result, "foo");
});
it("should not lowercase multiple leading characters", function(): void {
const result: string = HelperString.toCamelCase("IFoo");
assert.equal(result, "iFoo");
});
it("should not lowercase non-leading characters", function(): void {
const result: string = HelperString.toCamelCase("IFooBar");
assert.equal(result, "iFooBar");
});
});
describe("#toLowerCamelCase", function(): void {
it("should lowercase single leading character", function(): void {
const result: string = HelperString.toLowerCamelCase("Foo");
assert.equal(result, "foo");
});
it("should lowercase multiple leading characters", function(): void {
const result: string = HelperString.toLowerCamelCase("IFoo");
assert.equal(result, "ifoo");
});
it("should not lowercase non-leading characters", function(): void {
const result: string = HelperString.toLowerCamelCase("IFooBar");
assert.equal(result, "ifooBar");
});
});
});
| Implement tests for HelperString methods | Implement tests for HelperString methods
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -0,0 +1,34 @@
+import * as assert from "assert";
+import * as mocha from "mocha";
+import HelperString from "../../helpers/string";
+
+describe("HelperString", function(): void {
+ describe("#toCamelCase", function(): void {
+ it("should lowercase single leading character", function(): void {
+ const result: string = HelperString.toCamelCase("Foo");
+ assert.equal(result, "foo");
+ });
+ it("should not lowercase multiple leading characters", function(): void {
+ const result: string = HelperString.toCamelCase("IFoo");
+ assert.equal(result, "iFoo");
+ });
+ it("should not lowercase non-leading characters", function(): void {
+ const result: string = HelperString.toCamelCase("IFooBar");
+ assert.equal(result, "iFooBar");
+ });
+ });
+ describe("#toLowerCamelCase", function(): void {
+ it("should lowercase single leading character", function(): void {
+ const result: string = HelperString.toLowerCamelCase("Foo");
+ assert.equal(result, "foo");
+ });
+ it("should lowercase multiple leading characters", function(): void {
+ const result: string = HelperString.toLowerCamelCase("IFoo");
+ assert.equal(result, "ifoo");
+ });
+ it("should not lowercase non-leading characters", function(): void {
+ const result: string = HelperString.toLowerCamelCase("IFooBar");
+ assert.equal(result, "ifooBar");
+ });
+ });
+}); |
|
bd6c24b6a355520c234aad776a2d8bc3f6a433b3 | src/actions/statusSummary.ts | src/actions/statusSummary.ts | import {
STATUS_SUMMARY_REQUEST,
STATUS_SUMMARY_FAILURE,
STATUS_SUMMARY_SUCCESS
} from '../constants';
export interface FetchStatusSummaryRequest {
readonly type: STATUS_SUMMARY_REQUEST;
}
export interface FetchStatusSummarySuccess {
readonly type: STATUS_SUMMARY_SUCCESS;
}
export interface FetchStatusSummaryFailure {
readonly type: STATUS_SUMMARY_FAILURE;
}
export const statusSummaryRequest = (): FetchStatusSummaryRequest => ({
type: STATUS_SUMMARY_REQUEST
});
export const statusSummarySuccess = (): FetchStatusSummarySuccess => ({
type: STATUS_SUMMARY_SUCCESS
});
export const statusSummaryFailure = (): FetchStatusSummaryFailure => ({
type: STATUS_SUMMARY_FAILURE
});
| Add action creators for fetching status Summary. | Add action creators for fetching status Summary.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,29 @@
+import {
+ STATUS_SUMMARY_REQUEST,
+ STATUS_SUMMARY_FAILURE,
+ STATUS_SUMMARY_SUCCESS
+} from '../constants';
+
+export interface FetchStatusSummaryRequest {
+ readonly type: STATUS_SUMMARY_REQUEST;
+}
+
+export interface FetchStatusSummarySuccess {
+ readonly type: STATUS_SUMMARY_SUCCESS;
+}
+
+export interface FetchStatusSummaryFailure {
+ readonly type: STATUS_SUMMARY_FAILURE;
+}
+
+export const statusSummaryRequest = (): FetchStatusSummaryRequest => ({
+ type: STATUS_SUMMARY_REQUEST
+});
+
+export const statusSummarySuccess = (): FetchStatusSummarySuccess => ({
+ type: STATUS_SUMMARY_SUCCESS
+});
+
+export const statusSummaryFailure = (): FetchStatusSummaryFailure => ({
+ type: STATUS_SUMMARY_FAILURE
+}); |
|
5f356cb9ef5db6050818c8ac59609687a0da882a | packages/thrift-client/src/tests/integration/profiler.spec.ts | packages/thrift-client/src/tests/integration/profiler.spec.ts | import { expect } from 'code'
import * as Hapi from 'hapi'
import * as Lab from 'lab'
import * as net from 'net'
import * as rp from 'request-promise-native'
import {
CLIENT_CONFIG,
} from './config'
import { createServer as addService } from './add-service'
import { createServer as calculatorService } from './calculator-service'
import { createServer as mockCollector } from './Observability/mock-collector'
import {
createClientServer,
} from './client'
export const lab = Lab.script()
const describe = lab.describe
const it = lab.it
const before = lab.before
const after = lab.after
const profile = () => {
const used = process.memoryUsage().heapUsed / 1024 / 1024
console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`)
}
describe('Observability', () => {
let calcServer: Hapi.Server
let addServer: Hapi.Server
let clientServer: net.Server
let collectServer: net.Server
before(async () => {
calcServer = calculatorService(1)
addServer = addService(1)
clientServer = await createClientServer(1)
collectServer = await mockCollector()
return Promise.all([
calcServer.start(),
addServer.start(),
]).then((err) => {
console.log('Thrift server running')
})
})
after(async () => {
clientServer.close()
collectServer.close()
return Promise.all([
calcServer.stop(),
addServer.stop(),
]).then((err) => {
console.log('Thrift server stopped')
})
})
it('should correctly trace request using B3 headers', (done: any) => {
const count: number = 100
let current: number = 0
let completed: number = 0
function runRequest(): void {
current += 1
profile()
rp(`http://${CLIENT_CONFIG.hostName}:${CLIENT_CONFIG.port}/calculate`, {
qs: {
left: 5,
op: 'add',
right: 9,
},
}).then(() => {
completed += 1
if (completed === count) {
profile()
expect(true).to.equal(true)
done()
}
})
setTimeout(() => {
if (current < count) {
runRequest()
}
}, Math.random() * 100)
}
runRequest()
})
})
| Add tests to profile memory usage | chore: Add tests to profile memory usage
| TypeScript | apache-2.0 | creditkarma/thrift-server,creditkarma/thrift-server | ---
+++
@@ -0,0 +1,94 @@
+import { expect } from 'code'
+import * as Hapi from 'hapi'
+import * as Lab from 'lab'
+import * as net from 'net'
+import * as rp from 'request-promise-native'
+
+import {
+ CLIENT_CONFIG,
+} from './config'
+
+import { createServer as addService } from './add-service'
+import { createServer as calculatorService } from './calculator-service'
+import { createServer as mockCollector } from './Observability/mock-collector'
+
+import {
+ createClientServer,
+} from './client'
+
+export const lab = Lab.script()
+
+const describe = lab.describe
+const it = lab.it
+const before = lab.before
+const after = lab.after
+
+const profile = () => {
+ const used = process.memoryUsage().heapUsed / 1024 / 1024
+ console.log(`The script uses approximately ${Math.round(used * 100) / 100} MB`)
+}
+
+describe('Observability', () => {
+ let calcServer: Hapi.Server
+ let addServer: Hapi.Server
+ let clientServer: net.Server
+ let collectServer: net.Server
+
+ before(async () => {
+ calcServer = calculatorService(1)
+ addServer = addService(1)
+ clientServer = await createClientServer(1)
+ collectServer = await mockCollector()
+ return Promise.all([
+ calcServer.start(),
+ addServer.start(),
+ ]).then((err) => {
+ console.log('Thrift server running')
+ })
+ })
+
+ after(async () => {
+ clientServer.close()
+ collectServer.close()
+ return Promise.all([
+ calcServer.stop(),
+ addServer.stop(),
+ ]).then((err) => {
+ console.log('Thrift server stopped')
+ })
+ })
+
+ it('should correctly trace request using B3 headers', (done: any) => {
+ const count: number = 100
+ let current: number = 0
+ let completed: number = 0
+
+ function runRequest(): void {
+ current += 1
+ profile()
+
+ rp(`http://${CLIENT_CONFIG.hostName}:${CLIENT_CONFIG.port}/calculate`, {
+ qs: {
+ left: 5,
+ op: 'add',
+ right: 9,
+ },
+ }).then(() => {
+ completed += 1
+ if (completed === count) {
+ profile()
+ expect(true).to.equal(true)
+ done()
+ }
+ })
+
+ setTimeout(() => {
+ if (current < count) {
+ runRequest()
+ }
+ }, Math.random() * 100)
+ }
+
+ runRequest()
+ })
+}) |
|
89a9441cd992f9e1e269d9edc276e4736390c2a2 | bokehjs/src/coffee/api/interfaces/document.ts | bokehjs/src/coffee/api/interfaces/document.ts | import {Model} from "./model";
type JsObj = {[key: string]: any};
export interface Document {
constructor(): void;
clear(): void;
roots(): Array<Model>;
add_root(model: Model): void;
remove_root(model: Model): void;
title(): string;
set_title(title: string): void;
get_model_by_id(model_id: string): Model;
get_model_by_name(name: string): Model;
on_change(callback: (event: DocumentChangedEvent) => void): void;
remove_on_change(callback: (event: DocumentChangedEvent) => void): void;
to_json_string(include_defaults?: boolean): string;
to_json(include_defaults?: boolean): JsObj;
}
interface DocumentStatic {
from_json_string(s: string): Document;
from_json(json: JsObj): Document;
}
export declare var Document: DocumentStatic;
export interface DocumentChangedEvent {}
export interface ModelChangedEvent extends DocumentChangedEvent {
constructor(document: Document, model: Model, attr: string, old: any, new_: any): void;
}
export interface TitleChangedEvent extends DocumentChangedEvent {
constructor(document: Document, title: string): void;
}
export interface RootAddedEvent extends DocumentChangedEvent {
constructor(document: Document, model: Model): void;
}
export interface RootRemovedEvent extends DocumentChangedEvent {
constructor(document: Document, model: Model): void;
}
| Add typings for Document class and its events | Add typings for Document class and its events
| TypeScript | bsd-3-clause | KasperPRasmussen/bokeh,DuCorey/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,KasperPRasmussen/bokeh,schoolie/bokeh,mindriot101/bokeh,jakirkham/bokeh,azjps/bokeh,aavanian/bokeh,mindriot101/bokeh,azjps/bokeh,ptitjano/bokeh,azjps/bokeh,timsnyder/bokeh,percyfal/bokeh,jakirkham/bokeh,quasiben/bokeh,justacec/bokeh,aavanian/bokeh,aavanian/bokeh,justacec/bokeh,philippjfr/bokeh,ptitjano/bokeh,clairetang6/bokeh,phobson/bokeh,stonebig/bokeh,aavanian/bokeh,phobson/bokeh,dennisobrien/bokeh,phobson/bokeh,bokeh/bokeh,ericmjl/bokeh,ptitjano/bokeh,timsnyder/bokeh,philippjfr/bokeh,justacec/bokeh,ericmjl/bokeh,rs2/bokeh,ericmjl/bokeh,aavanian/bokeh,stonebig/bokeh,bokeh/bokeh,timsnyder/bokeh,rs2/bokeh,bokeh/bokeh,clairetang6/bokeh,percyfal/bokeh,ptitjano/bokeh,percyfal/bokeh,draperjames/bokeh,percyfal/bokeh,draperjames/bokeh,phobson/bokeh,bokeh/bokeh,dennisobrien/bokeh,jakirkham/bokeh,mindriot101/bokeh,schoolie/bokeh,DuCorey/bokeh,draperjames/bokeh,azjps/bokeh,schoolie/bokeh,dennisobrien/bokeh,philippjfr/bokeh,ericmjl/bokeh,aiguofer/bokeh,stonebig/bokeh,aiguofer/bokeh,Karel-van-de-Plassche/bokeh,quasiben/bokeh,phobson/bokeh,schoolie/bokeh,schoolie/bokeh,timsnyder/bokeh,ericmjl/bokeh,azjps/bokeh,draperjames/bokeh,dennisobrien/bokeh,KasperPRasmussen/bokeh,rs2/bokeh,quasiben/bokeh,draperjames/bokeh,DuCorey/bokeh,philippjfr/bokeh,ptitjano/bokeh,philippjfr/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,mindriot101/bokeh,jakirkham/bokeh,timsnyder/bokeh,aiguofer/bokeh,KasperPRasmussen/bokeh,Karel-van-de-Plassche/bokeh,aiguofer/bokeh,percyfal/bokeh,bokeh/bokeh,Karel-van-de-Plassche/bokeh,dennisobrien/bokeh,clairetang6/bokeh,rs2/bokeh,stonebig/bokeh,aiguofer/bokeh,clairetang6/bokeh,rs2/bokeh,DuCorey/bokeh,Karel-van-de-Plassche/bokeh,justacec/bokeh | ---
+++
@@ -0,0 +1,48 @@
+import {Model} from "./model";
+
+type JsObj = {[key: string]: any};
+
+export interface Document {
+ constructor(): void;
+
+ clear(): void;
+ roots(): Array<Model>;
+ add_root(model: Model): void;
+ remove_root(model: Model): void;
+
+ title(): string;
+ set_title(title: string): void;
+ get_model_by_id(model_id: string): Model;
+ get_model_by_name(name: string): Model;
+
+ on_change(callback: (event: DocumentChangedEvent) => void): void;
+ remove_on_change(callback: (event: DocumentChangedEvent) => void): void;
+
+ to_json_string(include_defaults?: boolean): string;
+ to_json(include_defaults?: boolean): JsObj;
+}
+
+interface DocumentStatic {
+ from_json_string(s: string): Document;
+ from_json(json: JsObj): Document;
+}
+
+export declare var Document: DocumentStatic;
+
+export interface DocumentChangedEvent {}
+
+export interface ModelChangedEvent extends DocumentChangedEvent {
+ constructor(document: Document, model: Model, attr: string, old: any, new_: any): void;
+}
+
+export interface TitleChangedEvent extends DocumentChangedEvent {
+ constructor(document: Document, title: string): void;
+}
+
+export interface RootAddedEvent extends DocumentChangedEvent {
+ constructor(document: Document, model: Model): void;
+}
+
+export interface RootRemovedEvent extends DocumentChangedEvent {
+ constructor(document: Document, model: Model): void;
+} |
|
ec6eb9ebdea6480af4549f6dd6a2d2a5faf3b40e | src/scripts/googleTrendsAnalysis.ts | src/scripts/googleTrendsAnalysis.ts | import * as wpdb from '../articles/wpdb'
import * as fs from 'fs-extra'
const googleTrends = require('google-trends-api')
async function main() {
/*await wpdb.connect()
const categories = await wpdb.getEntriesByCategory()
const titles = []
for (const category of categories) {
for (const entry of category.entries) {
titles.push(entry.title)
}
}
const data = []
for (const title of titles) {
const related = await googleTrends.relatedQueries({ keyword: title })
console.log(related)
data.push(related)
}
console.log(data)
await wpdb.end()*/
const file = await fs.readFile("/Users/mispy/tmp/trends.json", "utf8")
const queries = JSON.parse(file)
for (const query of queries) {
console.log(JSON.stringify(query.default.rankedList[0].rankedKeyword.map((v: any) => `${v.query} ${v.value}`)))
}
}
main() | Add initial google trends analysis script | Add initial google trends analysis script
| TypeScript | mit | OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,owid/owid-grapher | ---
+++
@@ -0,0 +1,32 @@
+import * as wpdb from '../articles/wpdb'
+import * as fs from 'fs-extra'
+const googleTrends = require('google-trends-api')
+
+async function main() {
+ /*await wpdb.connect()
+ const categories = await wpdb.getEntriesByCategory()
+ const titles = []
+ for (const category of categories) {
+ for (const entry of category.entries) {
+ titles.push(entry.title)
+ }
+ }
+
+ const data = []
+ for (const title of titles) {
+ const related = await googleTrends.relatedQueries({ keyword: title })
+ console.log(related)
+ data.push(related)
+ }
+ console.log(data)
+
+ await wpdb.end()*/
+
+ const file = await fs.readFile("/Users/mispy/tmp/trends.json", "utf8")
+ const queries = JSON.parse(file)
+ for (const query of queries) {
+ console.log(JSON.stringify(query.default.rankedList[0].rankedKeyword.map((v: any) => `${v.query} ${v.value}`)))
+ }
+}
+
+main() |
|
e290559057f3c84b27c5057b4d12951d46c35863 | tests/cases/conformance/types/tuple/readonlyArraysAndTuples2.ts | tests/cases/conformance/types/tuple/readonlyArraysAndTuples2.ts | // @strict: true
// @declaration: true
// @emitDecoratorMetadata: true
// @experimentalDecorators: true
type T10 = string[];
type T11 = Array<string>;
type T12 = readonly string[];
type T13 = ReadonlyArray<string>;
type T20 = [number, number];
type T21 = readonly [number, number];
declare function f1(ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]): readonly [string, string];
declare const someDec: any;
class A {
@someDec
j: readonly string[] = [];
@someDec
k: readonly [string, number] = ['foo', 42];
}
| Add tests for decorators and declaration emit from error free source | Add tests for decorators and declaration emit from error free source
| TypeScript | apache-2.0 | SaschaNaz/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,minestarks/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,kpreisser/TypeScript,alexeagle/TypeScript,alexeagle/TypeScript,Microsoft/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,weswigham/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,weswigham/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,nojvek/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,Microsoft/TypeScript | ---
+++
@@ -0,0 +1,23 @@
+// @strict: true
+// @declaration: true
+// @emitDecoratorMetadata: true
+// @experimentalDecorators: true
+
+type T10 = string[];
+type T11 = Array<string>;
+type T12 = readonly string[];
+type T13 = ReadonlyArray<string>;
+
+type T20 = [number, number];
+type T21 = readonly [number, number];
+
+declare function f1(ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]): readonly [string, string];
+
+declare const someDec: any;
+
+class A {
+ @someDec
+ j: readonly string[] = [];
+ @someDec
+ k: readonly [string, number] = ['foo', 42];
+} |
|
56fe305d81a37be6c43376172ed85fa1230414f3 | ui/common/src/wheel.ts | ui/common/src/wheel.ts | export default function shouldScroll(e: WheelEvent, threshold: number): boolean {
/** Track distance scrolled across multiple wheel events, resetting after 500 ms. */
const lastScrollDirection = lichess.tempStorage.get('lastScrollDirection');
let scrollTotal = parseInt(lichess.tempStorage.get('scrollTotal') || '0');
const lastScrollTimestamp = parseFloat(lichess.tempStorage.get('lastScrollTimestamp') || '-9999');
let ret = false;
if (e.deltaY > 0) {
if (lastScrollDirection != 'forward' || e.timeStamp - lastScrollTimestamp > 500) scrollTotal = 0;
lichess.tempStorage.set('lastScrollDirection', 'forward');
scrollTotal += e.deltaY;
if (scrollTotal >= threshold) {
ret = true;
scrollTotal -= threshold;
}
} else if (e.deltaY < 0) {
if (lastScrollDirection != 'back' || e.timeStamp - lastScrollTimestamp > 500) scrollTotal = 0;
lichess.tempStorage.set('lastScrollDirection', 'back');
scrollTotal -= e.deltaY;
if (scrollTotal >= threshold) {
ret = true;
scrollTotal -= threshold;
}
}
lichess.tempStorage.set('scrollTotal', scrollTotal.toString());
lichess.tempStorage.set('lastScrollTimestamp', e.timeStamp.toString());
return ret;
}
| Add common function for tracking scroll distance | Add common function for tracking scroll distance
| TypeScript | agpl-3.0 | arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila,arex1337/lila | ---
+++
@@ -0,0 +1,27 @@
+export default function shouldScroll(e: WheelEvent, threshold: number): boolean {
+ /** Track distance scrolled across multiple wheel events, resetting after 500 ms. */
+ const lastScrollDirection = lichess.tempStorage.get('lastScrollDirection');
+ let scrollTotal = parseInt(lichess.tempStorage.get('scrollTotal') || '0');
+ const lastScrollTimestamp = parseFloat(lichess.tempStorage.get('lastScrollTimestamp') || '-9999');
+ let ret = false;
+ if (e.deltaY > 0) {
+ if (lastScrollDirection != 'forward' || e.timeStamp - lastScrollTimestamp > 500) scrollTotal = 0;
+ lichess.tempStorage.set('lastScrollDirection', 'forward');
+ scrollTotal += e.deltaY;
+ if (scrollTotal >= threshold) {
+ ret = true;
+ scrollTotal -= threshold;
+ }
+ } else if (e.deltaY < 0) {
+ if (lastScrollDirection != 'back' || e.timeStamp - lastScrollTimestamp > 500) scrollTotal = 0;
+ lichess.tempStorage.set('lastScrollDirection', 'back');
+ scrollTotal -= e.deltaY;
+ if (scrollTotal >= threshold) {
+ ret = true;
+ scrollTotal -= threshold;
+ }
+ }
+ lichess.tempStorage.set('scrollTotal', scrollTotal.toString());
+ lichess.tempStorage.set('lastScrollTimestamp', e.timeStamp.toString());
+ return ret;
+} |
|
1de7a769ebc87d83ba6231af585aa0a79ed4c859 | __mocks__/@stencil/state-tunnel.tsx | __mocks__/@stencil/state-tunnel.tsx | var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
function defaultConsumerRender(subscribe, child) {
return h("context-consumer", { subscribe: subscribe, renderer: child });
}
export function createProviderConsumer(defaultState, consumerRender = defaultConsumerRender) {
let listeners = new Map();
let currentState = defaultState;
function notifyConsumers() {
listeners.forEach(updateListener);
}
function updateListener(fields, listener) {
if (Array.isArray(fields)) {
[...fields].forEach(fieldName => {
listener[fieldName] = currentState[fieldName];
});
}
else {
listener[fields] = Object.assign({}, currentState);
}
listener.forceUpdate();
}
function attachListener(propList) {
return (el) => {
if (listeners.has(el)) {
return;
}
listeners.set(el, propList);
updateListener(propList, el);
};
}
function subscribe(el, propList) {
attachListener(propList)(el);
return function () {
listeners.delete(el);
};
}
const Provider = ({ state }, children) => {
currentState = state;
notifyConsumers();
return children;
};
const Consumer = (props, children) => {
return consumerRender(subscribe, children[0]);
};
function wrapConsumer(childComponent, fieldList) {
const Child = childComponent.is;
return (_a) => {
var { children } = _a, props = __rest(_a, ["children"]);
return (h(Child, Object.assign({ ref: attachListener(fieldList) }, props), children));
};
}
function injectProps(childComponent, fieldList) {
let unsubscribe = null;
const elementRefName = Object.keys(childComponent.properties).find(propName => {
return childComponent.properties[propName].elementRef == true;
});
if (elementRefName == undefined) {
throw new Error(`Please ensure that your Component ${childComponent.is} has an attribtue with "@Element" decorator. ` +
`This is required to be able to inject properties.`);
}
const prevComponentWillLoad = childComponent.prototype.componentWillLoad;
childComponent.prototype.componentWillLoad = function () {
unsubscribe = subscribe(this[elementRefName], fieldList);
if (prevComponentWillLoad) {
return prevComponentWillLoad.bind(this)();
}
};
const prevComponentDidUnload = childComponent.prototype.componentDidUnload;
childComponent.prototype.componentDidUnload = function () {
unsubscribe();
if (prevComponentDidUnload) {
return prevComponentDidUnload.bind(this)();
}
};
}
return {
Provider,
Consumer,
wrapConsumer,
injectProps
};
}
| Add jest's mock feature and mocking state_tunnel to resolve test error | Add jest's mock feature and mocking state_tunnel to resolve test error
| TypeScript | mit | scania/corporate-ui,scania/corporate-ui | ---
+++
@@ -0,0 +1,90 @@
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
+ t[p[i]] = s[p[i]];
+ return t;
+};
+function defaultConsumerRender(subscribe, child) {
+ return h("context-consumer", { subscribe: subscribe, renderer: child });
+}
+export function createProviderConsumer(defaultState, consumerRender = defaultConsumerRender) {
+ let listeners = new Map();
+ let currentState = defaultState;
+ function notifyConsumers() {
+ listeners.forEach(updateListener);
+ }
+ function updateListener(fields, listener) {
+ if (Array.isArray(fields)) {
+ [...fields].forEach(fieldName => {
+ listener[fieldName] = currentState[fieldName];
+ });
+ }
+ else {
+ listener[fields] = Object.assign({}, currentState);
+ }
+ listener.forceUpdate();
+ }
+ function attachListener(propList) {
+ return (el) => {
+ if (listeners.has(el)) {
+ return;
+ }
+ listeners.set(el, propList);
+ updateListener(propList, el);
+ };
+ }
+ function subscribe(el, propList) {
+ attachListener(propList)(el);
+ return function () {
+ listeners.delete(el);
+ };
+ }
+ const Provider = ({ state }, children) => {
+ currentState = state;
+ notifyConsumers();
+ return children;
+ };
+ const Consumer = (props, children) => {
+ return consumerRender(subscribe, children[0]);
+ };
+ function wrapConsumer(childComponent, fieldList) {
+ const Child = childComponent.is;
+ return (_a) => {
+ var { children } = _a, props = __rest(_a, ["children"]);
+ return (h(Child, Object.assign({ ref: attachListener(fieldList) }, props), children));
+ };
+ }
+ function injectProps(childComponent, fieldList) {
+ let unsubscribe = null;
+ const elementRefName = Object.keys(childComponent.properties).find(propName => {
+ return childComponent.properties[propName].elementRef == true;
+ });
+ if (elementRefName == undefined) {
+ throw new Error(`Please ensure that your Component ${childComponent.is} has an attribtue with "@Element" decorator. ` +
+ `This is required to be able to inject properties.`);
+ }
+ const prevComponentWillLoad = childComponent.prototype.componentWillLoad;
+ childComponent.prototype.componentWillLoad = function () {
+ unsubscribe = subscribe(this[elementRefName], fieldList);
+ if (prevComponentWillLoad) {
+ return prevComponentWillLoad.bind(this)();
+ }
+ };
+ const prevComponentDidUnload = childComponent.prototype.componentDidUnload;
+ childComponent.prototype.componentDidUnload = function () {
+ unsubscribe();
+ if (prevComponentDidUnload) {
+ return prevComponentDidUnload.bind(this)();
+ }
+ };
+ }
+ return {
+ Provider,
+ Consumer,
+ wrapConsumer,
+ injectProps
+ };
+} |
|
e581b0f1a29fcf70964b9ad73ed482ac642f7e32 | packages/glimmer-util/lib/assert.ts | packages/glimmer-util/lib/assert.ts | import Logger from './logger';
// let alreadyWarned = false;
export function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || "assertion failure");
}
}
export function prodAssert() {}
export default debugAssert;
| // import Logger from './logger';
// let alreadyWarned = false;
export function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || "assertion failure");
}
}
export function prodAssert() {}
export default debugAssert;
| Comment out (now) unused import | Comment out (now) unused import
| TypeScript | mit | lbdm44/glimmer-vm,glimmerjs/glimmer-vm,tildeio/glimmer,tildeio/glimmer,glimmerjs/glimmer-vm,tildeio/glimmer,lbdm44/glimmer-vm,chadhietala/glimmer,chadhietala/glimmer,chadhietala/glimmer,glimmerjs/glimmer-vm,chadhietala/glimmer,lbdm44/glimmer-vm | ---
+++
@@ -1,4 +1,4 @@
-import Logger from './logger';
+// import Logger from './logger';
// let alreadyWarned = false;
|
e1df7e8969d491c46afae4d2c88d72d744b46721 | tests/typescript.ts | tests/typescript.ts | // Test file to check Typescript types for the .js dist
import noUiSlider from 'dist/nouislider.js';
const element: HTMLElement|null = document.querySelector('#slider');
if (element) {
noUiSlider.create(element, {
start: [20, 50],
range: {
min: 0,
'50%': 30,
max: 100
}
});
const range = {
min: 0,
'50%': 30,
max: 100
};
noUiSlider.create(element, {
start: [20, 50],
range: range
});
}
| Add test file to check Typescript types for the .js dist | Add test file to check Typescript types for the .js dist
| TypeScript | mit | leongersen/noUiSlider,leongersen/noUiSlider,leongersen/noUiSlider,leongersen/noUiSlider | ---
+++
@@ -0,0 +1,27 @@
+// Test file to check Typescript types for the .js dist
+import noUiSlider from 'dist/nouislider.js';
+
+const element: HTMLElement|null = document.querySelector('#slider');
+
+if (element) {
+
+ noUiSlider.create(element, {
+ start: [20, 50],
+ range: {
+ min: 0,
+ '50%': 30,
+ max: 100
+ }
+ });
+
+ const range = {
+ min: 0,
+ '50%': 30,
+ max: 100
+ };
+
+ noUiSlider.create(element, {
+ start: [20, 50],
+ range: range
+ });
+} |
|
d6fe5776f8d135b3293e5fa2f9d01f8417ffab9d | jsonwebtoken/jsonwebtoken-tests.ts | jsonwebtoken/jsonwebtoken-tests.ts | /**
* Test suite created by Maxime LUCE <https://github.com/SomaticIT>
*
* Created by using code samples from https://github.com/auth0/node-jsonwebtoken.
*/
/// <reference path="../node/node.d.ts" />
/// <reference path="jsonwebtoken.d.ts" />
import jwt = require("jsonwebtoken");
import fs = require("fs");
var token: string;
var cert: Buffer;
/**
* jwt.sign
* https://github.com/auth0/node-jsonwebtoken#usage
*/
// sign with default (HMAC SHA256)
token = jwt.sign({ foo: 'bar' }, 'shhhhh');
// sign with RSA SHA256
cert = fs.readFileSync('private.key'); // get private key
token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});
/**
* jwt.verify
* https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
*/
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
// verify a token asymmetric
cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
// verify audience
cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
// if audience mismatch, err == invalid audience
});
// verify issuer
cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
// if issuer mismatch, err == invalid issuer
});
/**
* jwt.decode
* https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken
*/
var decoded = jwt.decode(token);
| Add test suite for jsonwebtoken package | Add test suite for jsonwebtoken package
| TypeScript | mit | GlennQuirynen/DefinitelyTyped,MugeSo/DefinitelyTyped,jimthedev/DefinitelyTyped,muenchdo/DefinitelyTyped,abner/DefinitelyTyped,mareek/DefinitelyTyped,daptiv/DefinitelyTyped,onecentlin/DefinitelyTyped,stanislavHamara/DefinitelyTyped,alvarorahul/DefinitelyTyped,nitintutlani/DefinitelyTyped,jacqt/DefinitelyTyped,one-pieces/DefinitelyTyped,sclausen/DefinitelyTyped,dsebastien/DefinitelyTyped,smrq/DefinitelyTyped,rfranco/DefinitelyTyped,aqua89/DefinitelyTyped,RX14/DefinitelyTyped,zuzusik/DefinitelyTyped,OpenMaths/DefinitelyTyped,algorithme/DefinitelyTyped,stephenjelfs/DefinitelyTyped,arusakov/DefinitelyTyped,mcrawshaw/DefinitelyTyped,awerlang/DefinitelyTyped,jiaz/DefinitelyTyped,Dominator008/DefinitelyTyped,micurs/DefinitelyTyped,basp/DefinitelyTyped,mcrawshaw/DefinitelyTyped,alextkachman/DefinitelyTyped,brentonhouse/DefinitelyTyped,tomtarrot/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,miguelmq/DefinitelyTyped,markogresak/DefinitelyTyped,Zenorbi/DefinitelyTyped,martinduparc/DefinitelyTyped,furny/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,gandjustas/DefinitelyTyped,nitintutlani/DefinitelyTyped,Syati/DefinitelyTyped,NCARalph/DefinitelyTyped,mhegazy/DefinitelyTyped,JaminFarr/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,psnider/DefinitelyTyped,sledorze/DefinitelyTyped,Ridermansb/DefinitelyTyped,chrismbarr/DefinitelyTyped,georgemarshall/DefinitelyTyped,lbguilherme/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,mjjames/DefinitelyTyped,ashwinr/DefinitelyTyped,fredgalvao/DefinitelyTyped,haskellcamargo/DefinitelyTyped,Karabur/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,rolandzwaga/DefinitelyTyped,danfma/DefinitelyTyped,kanreisa/DefinitelyTyped,opichals/DefinitelyTyped,stacktracejs/DefinitelyTyped,olemp/DefinitelyTyped,bobslaede/DefinitelyTyped,benliddicott/DefinitelyTyped,UzEE/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,Karabur/DefinitelyTyped,aciccarello/DefinitelyTyped,chrilith/DefinitelyTyped,reppners/DefinitelyTyped,timjk/DefinitelyTyped,biomassives/DefinitelyTyped,herrmanno/DefinitelyTyped,shiwano/DefinitelyTyped,ml-workshare/DefinitelyTyped,frogcjn/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,samdark/DefinitelyTyped,hellopao/DefinitelyTyped,RX14/DefinitelyTyped,flyfishMT/DefinitelyTyped,tgfjt/DefinitelyTyped,yuit/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,gildorwang/DefinitelyTyped,jpevarnek/DefinitelyTyped,alextkachman/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,mshmelev/DefinitelyTyped,miguelmq/DefinitelyTyped,xStrom/DefinitelyTyped,Almouro/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,igorsechyn/DefinitelyTyped,bennett000/DefinitelyTyped,MidnightDesign/DefinitelyTyped,sandersky/DefinitelyTyped,GregOnNet/DefinitelyTyped,Dashlane/DefinitelyTyped,pocesar/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,progre/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,scatcher/DefinitelyTyped,hatz48/DefinitelyTyped,stacktracejs/DefinitelyTyped,wilfrem/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,jraymakers/DefinitelyTyped,Penryn/DefinitelyTyped,nycdotnet/DefinitelyTyped,lseguin42/DefinitelyTyped,minodisk/DefinitelyTyped,xswordsx/DefinitelyTyped,dydek/DefinitelyTyped,tan9/DefinitelyTyped,donnut/DefinitelyTyped,drinchev/DefinitelyTyped,AGBrown/DefinitelyTyped-ABContrib,subjectix/DefinitelyTyped,esperco/DefinitelyTyped,pwelter34/DefinitelyTyped,musakarakas/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,UzEE/DefinitelyTyped,TildaLabs/DefinitelyTyped,nobuoka/DefinitelyTyped,abner/DefinitelyTyped,rockclimber90/DefinitelyTyped,brettle/DefinitelyTyped,jsaelhof/DefinitelyTyped,optical/DefinitelyTyped,axelcostaspena/DefinitelyTyped,pkhayundi/DefinitelyTyped,wilfrem/DefinitelyTyped,frogcjn/DefinitelyTyped,minodisk/DefinitelyTyped,samwgoldman/DefinitelyTyped,modifyink/DefinitelyTyped,ducin/DefinitelyTyped,takfjt/DefinitelyTyped,arcticwaters/DefinitelyTyped,DeadAlready/DefinitelyTyped,mwain/DefinitelyTyped,raijinsetsu/DefinitelyTyped,EnableSoftware/DefinitelyTyped,chbrown/DefinitelyTyped,KonaTeam/DefinitelyTyped,robert-voica/DefinitelyTyped,jbrantly/DefinitelyTyped,rerezz/DefinitelyTyped,psnider/DefinitelyTyped,jimthedev/DefinitelyTyped,onecentlin/DefinitelyTyped,aindlq/DefinitelyTyped,mszczepaniak/DefinitelyTyped,HPFOD/DefinitelyTyped,quantumman/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,mweststrate/DefinitelyTyped,wbuchwalter/DefinitelyTyped,borisyankov/DefinitelyTyped,teddyward/DefinitelyTyped,tomtheisen/DefinitelyTyped,sixinli/DefinitelyTyped,masonkmeyer/DefinitelyTyped,olivierlemasle/DefinitelyTyped,dydek/DefinitelyTyped,robertbaker/DefinitelyTyped,GodsBreath/DefinitelyTyped,acepoblete/DefinitelyTyped,ecramer89/DefinitelyTyped,hypno2000/typings,giggio/DefinitelyTyped,Deathspike/DefinitelyTyped,elisee/DefinitelyTyped,gcastre/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,HereSinceres/DefinitelyTyped,arusakov/DefinitelyTyped,Syati/DefinitelyTyped,benishouga/DefinitelyTyped,Saneyan/DefinitelyTyped,Zzzen/DefinitelyTyped,yuit/DefinitelyTyped,Dominator008/DefinitelyTyped,bpowers/DefinitelyTyped,Dashlane/DefinitelyTyped,teves-castro/DefinitelyTyped,fredgalvao/DefinitelyTyped,igorraush/DefinitelyTyped,YousefED/DefinitelyTyped,jeremyhayes/DefinitelyTyped,davidpricedev/DefinitelyTyped,Seltzer/DefinitelyTyped,behzad888/DefinitelyTyped,hesselink/DefinitelyTyped,adammartin1981/DefinitelyTyped,tscho/DefinitelyTyped,vote539/DefinitelyTyped,syuilo/DefinitelyTyped,drinchev/DefinitelyTyped,fnipo/DefinitelyTyped,Pro/DefinitelyTyped,aciccarello/DefinitelyTyped,shahata/DefinitelyTyped,bencoveney/DefinitelyTyped,amanmahajan7/DefinitelyTyped,modifyink/DefinitelyTyped,Jwsonic/DefinitelyTyped,philippstucki/DefinitelyTyped,scriby/DefinitelyTyped,Zzzen/DefinitelyTyped,omidkrad/DefinitelyTyped,hatz48/DefinitelyTyped,jasonswearingen/DefinitelyTyped,angelobelchior8/DefinitelyTyped,superduper/DefinitelyTyped,teves-castro/DefinitelyTyped,TheBay0r/DefinitelyTyped,mjjames/DefinitelyTyped,nmalaguti/DefinitelyTyped,scsouthw/DefinitelyTyped,dumbmatter/DefinitelyTyped,rcchen/DefinitelyTyped,georgemarshall/DefinitelyTyped,musically-ut/DefinitelyTyped,syntax42/DefinitelyTyped,danfma/DefinitelyTyped,use-strict/DefinitelyTyped,lbesson/DefinitelyTyped,HPFOD/DefinitelyTyped,LordJZ/DefinitelyTyped,chrismbarr/DefinitelyTyped,MugeSo/DefinitelyTyped,nojaf/DefinitelyTyped,glenndierckx/DefinitelyTyped,philippstucki/DefinitelyTyped,mattblang/DefinitelyTyped,jtlan/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,eugenpodaru/DefinitelyTyped,jsaelhof/DefinitelyTyped,dflor003/DefinitelyTyped,mendix/DefinitelyTyped,bruennijs/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,elisee/DefinitelyTyped,ciriarte/DefinitelyTyped,erosb/DefinitelyTyped,bjfletcher/DefinitelyTyped,mareek/DefinitelyTyped,Gmulti/DefinitelyTyped,abbasmhd/DefinitelyTyped,hiraash/DefinitelyTyped,Trapulo/DefinitelyTyped,DenEwout/DefinitelyTyped,bdoss/DefinitelyTyped,mvarblow/DefinitelyTyped,subash-a/DefinitelyTyped,ajtowf/DefinitelyTyped,Riron/DefinitelyTyped,gyohk/DefinitelyTyped,nainslie/DefinitelyTyped,nobuoka/DefinitelyTyped,evansolomon/DefinitelyTyped,alexdresko/DefinitelyTyped,newclear/DefinitelyTyped,greglo/DefinitelyTyped,flyfishMT/DefinitelyTyped,newclear/DefinitelyTyped,zuzusik/DefinitelyTyped,dmoonfire/DefinitelyTyped,olemp/DefinitelyTyped,gorcz/DefinitelyTyped,munxar/DefinitelyTyped,OpenMaths/DefinitelyTyped,arusakov/DefinitelyTyped,timramone/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,mrozhin/DefinitelyTyped,bkristensen/DefinitelyTyped,raijinsetsu/DefinitelyTyped,gyohk/DefinitelyTyped,dwango-js/DefinitelyTyped,philippsimon/DefinitelyTyped,aciccarello/DefinitelyTyped,davidsidlinger/DefinitelyTyped,Ptival/DefinitelyTyped,PascalSenn/DefinitelyTyped,the41/DefinitelyTyped,MarlonFan/DefinitelyTyped,ashwinr/DefinitelyTyped,nodeframe/DefinitelyTyped,use-strict/DefinitelyTyped,felipe3dfx/DefinitelyTyped,rushi216/DefinitelyTyped,isman-usoh/DefinitelyTyped,behzad888/DefinitelyTyped,mcliment/DefinitelyTyped,cherrydev/DefinitelyTyped,alexdresko/DefinitelyTyped,Mek7/DefinitelyTyped,isman-usoh/DefinitelyTyped,takenet/DefinitelyTyped,almstrand/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,Pipe-shen/DefinitelyTyped,georgemarshall/DefinitelyTyped,kuon/DefinitelyTyped,alainsahli/DefinitelyTyped,AgentME/DefinitelyTyped,johan-gorter/DefinitelyTyped,mhegazy/DefinitelyTyped,dpsthree/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,sledorze/DefinitelyTyped,florentpoujol/DefinitelyTyped,dreampulse/DefinitelyTyped,pocesar/DefinitelyTyped,damianog/DefinitelyTyped,tdmckinn/DefinitelyTyped,Ptival/DefinitelyTyped,vpineda1996/DefinitelyTyped,stylelab-io/DefinitelyTyped,Fraegle/DefinitelyTyped,Minishlink/DefinitelyTyped,maglar0/DefinitelyTyped,QuatroCode/DefinitelyTyped,jaysoo/DefinitelyTyped,arueckle/DefinitelyTyped,nakakura/DefinitelyTyped,egeland/DefinitelyTyped,greglo/DefinitelyTyped,kmeurer/DefinitelyTyped,grahammendick/DefinitelyTyped,martinduparc/DefinitelyTyped,nycdotnet/DefinitelyTyped,innerverse/DefinitelyTyped,amir-arad/DefinitelyTyped,hor-crux/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,mattanja/DefinitelyTyped,chocolatechipui/DefinitelyTyped,AgentME/DefinitelyTyped,lightswitch05/DefinitelyTyped,hafenr/DefinitelyTyped,glenndierckx/DefinitelyTyped,xica/DefinitelyTyped,leoromanovsky/DefinitelyTyped,takenet/DefinitelyTyped,arcticwaters/DefinitelyTyped,tinganho/DefinitelyTyped,gandjustas/DefinitelyTyped,chrootsu/DefinitelyTyped,lucyhe/DefinitelyTyped,vsavkin/DefinitelyTyped,richardTowers/DefinitelyTyped,hx0day/DefinitelyTyped,deeleman/DefinitelyTyped,Carreau/DefinitelyTyped,bardt/DefinitelyTyped,shlomiassaf/DefinitelyTyped,trystanclarke/DefinitelyTyped,zensh/DefinitelyTyped,jimthedev/DefinitelyTyped,Penryn/DefinitelyTyped,gregoryagu/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,pocke/DefinitelyTyped,applesaucers/lodash-invokeMap,bobslaede/DefinitelyTyped,musicist288/DefinitelyTyped,Litee/DefinitelyTyped,subash-a/DefinitelyTyped,kalloc/DefinitelyTyped,PopSugar/DefinitelyTyped,chadoliver/DefinitelyTyped,johan-gorter/DefinitelyTyped,damianog/DefinitelyTyped,tjoskar/DefinitelyTyped,lukehoban/DefinitelyTyped,donnut/DefinitelyTyped,CSharpFan/DefinitelyTyped,vincentw56/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,laco0416/DefinitelyTyped,magny/DefinitelyTyped,vote539/DefinitelyTyped,behzad88/DefinitelyTyped,nseckinoral/DefinitelyTyped,zuohaocheng/DefinitelyTyped,abbasmhd/DefinitelyTyped,eekboom/DefinitelyTyped,OfficeDev/DefinitelyTyped,progre/DefinitelyTyped,lekaha/DefinitelyTyped,xStrom/DefinitelyTyped,magny/DefinitelyTyped,Litee/DefinitelyTyped,DustinWehr/DefinitelyTyped,RedSeal-co/DefinitelyTyped,tarruda/DefinitelyTyped,zuzusik/DefinitelyTyped,emanuelhp/DefinitelyTyped,Garciat/DefinitelyTyped,ayanoin/DefinitelyTyped,Nemo157/DefinitelyTyped,dariajung/DefinitelyTyped,wkrueger/DefinitelyTyped,martinduparc/DefinitelyTyped,aroder/DefinitelyTyped,bilou84/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mattblang/DefinitelyTyped,alvarorahul/DefinitelyTyped,Zorgatone/DefinitelyTyped,drillbits/DefinitelyTyped,jesseschalken/DefinitelyTyped,michalczukm/DefinitelyTyped,ryan10132/DefinitelyTyped,jasonswearingen/DefinitelyTyped,cvrajeesh/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,maxlang/DefinitelyTyped,psnider/DefinitelyTyped,dsebastien/DefinitelyTyped,blink1073/DefinitelyTyped,trystanclarke/DefinitelyTyped,jeffbcross/DefinitelyTyped,greglockwood/DefinitelyTyped,dmoonfire/DefinitelyTyped,mattanja/DefinitelyTyped,nelsonmorais/DefinitelyTyped,hellopao/DefinitelyTyped,zalamtech/DefinitelyTyped,arma-gast/DefinitelyTyped,M-Zuber/DefinitelyTyped,corps/DefinitelyTyped,bluong/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,bennett000/DefinitelyTyped,ajtowf/DefinitelyTyped,forumone/DefinitelyTyped,duncanmak/DefinitelyTyped,paulmorphy/DefinitelyTyped,duongphuhiep/DefinitelyTyped,vasek17/DefinitelyTyped,scriby/DefinitelyTyped,pocesar/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,YousefED/DefinitelyTyped,benishouga/DefinitelyTyped,billccn/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,sclausen/DefinitelyTyped,nmalaguti/DefinitelyTyped,brainded/DefinitelyTyped,optical/DefinitelyTyped,applesaucers/lodash-invokeMap,darkl/DefinitelyTyped,bdoss/DefinitelyTyped,nakakura/DefinitelyTyped,vagarenko/DefinitelyTyped,AgentME/DefinitelyTyped,reppners/DefinitelyTyped,spearhead-ea/DefinitelyTyped,mshmelev/DefinitelyTyped,shlomiassaf/DefinitelyTyped,rschmukler/DefinitelyTyped,tigerxy/DefinitelyTyped,gdi2290/DefinitelyTyped,gedaiu/DefinitelyTyped,rcchen/DefinitelyTyped,Lorisu/DefinitelyTyped,Seikho/DefinitelyTyped,emanuelhp/DefinitelyTyped,manekovskiy/DefinitelyTyped,goaty92/DefinitelyTyped,Kuniwak/DefinitelyTyped,georgemarshall/DefinitelyTyped,zhiyiting/DefinitelyTyped,theyelllowdart/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,schmuli/DefinitelyTyped,tgfjt/DefinitelyTyped,whoeverest/DefinitelyTyped,amanmahajan7/DefinitelyTyped,digitalpixies/DefinitelyTyped,egeland/DefinitelyTyped,florentpoujol/DefinitelyTyped,unknownloner/DefinitelyTyped,shovon/DefinitelyTyped,fearthecowboy/DefinitelyTyped,pafflique/DefinitelyTyped,adamcarr/DefinitelyTyped,tan9/DefinitelyTyped,philippsimon/DefinitelyTyped,evandrewry/DefinitelyTyped,laball/DefinitelyTyped,EnableSoftware/DefinitelyTyped,wcomartin/DefinitelyTyped,QuatroCode/DefinitelyTyped,rschmukler/DefinitelyTyped,kabogo/DefinitelyTyped,benishouga/DefinitelyTyped,gcastre/DefinitelyTyped,vagarenko/DefinitelyTyped,paulmorphy/DefinitelyTyped,aldo-roman/DefinitelyTyped,esperco/DefinitelyTyped,Chris380/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,nfriend/DefinitelyTyped,tboyce/DefinitelyTyped,nabeix/DefinitelyTyped,schmuli/DefinitelyTyped,DeluxZ/DefinitelyTyped,abmohan/DefinitelyTyped,schmuli/DefinitelyTyped,WritingPanda/DefinitelyTyped,jraymakers/DefinitelyTyped,syuilo/DefinitelyTyped,chrootsu/DefinitelyTyped,mrk21/DefinitelyTyped,smrq/DefinitelyTyped,IAPark/DefinitelyTyped,robl499/DefinitelyTyped,shiwano/DefinitelyTyped,davidpricedev/DefinitelyTyped,hellopao/DefinitelyTyped,Shiak1/DefinitelyTyped,dragouf/DefinitelyTyped,Pro/DefinitelyTyped,ErykB2000/DefinitelyTyped,Zorgatone/DefinitelyTyped,arma-gast/DefinitelyTyped,moonpyk/DefinitelyTyped,stephenjelfs/DefinitelyTyped,icereed/DefinitelyTyped,nainslie/DefinitelyTyped,pwelter34/DefinitelyTyped,Bobjoy/DefinitelyTyped,paxibay/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,uestcNaldo/DefinitelyTyped,AyaMorisawa/DefinitelyTyped | ---
+++
@@ -0,0 +1,64 @@
+/**
+ * Test suite created by Maxime LUCE <https://github.com/SomaticIT>
+ *
+ * Created by using code samples from https://github.com/auth0/node-jsonwebtoken.
+ */
+
+/// <reference path="../node/node.d.ts" />
+/// <reference path="jsonwebtoken.d.ts" />
+
+import jwt = require("jsonwebtoken");
+import fs = require("fs");
+
+var token: string;
+var cert: Buffer;
+
+/**
+ * jwt.sign
+ * https://github.com/auth0/node-jsonwebtoken#usage
+ */
+// sign with default (HMAC SHA256)
+token = jwt.sign({ foo: 'bar' }, 'shhhhh');
+
+// sign with RSA SHA256
+cert = fs.readFileSync('private.key'); // get private key
+token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});
+
+/**
+ * jwt.verify
+ * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
+ */
+// verify a token symmetric
+jwt.verify(token, 'shhhhh', function(err, decoded) {
+ console.log(decoded.foo) // bar
+});
+
+// invalid token
+jwt.verify(token, 'wrong-secret', function(err, decoded) {
+ // err
+ // decoded undefined
+});
+
+// verify a token asymmetric
+cert = fs.readFileSync('public.pem'); // get public key
+jwt.verify(token, cert, function(err, decoded) {
+ console.log(decoded.foo) // bar
+});
+
+// verify audience
+cert = fs.readFileSync('public.pem'); // get public key
+jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
+ // if audience mismatch, err == invalid audience
+});
+
+// verify issuer
+cert = fs.readFileSync('public.pem'); // get public key
+jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
+ // if issuer mismatch, err == invalid issuer
+});
+
+/**
+ * jwt.decode
+ * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken
+ */
+var decoded = jwt.decode(token); |
|
6efd97e8e6a752004ae8964af8e3b377064e4909 | script/validate-changelog.ts | script/validate-changelog.ts | #!/usr/bin/env ts-node
import * as Path from 'path'
import * as Fs from 'fs'
import * as Ajv from 'ajv'
function handleError(error: string) {
console.error(error)
process.exit(-1)
}
function formatErrors(errors: Ajv.ErrorObject[]): string {
return errors
.map(error => {
const { dataPath, message } = error
const additionalProperties = error.params as any
const additionalProperty = additionalProperties.additionalProperty as string
let additionalPropertyText = ''
if (additionalProperty != null) {
additionalPropertyText = `, found: '${
additionalProperties.additionalProperty
}'`
}
// dataPath starts with a leading "."," which is a bit confusing
const element = dataPath.substr(1)
return ` - ${element} - ${message}${additionalPropertyText}`
})
.join('\n')
}
const repositoryRoot = Path.dirname(__dirname)
const changelogPath = Path.join(repositoryRoot, 'changelog.json')
// eslint-disable-next-line no-sync
const changelog = Fs.readFileSync(changelogPath, 'utf8')
let changelogObj = null
try {
changelogObj = JSON.parse(changelog)
} catch {
handleError(
'Unable to parse the contents of changelog.json into a JSON object. Please review the file contents.'
)
}
const schema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
properties: {
releases: {
type: 'object',
patternProperties: {
'^([0-9]+.[0-9]+.[0-9]+)(-beta[0-9]+|-test[0-9]+)?$': {
type: 'array',
items: {
type: 'string',
},
uniqueItems: true,
},
},
additionalProperties: false,
},
},
}
const ajv = new Ajv({ allErrors: true, uniqueItems: true })
const validate = ajv.compile(schema)
const valid = validate(changelogObj)
if (!valid && validate.errors != null) {
handleError(`Errors: \n${formatErrors(validate.errors)}`)
}
console.log('The changelog is totally fine')
| Revert "remove old changelog validate script" | Revert "remove old changelog validate script"
This reverts commit 58d41f678959cfed96d30eb3b1b2c533a2eb47f9.
| TypeScript | mit | kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop | ---
+++
@@ -0,0 +1,81 @@
+#!/usr/bin/env ts-node
+
+import * as Path from 'path'
+import * as Fs from 'fs'
+
+import * as Ajv from 'ajv'
+
+function handleError(error: string) {
+ console.error(error)
+ process.exit(-1)
+}
+
+function formatErrors(errors: Ajv.ErrorObject[]): string {
+ return errors
+ .map(error => {
+ const { dataPath, message } = error
+ const additionalProperties = error.params as any
+ const additionalProperty = additionalProperties.additionalProperty as string
+
+ let additionalPropertyText = ''
+
+ if (additionalProperty != null) {
+ additionalPropertyText = `, found: '${
+ additionalProperties.additionalProperty
+ }'`
+ }
+
+ // dataPath starts with a leading "."," which is a bit confusing
+ const element = dataPath.substr(1)
+
+ return ` - ${element} - ${message}${additionalPropertyText}`
+ })
+ .join('\n')
+}
+
+const repositoryRoot = Path.dirname(__dirname)
+const changelogPath = Path.join(repositoryRoot, 'changelog.json')
+
+// eslint-disable-next-line no-sync
+const changelog = Fs.readFileSync(changelogPath, 'utf8')
+
+let changelogObj = null
+
+try {
+ changelogObj = JSON.parse(changelog)
+} catch {
+ handleError(
+ 'Unable to parse the contents of changelog.json into a JSON object. Please review the file contents.'
+ )
+}
+
+const schema = {
+ $schema: 'http://json-schema.org/draft-07/schema#',
+ type: 'object',
+ properties: {
+ releases: {
+ type: 'object',
+ patternProperties: {
+ '^([0-9]+.[0-9]+.[0-9]+)(-beta[0-9]+|-test[0-9]+)?$': {
+ type: 'array',
+ items: {
+ type: 'string',
+ },
+ uniqueItems: true,
+ },
+ },
+ additionalProperties: false,
+ },
+ },
+}
+
+const ajv = new Ajv({ allErrors: true, uniqueItems: true })
+const validate = ajv.compile(schema)
+
+const valid = validate(changelogObj)
+
+if (!valid && validate.errors != null) {
+ handleError(`Errors: \n${formatErrors(validate.errors)}`)
+}
+
+console.log('The changelog is totally fine') |
|
c4dd36443aaf629725ecfdfda2ebd8a03e179391 | src/main/io/settings-io.ts | src/main/io/settings-io.ts | // Copyright 2016 underdolphin(masato sueda)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as fs from 'fs';
import SettingsSchema = Schemas.Settings;
export class Settings {
public defaultReader() {
return JSON.parse(fs.readFileSync(`${process.cwd()}/build/assets/default.settings.json`, `utf-8`));
}
public Reader() {
return JSON.parse(fs.readFileSync(`${process.cwd()}/build/assets/settings.json`, `utf-8`));
}
public Writer(settings: JSON): void {
fs.writeFile(`${process.cwd()}/build/assets/settings.json`, JSON.stringify(settings));
}
}
| Add io for settings file | Add io for settings file
| TypeScript | apache-2.0 | underdolphin/SoundRebuild,underdolphin/SoundRebuild,underdolphin/SoundRebuild | ---
+++
@@ -0,0 +1,30 @@
+// Copyright 2016 underdolphin(masato sueda)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import * as fs from 'fs';
+import SettingsSchema = Schemas.Settings;
+
+export class Settings {
+ public defaultReader() {
+ return JSON.parse(fs.readFileSync(`${process.cwd()}/build/assets/default.settings.json`, `utf-8`));
+ }
+
+ public Reader() {
+ return JSON.parse(fs.readFileSync(`${process.cwd()}/build/assets/settings.json`, `utf-8`));
+ }
+
+ public Writer(settings: JSON): void {
+ fs.writeFile(`${process.cwd()}/build/assets/settings.json`, JSON.stringify(settings));
+ }
+} |
|
6ca778ddea235e69d4d3122dada2672b4e8f8062 | polygerrit-ui/app/elements/shared/gr-account-chip/gr-account-chip_test.ts | polygerrit-ui/app/elements/shared/gr-account-chip/gr-account-chip_test.ts | /**
* @license
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../../../test/common-test-setup-karma';
import {fixture} from '@open-wc/testing-helpers';
import {html} from 'lit';
import './gr-account-chip';
import {GrAccountChip} from './gr-account-chip';
import {
createAccountWithIdNameAndEmail,
createChange,
} from '../../../test/test-data-generators';
suite('gr-account-chip tests', () => {
let element: GrAccountChip;
setup(async () => {
const reviewer = createAccountWithIdNameAndEmail();
const change = createChange();
element = await fixture<GrAccountChip>(html`<gr-account-chip
.account=${reviewer}
.change=${change}
></gr-account-chip>`);
});
test('renders', () => {
expect(element).shadowDom.to.equal(`<div class="container">
<gr-account-link></gr-account-link>
<slot name="vote-chip"></slot>
<gr-button
aria-disabled="false"
aria-label="Remove"
class="remove"
hidden=""
id="remove"
link=""
role="button"
tabindex="0"
>
<iron-icon icon="gr-icons:close"></iron-icon>
</gr-button>
</div>
`);
});
});
| Add shadow dom UT for gr-account-chip | Add shadow dom UT for gr-account-chip
Change-Id: I0628297ff259e344b85e4b8ed7c399bf17b0cfa9
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -0,0 +1,58 @@
+/**
+ * @license
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import '../../../test/common-test-setup-karma';
+import {fixture} from '@open-wc/testing-helpers';
+import {html} from 'lit';
+import './gr-account-chip';
+import {GrAccountChip} from './gr-account-chip';
+import {
+ createAccountWithIdNameAndEmail,
+ createChange,
+} from '../../../test/test-data-generators';
+
+suite('gr-account-chip tests', () => {
+ let element: GrAccountChip;
+ setup(async () => {
+ const reviewer = createAccountWithIdNameAndEmail();
+ const change = createChange();
+ element = await fixture<GrAccountChip>(html`<gr-account-chip
+ .account=${reviewer}
+ .change=${change}
+ ></gr-account-chip>`);
+ });
+
+ test('renders', () => {
+ expect(element).shadowDom.to.equal(`<div class="container">
+ <gr-account-link></gr-account-link>
+ <slot name="vote-chip"></slot>
+ <gr-button
+ aria-disabled="false"
+ aria-label="Remove"
+ class="remove"
+ hidden=""
+ id="remove"
+ link=""
+ role="button"
+ tabindex="0"
+ >
+ <iron-icon icon="gr-icons:close"></iron-icon>
+ </gr-button>
+ </div>
+ `);
+ });
+}); |
|
01d071046a9a8b131f8d5cadbc70295cb6da9e85 | src/utils/number.spec.ts | src/utils/number.spec.ts | import { distance, makeDivisibleBy } from "./number";
describe("distance", () => {
it("does basic straight line distance", () => {
expect(distance(1, 1, 1, 2)).toBe(1);
});
});
describe("makeDivisibleBy", () => {
it("returns same number if already divisible", () => {
expect(makeDivisibleBy(4, 4)).toBe(4);
expect(makeDivisibleBy(16, 4)).toBe(16);
});
it("returns 0 for 0 in the numerator", () => {
expect(makeDivisibleBy(0, 4)).toBe(0);
});
it("increases number when not divisible", () => {
expect(makeDivisibleBy(1, 4)).toBe(4);
expect(makeDivisibleBy(2, 4)).toBe(4);
expect(makeDivisibleBy(3, 4)).toBe(4);
expect(makeDivisibleBy(13, 4)).toBe(16);
expect(makeDivisibleBy(14, 4)).toBe(16);
expect(makeDivisibleBy(15, 4)).toBe(16);
});
});
| Add an example unit test | Add an example unit test
| TypeScript | unlicense | PartyPlanner64/PartyPlanner64,PartyPlanner64/PartyPlanner64,PartyPlanner64/PartyPlanner64 | ---
+++
@@ -0,0 +1,27 @@
+import { distance, makeDivisibleBy } from "./number";
+
+describe("distance", () => {
+ it("does basic straight line distance", () => {
+ expect(distance(1, 1, 1, 2)).toBe(1);
+ });
+});
+
+describe("makeDivisibleBy", () => {
+ it("returns same number if already divisible", () => {
+ expect(makeDivisibleBy(4, 4)).toBe(4);
+ expect(makeDivisibleBy(16, 4)).toBe(16);
+ });
+
+ it("returns 0 for 0 in the numerator", () => {
+ expect(makeDivisibleBy(0, 4)).toBe(0);
+ });
+
+ it("increases number when not divisible", () => {
+ expect(makeDivisibleBy(1, 4)).toBe(4);
+ expect(makeDivisibleBy(2, 4)).toBe(4);
+ expect(makeDivisibleBy(3, 4)).toBe(4);
+ expect(makeDivisibleBy(13, 4)).toBe(16);
+ expect(makeDivisibleBy(14, 4)).toBe(16);
+ expect(makeDivisibleBy(15, 4)).toBe(16);
+ });
+}); |
|
94220b146b1072ad7c68afa4f8505d44a1fd5c0a | app/src/lib/dispatcher/emoji-store.ts | app/src/lib/dispatcher/emoji-store.ts | import * as Fs from 'fs'
import * as Path from 'path'
import * as Url from 'url'
export default class EmojiStore {
/** Map from shorcut (e.g., +1) to on disk URL. */
public readonly emoji = new Map<string, string>()
public read(): Promise<void> {
return new Promise((resolve, reject) => {
Fs.readFile(Path.join(__dirname, 'emoji.json'), 'utf8', (err, data) => {
const json = JSON.parse(data)
for (const key of Object.keys(json)) {
const serverURL = json[key]
const localPath = serverURLToLocalPath(serverURL)
this.emoji.set(key, localPath)
}
resolve()
})
})
}
}
function serverURLToLocalPath(url: string): string {
// url = https://assets-cdn.github.com/images/icons/emoji/unicode/1f44e.png?v6
const parsedURL = Url.parse(url)
const path = parsedURL.pathname!
// path = /images/icons/emoji/unicode/1f44e.png
const relativePath = path.replace('/images/icons', '')
// relativePath = /emoji/unicode/1f44e.png
return `file://${Path.join(__dirname, relativePath)}`
}
| Read in the emoji lookup table | Read in the emoji lookup table
| TypeScript | mit | artivilla/desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,BugTesterTest/desktops,desktop/desktop,shiftkey/desktop,kactus-io/kactus,BugTesterTest/desktops,desktop/desktop,j-f1/forked-desktop,desktop/desktop,hjobrien/desktop,hjobrien/desktop,gengjiawen/desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,artivilla/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,gengjiawen/desktop,say25/desktop,say25/desktop,hjobrien/desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,BugTesterTest/desktops,hjobrien/desktop | ---
+++
@@ -0,0 +1,37 @@
+import * as Fs from 'fs'
+import * as Path from 'path'
+import * as Url from 'url'
+
+export default class EmojiStore {
+ /** Map from shorcut (e.g., +1) to on disk URL. */
+ public readonly emoji = new Map<string, string>()
+
+ public read(): Promise<void> {
+ return new Promise((resolve, reject) => {
+ Fs.readFile(Path.join(__dirname, 'emoji.json'), 'utf8', (err, data) => {
+ const json = JSON.parse(data)
+ for (const key of Object.keys(json)) {
+ const serverURL = json[key]
+ const localPath = serverURLToLocalPath(serverURL)
+ this.emoji.set(key, localPath)
+ }
+
+ resolve()
+ })
+ })
+ }
+}
+
+function serverURLToLocalPath(url: string): string {
+ // url = https://assets-cdn.github.com/images/icons/emoji/unicode/1f44e.png?v6
+
+ const parsedURL = Url.parse(url)
+
+ const path = parsedURL.pathname!
+ // path = /images/icons/emoji/unicode/1f44e.png
+
+ const relativePath = path.replace('/images/icons', '')
+ // relativePath = /emoji/unicode/1f44e.png
+
+ return `file://${Path.join(__dirname, relativePath)}`
+} |
|
bd133aed103af6c1e7c2ece9ee4dc8d14cfc2d0c | src/libs/constants/error_authors.ts | src/libs/constants/error_authors.ts | export interface ErrorAuthors {
"Additional Word Hint": string
"Capitalization Hint": string
"Flexible Additional Word Hint": string
"Flexible Missing Word Hint": string
"Flexible Modified Word Hint": string
"Focus Point Hint": string
"Incorrect Sequence Hint": string
"Missing Details Hint": string
"Missing Word Hint": string
"Modified Word Hint": string
"Not Concise Hint": string
"Parts of Speech": string
"Punctuation End Hint": string
"Punctuation Hint": string
"Punctuation and Case Hint": string
"Required Words Hint": string
"Spacing After Comma Hint": string
"Starting Capitalization Hint": string
"Spelling Hint": string
"Too Long Hint": string
"Too Short Hint": string
"Whitespace Hint": string
}
const error_authors: ErrorAuthors = {
"Additional Word Hint": "Additional Word Hint",
"Capitalization Hint": "Capitalization Hint",
"Flexible Additional Word Hint": "Flexible Additional Word Hint",
"Flexible Missing Word Hint": "Flexible Missing Word Hint",
"Flexible Modified Word Hint": "Flexible Modified Word Hint",
"Focus Point Hint": "Focus Point Hint",
"Incorrect Sequence Hint": "Incorrect Sequence Hint",
"Missing Details Hint": "Missing Details Hint",
"Missing Word Hint": "Missing Word Hint",
"Modified Word Hint": "Modified Word Hint",
"Not Concise Hint": "Not Concise Hint",
"Parts of Speech": "Parts of Speech",
"Punctuation End Hint": "Punctuation End Hint",
"Punctuation Hint": "Punctuation Hint",
"Punctuation and Case Hint": "Punctuation and Case Hint",
"Required Words Hint": "Required Words Hint",
"Spacing After Comma Hint": "Spacing After Comma Hint",
"Spelling Hint": "Spelling Hint",
"Starting Capitalization Hint": "Starting Capitalization Hint",
"Too Long Hint": "Too Long Hint",
"Too Short Hint": "Too Short Hint",
"Whitespace Hint": "Whitespace Hint",
}
export default error_authors | Make a constants file for authors. | Make a constants file for authors.
| TypeScript | agpl-3.0 | empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core | ---
+++
@@ -0,0 +1,51 @@
+export interface ErrorAuthors {
+ "Additional Word Hint": string
+ "Capitalization Hint": string
+ "Flexible Additional Word Hint": string
+ "Flexible Missing Word Hint": string
+ "Flexible Modified Word Hint": string
+ "Focus Point Hint": string
+ "Incorrect Sequence Hint": string
+ "Missing Details Hint": string
+ "Missing Word Hint": string
+ "Modified Word Hint": string
+ "Not Concise Hint": string
+ "Parts of Speech": string
+ "Punctuation End Hint": string
+ "Punctuation Hint": string
+ "Punctuation and Case Hint": string
+ "Required Words Hint": string
+ "Spacing After Comma Hint": string
+ "Starting Capitalization Hint": string
+ "Spelling Hint": string
+ "Too Long Hint": string
+ "Too Short Hint": string
+ "Whitespace Hint": string
+}
+
+const error_authors: ErrorAuthors = {
+ "Additional Word Hint": "Additional Word Hint",
+ "Capitalization Hint": "Capitalization Hint",
+ "Flexible Additional Word Hint": "Flexible Additional Word Hint",
+ "Flexible Missing Word Hint": "Flexible Missing Word Hint",
+ "Flexible Modified Word Hint": "Flexible Modified Word Hint",
+ "Focus Point Hint": "Focus Point Hint",
+ "Incorrect Sequence Hint": "Incorrect Sequence Hint",
+ "Missing Details Hint": "Missing Details Hint",
+ "Missing Word Hint": "Missing Word Hint",
+ "Modified Word Hint": "Modified Word Hint",
+ "Not Concise Hint": "Not Concise Hint",
+ "Parts of Speech": "Parts of Speech",
+ "Punctuation End Hint": "Punctuation End Hint",
+ "Punctuation Hint": "Punctuation Hint",
+ "Punctuation and Case Hint": "Punctuation and Case Hint",
+ "Required Words Hint": "Required Words Hint",
+ "Spacing After Comma Hint": "Spacing After Comma Hint",
+ "Spelling Hint": "Spelling Hint",
+ "Starting Capitalization Hint": "Starting Capitalization Hint",
+ "Too Long Hint": "Too Long Hint",
+ "Too Short Hint": "Too Short Hint",
+ "Whitespace Hint": "Whitespace Hint",
+}
+
+export default error_authors |
|
82a1d72f9bc26b4fa0c0ef224931cf3ab5922e38 | modules/core/test/v2/unit/coins/hbar.ts | modules/core/test/v2/unit/coins/hbar.ts | import * as Promise from 'bluebird';
import { Hbar } from '../../../../src/v2/coins/';
const co = Promise.coroutine;
import { TestBitGo } from '../../../lib/test_bitgo';
describe('Hedera Hashgraph:', function() {
let bitgo;
let basecoin;
before(function() {
bitgo = new TestBitGo({ env: 'mock' });
bitgo.initializeTestVars();
basecoin = bitgo.coin('thbar');
});
it('should instantiate the coin', function() {
const basecoin = bitgo.coin('hbar');
basecoin.should.be.an.instanceof(Hbar);
});
it('should check valid addresses', co(function *() {
const badAddresses = ['', '0.0', 'YZ09fd-', '0.0.0.a', 'sadasdfggg', '0.2.a.b'];
const goodAddresses = ['0', '0.0.0', '0.0.41098'];
badAddresses.map(addr => { basecoin.isValidAddress(addr).should.equal(false); });
goodAddresses.map(addr => { basecoin.isValidAddress(addr).should.equal(true); });
}));
describe('Keypairs:', () => {
it('should generate a keypair from random seed', function() {
const keyPair = basecoin.generateKeyPair();
keyPair.should.have.property('pub');
keyPair.should.have.property('prv');
// TODO: add back when validation of the pub is live
// basecoin.isValidPub(keyPair.pub).should.equal(true);
});
it('should generate a keypair from a seed', function() {
const seedText = '80350b4208d381fbfe2276a326603049fe500731c46d3c9936b5ce036b51377f';
const seed = Buffer.from(seedText, 'hex');
const keyPair = basecoin.generateKeyPair(seed);
keyPair.pub.should.equal('9cc402b5c75214269c2826e3c6119377cab6c367601338661c87a4e07c6e0333');
keyPair.prv.should.equal('80350b4208d381fbfe2276a326603049fe500731c46d3c9936b5ce036b51377f');
});
});
});
| Add simple tests to Hbar skeleton | Add simple tests to Hbar skeleton
Ticket: BG-23027
| TypeScript | apache-2.0 | BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS | ---
+++
@@ -0,0 +1,49 @@
+import * as Promise from 'bluebird';
+import { Hbar } from '../../../../src/v2/coins/';
+
+const co = Promise.coroutine;
+import { TestBitGo } from '../../../lib/test_bitgo';
+
+describe('Hedera Hashgraph:', function() {
+ let bitgo;
+ let basecoin;
+
+ before(function() {
+ bitgo = new TestBitGo({ env: 'mock' });
+ bitgo.initializeTestVars();
+ basecoin = bitgo.coin('thbar');
+ });
+
+ it('should instantiate the coin', function() {
+ const basecoin = bitgo.coin('hbar');
+ basecoin.should.be.an.instanceof(Hbar);
+ });
+
+ it('should check valid addresses', co(function *() {
+ const badAddresses = ['', '0.0', 'YZ09fd-', '0.0.0.a', 'sadasdfggg', '0.2.a.b'];
+ const goodAddresses = ['0', '0.0.0', '0.0.41098'];
+
+ badAddresses.map(addr => { basecoin.isValidAddress(addr).should.equal(false); });
+ goodAddresses.map(addr => { basecoin.isValidAddress(addr).should.equal(true); });
+ }));
+
+ describe('Keypairs:', () => {
+ it('should generate a keypair from random seed', function() {
+ const keyPair = basecoin.generateKeyPair();
+ keyPair.should.have.property('pub');
+ keyPair.should.have.property('prv');
+
+ // TODO: add back when validation of the pub is live
+ // basecoin.isValidPub(keyPair.pub).should.equal(true);
+ });
+
+ it('should generate a keypair from a seed', function() {
+ const seedText = '80350b4208d381fbfe2276a326603049fe500731c46d3c9936b5ce036b51377f';
+ const seed = Buffer.from(seedText, 'hex');
+ const keyPair = basecoin.generateKeyPair(seed);
+
+ keyPair.pub.should.equal('9cc402b5c75214269c2826e3c6119377cab6c367601338661c87a4e07c6e0333');
+ keyPair.prv.should.equal('80350b4208d381fbfe2276a326603049fe500731c46d3c9936b5ce036b51377f');
+ });
+ });
+}); |
|
4f6b5b1cda03d11ec130440da1edff6385fe4c18 | src/Test/Ast/InlineDocument/OutlineConventions.ts | src/Test/Ast/InlineDocument/OutlineConventions.ts | import { expect } from 'chai'
import Up from'../../../index'
import { InlineUpDocument } from'../../../SyntaxNodes/InlineUpDocument'
import { PlainTextNode } from'../../../SyntaxNodes/PlainTextNode'
context('Inline documents completely ignore outline conventions. This includes:', () => {
specify('Outline separation streaks', () => {
expect(Up.toInlineDocument('#~#~#~#~#')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('#~#~#~#~#')
]))
})
specify('Ordered lists', () => {
expect(Up.toInlineDocument('1) I agree.')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('1) I agree.')
]))
})
specify('Unordered lists', () => {
expect(Up.toInlineDocument('* Prices and participation may vary')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('* Prices and participation may vary')
]))
})
specify('Blockquotes', () => {
expect(Up.toInlineDocument('> o_o <')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('> o_o <')
]))
})
specify('Code blocks', () => {
expect(Up.toInlineDocument('```')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('```')
]))
})
})
| Add 5 passing inline document tests | Add 5 passing inline document tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,42 @@
+import { expect } from 'chai'
+import Up from'../../../index'
+import { InlineUpDocument } from'../../../SyntaxNodes/InlineUpDocument'
+import { PlainTextNode } from'../../../SyntaxNodes/PlainTextNode'
+
+
+context('Inline documents completely ignore outline conventions. This includes:', () => {
+ specify('Outline separation streaks', () => {
+ expect(Up.toInlineDocument('#~#~#~#~#')).to.be.eql(
+ new InlineUpDocument([
+ new PlainTextNode('#~#~#~#~#')
+ ]))
+ })
+
+ specify('Ordered lists', () => {
+ expect(Up.toInlineDocument('1) I agree.')).to.be.eql(
+ new InlineUpDocument([
+ new PlainTextNode('1) I agree.')
+ ]))
+ })
+
+ specify('Unordered lists', () => {
+ expect(Up.toInlineDocument('* Prices and participation may vary')).to.be.eql(
+ new InlineUpDocument([
+ new PlainTextNode('* Prices and participation may vary')
+ ]))
+ })
+
+ specify('Blockquotes', () => {
+ expect(Up.toInlineDocument('> o_o <')).to.be.eql(
+ new InlineUpDocument([
+ new PlainTextNode('> o_o <')
+ ]))
+ })
+
+ specify('Code blocks', () => {
+ expect(Up.toInlineDocument('```')).to.be.eql(
+ new InlineUpDocument([
+ new PlainTextNode('```')
+ ]))
+ })
+}) |
|
010580f9d286ad941006346ee607022046653c6e | src/Test/Html/Config/TableOfContents.ts | src/Test/Html/Config/TableOfContents.ts | import { expect } from 'chai'
import Up from '../../../index'
import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
import { HeadingNode } from '../../../SyntaxNodes/HeadingNode'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
describe('The main heading within the table of contents', () => {
it('uses the config term for "tableOfContents"', () => {
const up = new Up({
i18n: {
terms: { tableOfContents: 'In This Article' }
}
})
const heading =
new HeadingNode([new PlainTextNode('I enjoy apples')], 1)
const documentNode =
new DocumentNode([heading], new DocumentNode.TableOfContents([heading]))
expect(up.toHtml(documentNode)).to.be.eql(
'<nav class="up-table-of-contents">'
+ '<h1>In This Article</h1>'
+ '<ul>'
+ '<li><h2><a href="#up-part-1">I enjoy apples</a></h2></li>'
+ '</ul>'
+ '</nav>'
+ '<h1 id="up-part-1">I enjoy apples</h1>')
})
}) | Add passing table of contents HTML test | Add passing table of contents HTML test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,31 @@
+import { expect } from 'chai'
+import Up from '../../../index'
+import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
+import { HeadingNode } from '../../../SyntaxNodes/HeadingNode'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+
+
+describe('The main heading within the table of contents', () => {
+ it('uses the config term for "tableOfContents"', () => {
+ const up = new Up({
+ i18n: {
+ terms: { tableOfContents: 'In This Article' }
+ }
+ })
+
+ const heading =
+ new HeadingNode([new PlainTextNode('I enjoy apples')], 1)
+
+ const documentNode =
+ new DocumentNode([heading], new DocumentNode.TableOfContents([heading]))
+
+ expect(up.toHtml(documentNode)).to.be.eql(
+ '<nav class="up-table-of-contents">'
+ + '<h1>In This Article</h1>'
+ + '<ul>'
+ + '<li><h2><a href="#up-part-1">I enjoy apples</a></h2></li>'
+ + '</ul>'
+ + '</nav>'
+ + '<h1 id="up-part-1">I enjoy apples</h1>')
+ })
+}) |
|
3ecde6a2ecd7f5ee12b728a3a0fbcc912bcb0f8b | src/scripts/generate-lexicon.ts | src/scripts/generate-lexicon.ts | const nlp = require('compromise'); // tslint:disable-line
const verbConjugations: Lexicon[] = require('../../lexicon/verb-conjugations.json'); // tslint:disable-line
import { writeFile } from 'mz/fs';
import { join } from 'path';
const tenses = [
'infinitive',
'past',
'gerund',
'present',
];
interface TenseToSomething {
infinitive: string | any;
past: string | any;
gerund: string | any;
present: string | any;
[key: string]: string | any;
}
const tenseToLexiconKey: TenseToSomething = {
infinitive: 'infinitive',
past: 'past',
gerund: 'present participle',
present: '3rd singular present',
};
interface Lexicon {
'infinitive': string;
'past': string;
'present participle': string;
'3rd singular present': string;
[key: string]: string;
}
const tenseToConjugationKey: TenseToSomething = {
infinitive: 'Infinitive',
past: 'PastTense',
gerund: 'Gerund',
present: 'PresentTense',
};
const tenseToCorrections: TenseToSomething = {
infinitive: {},
past: {},
gerund: {},
present: {},
};
for (const verb of verbConjugations) {
for (const toTense of tenses) {
for (const fromTense of tenses) {
const calculatedConjugations = nlp(verb[tenseToLexiconKey[fromTense]]).verbs().conjugate();
if (!calculatedConjugations || !calculatedConjugations[0]) {
tenseToCorrections[toTense][verb[tenseToLexiconKey[fromTense]]] = verb[tenseToLexiconKey[toTense]];
continue;
}
const calculatedResult = calculatedConjugations[0][tenseToConjugationKey[toTense]];
const expectedResult = verb[tenseToLexiconKey[toTense]];
// (calculatedResult !== expectedResult) && console.log('Comparing ', calculatedResult, expectedResult, calculatedResult === expectedResult);
if (calculatedResult !== expectedResult) {
tenseToCorrections[toTense][verb[tenseToLexiconKey[fromTense]]] = verb[tenseToLexiconKey[toTense]];
}
}
}
}
Promise.all(tenses.map(tense => writeFile(join(__dirname, `../../lexicon/verbs-to-${tense}.json`), JSON.stringify(tenseToCorrections[tense], null, ' '))));
| Create script for generating lexicons | Create script for generating lexicons
| TypeScript | mit | martinhartt/messagelint,martinhartt/messagelint,martinhartt/messagelint | ---
+++
@@ -0,0 +1,73 @@
+const nlp = require('compromise'); // tslint:disable-line
+const verbConjugations: Lexicon[] = require('../../lexicon/verb-conjugations.json'); // tslint:disable-line
+import { writeFile } from 'mz/fs';
+import { join } from 'path';
+
+const tenses = [
+ 'infinitive',
+ 'past',
+ 'gerund',
+ 'present',
+];
+
+interface TenseToSomething {
+ infinitive: string | any;
+ past: string | any;
+ gerund: string | any;
+ present: string | any;
+ [key: string]: string | any;
+}
+
+const tenseToLexiconKey: TenseToSomething = {
+ infinitive: 'infinitive',
+ past: 'past',
+ gerund: 'present participle',
+ present: '3rd singular present',
+};
+
+interface Lexicon {
+ 'infinitive': string;
+ 'past': string;
+ 'present participle': string;
+ '3rd singular present': string;
+ [key: string]: string;
+}
+
+const tenseToConjugationKey: TenseToSomething = {
+ infinitive: 'Infinitive',
+ past: 'PastTense',
+ gerund: 'Gerund',
+ present: 'PresentTense',
+};
+
+const tenseToCorrections: TenseToSomething = {
+ infinitive: {},
+ past: {},
+ gerund: {},
+ present: {},
+};
+
+for (const verb of verbConjugations) {
+ for (const toTense of tenses) {
+ for (const fromTense of tenses) {
+ const calculatedConjugations = nlp(verb[tenseToLexiconKey[fromTense]]).verbs().conjugate();
+
+ if (!calculatedConjugations || !calculatedConjugations[0]) {
+ tenseToCorrections[toTense][verb[tenseToLexiconKey[fromTense]]] = verb[tenseToLexiconKey[toTense]];
+ continue;
+ }
+
+
+ const calculatedResult = calculatedConjugations[0][tenseToConjugationKey[toTense]];
+ const expectedResult = verb[tenseToLexiconKey[toTense]];
+
+ // (calculatedResult !== expectedResult) && console.log('Comparing ', calculatedResult, expectedResult, calculatedResult === expectedResult);
+
+ if (calculatedResult !== expectedResult) {
+ tenseToCorrections[toTense][verb[tenseToLexiconKey[fromTense]]] = verb[tenseToLexiconKey[toTense]];
+ }
+ }
+ }
+}
+
+Promise.all(tenses.map(tense => writeFile(join(__dirname, `../../lexicon/verbs-to-${tense}.json`), JSON.stringify(tenseToCorrections[tense], null, ' ')))); |
|
c385cb0adce1db3366cebe747b6ab22940ba76aa | src/main/client/app/framework/components/Security.tsx | src/main/client/app/framework/components/Security.tsx | import preact from "preact"
import {SessionState, sessionStore, SessionUser, UserRole} from "../session/sessionStore";
import StoreListenerComponent from "../utils/dom";
import {Function1} from "../lib";
interface HocOnLoggedInProps {
user?: SessionUser
}
type OnLoggedInProps<P> = HocOnLoggedInProps & P
export function OnLoggedIn<P>(InnerComponent: new() => preact.Component<P, any> | Function1<P, JSX.Element> | any): preact.Component<P, any> {
return class extends StoreListenerComponent<P, SessionState> {
constructor() {
super(sessionStore)
}
render(props: OnLoggedInProps<P>, state: SessionState) {
if (state.user) {
return (
<InnerComponent
{...props}
user={state.user}
/>
)
} else {
return null
}
}
} as any
}
interface HocOnGrantedProps {
user?: SessionUser
}
type OnGrantedProps<P> = HocOnGrantedProps & P
export function OnGranted<P>(InnerComponent: Function1<P, JSX.Element> | any, role: UserRole): Function1<OnGrantedProps<P>, JSX.Element> {
return class extends StoreListenerComponent<P, SessionState> {
constructor() {
super(sessionStore)
}
render(props: OnGrantedProps<P>, state: SessionState) {
if (state.user && state.user.role === role) {
return (
<InnerComponent
{...props}
user={state.user}
/>
)
} else {
return null
}
}
} as any
} | Create component to better handle security. | Create component to better handle security.
Because sometime, we need to display some components
only when the user have some rights, create two component to handle
authentication and authorization: `OnLoggedIn` and `OnGranted`.
This commit do the following:
* Create the two components
| TypeScript | mit | kneelnrise/vep,kneelnrise/vep,kneelnrise/vep | ---
+++
@@ -0,0 +1,58 @@
+import preact from "preact"
+import {SessionState, sessionStore, SessionUser, UserRole} from "../session/sessionStore";
+import StoreListenerComponent from "../utils/dom";
+import {Function1} from "../lib";
+
+interface HocOnLoggedInProps {
+ user?: SessionUser
+}
+
+type OnLoggedInProps<P> = HocOnLoggedInProps & P
+
+export function OnLoggedIn<P>(InnerComponent: new() => preact.Component<P, any> | Function1<P, JSX.Element> | any): preact.Component<P, any> {
+ return class extends StoreListenerComponent<P, SessionState> {
+ constructor() {
+ super(sessionStore)
+ }
+
+ render(props: OnLoggedInProps<P>, state: SessionState) {
+ if (state.user) {
+ return (
+ <InnerComponent
+ {...props}
+ user={state.user}
+ />
+ )
+ } else {
+ return null
+ }
+ }
+ } as any
+}
+
+interface HocOnGrantedProps {
+ user?: SessionUser
+}
+
+type OnGrantedProps<P> = HocOnGrantedProps & P
+
+export function OnGranted<P>(InnerComponent: Function1<P, JSX.Element> | any, role: UserRole): Function1<OnGrantedProps<P>, JSX.Element> {
+ return class extends StoreListenerComponent<P, SessionState> {
+ constructor() {
+ super(sessionStore)
+ }
+
+ render(props: OnGrantedProps<P>, state: SessionState) {
+ if (state.user && state.user.role === role) {
+ return (
+ <InnerComponent
+ {...props}
+ user={state.user}
+ />
+ )
+ } else {
+ return null
+ }
+ }
+ } as any
+} |
|
d93d3ebccf065c7c657ba9fdd13c7a33ed2205b4 | src/random_strategy.ts | src/random_strategy.ts |
import {IStrategy} from "./strategy_runner";
export class RandomStrategy implements IStrategy {
public playCard(gameState: GameState): [number, Card] {
let flag = _.random(1, 9);
return [flag, _.sample(gameState.playerCards)];
};
}
| Add a strategy that randomly selects cards | feat(RandomStrategy): Add a strategy that randomly selects cards
| TypeScript | mit | grantpatten/battleline-ai,grantpatten/battleline-ai | ---
+++
@@ -0,0 +1,9 @@
+
+import {IStrategy} from "./strategy_runner";
+
+export class RandomStrategy implements IStrategy {
+ public playCard(gameState: GameState): [number, Card] {
+ let flag = _.random(1, 9);
+ return [flag, _.sample(gameState.playerCards)];
+ };
+} |
|
2b8b253d2ad51c229df4cfac865b02bc2fa8f591 | packages/gitgraph-core/src/__tests__/gitgraph.getRenderedData.commits.test.ts | packages/gitgraph-core/src/__tests__/gitgraph.getRenderedData.commits.test.ts | import { GitgraphCore } from "../index";
describe("Gitgraph.getRenderedData.commits", () => {
it("should use a default message on merge", () => {
const gitgraph = new GitgraphCore();
const master = gitgraph.branch("master");
master.commit("one");
const develop = gitgraph.branch("develop");
develop.commit("two");
master.merge(develop);
const { commits } = gitgraph.getRenderedData();
expect(commits).toMatchObject([
{ subject: "one" },
{ subject: "two" },
{ subject: "Merge branch develop" },
]);
});
});
| Test getRenderedData commit messages specifically | Test getRenderedData commit messages specifically
| TypeScript | mit | nicoespeon/gitgraph.js,nicoespeon/gitgraph.js,nicoespeon/gitgraph.js,nicoespeon/gitgraph.js | ---
+++
@@ -0,0 +1,22 @@
+import { GitgraphCore } from "../index";
+
+describe("Gitgraph.getRenderedData.commits", () => {
+ it("should use a default message on merge", () => {
+ const gitgraph = new GitgraphCore();
+
+ const master = gitgraph.branch("master");
+ master.commit("one");
+
+ const develop = gitgraph.branch("develop");
+ develop.commit("two");
+ master.merge(develop);
+
+ const { commits } = gitgraph.getRenderedData();
+
+ expect(commits).toMatchObject([
+ { subject: "one" },
+ { subject: "two" },
+ { subject: "Merge branch develop" },
+ ]);
+ });
+}); |
|
3de3eb4a823f751c0ca6b1a4798a537510f22e01 | src/math/math.ts | src/math/math.ts | import * as _ from 'lodash';
/**
* Computes the minimum and maxiumum value of `collection`.
* This method complements the lodash
* [http://devdocs.io/lodash~4/index#minBy](minBy) and
* [http://devdocs.io/lodash~4/index#maxBy](maxBy) functions
* by allowing an Object `collection`, supplying the
* `iteratee` two arguments (_value_, _key_), and iterating
* only once over the collection. Non-numeric and non-finite
* iteration results are ignored. If there is no numeric,
* finite iteration result, then this method returns
* `undefined`.
*
* @method bounds
* @param collection {Object|any[]} the collection to
* iterate over
* @param iteratee {function=_.identity} the iteratee
* invoked per element
* @return the [min, max] bounds
*/
function bounds(collection: Object|any[], iteratee=_.identity) {
let min;
let max;
let check = (value, key) => {
let target = iteratee(value, key);
if (_.isFinite(target)) {
if (_.isUndefined(min) || target < min) {
min = target;
}
if (_.isUndefined(max) || target > max) {
max = target;
}
}
};
_.forEach(collection, check);
return _.isUndefined(min) ? undefined : [min, max];
}
export { bounds };
| Add the bounds utility function. | Add the bounds utility function.
| TypeScript | bsd-2-clause | ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile,ohsu-qin/qiprofile | ---
+++
@@ -0,0 +1,41 @@
+import * as _ from 'lodash';
+
+/**
+ * Computes the minimum and maxiumum value of `collection`.
+ * This method complements the lodash
+ * [http://devdocs.io/lodash~4/index#minBy](minBy) and
+ * [http://devdocs.io/lodash~4/index#maxBy](maxBy) functions
+ * by allowing an Object `collection`, supplying the
+ * `iteratee` two arguments (_value_, _key_), and iterating
+ * only once over the collection. Non-numeric and non-finite
+ * iteration results are ignored. If there is no numeric,
+ * finite iteration result, then this method returns
+ * `undefined`.
+ *
+ * @method bounds
+ * @param collection {Object|any[]} the collection to
+ * iterate over
+ * @param iteratee {function=_.identity} the iteratee
+ * invoked per element
+ * @return the [min, max] bounds
+ */
+function bounds(collection: Object|any[], iteratee=_.identity) {
+ let min;
+ let max;
+ let check = (value, key) => {
+ let target = iteratee(value, key);
+ if (_.isFinite(target)) {
+ if (_.isUndefined(min) || target < min) {
+ min = target;
+ }
+ if (_.isUndefined(max) || target > max) {
+ max = target;
+ }
+ }
+ };
+ _.forEach(collection, check);
+
+ return _.isUndefined(min) ? undefined : [min, max];
+}
+
+export { bounds }; |
|
73756b42c1de0737d7dcd59529e85bb4819f8373 | webpack/farmware/__tests__/farmware_test.tsx | webpack/farmware/__tests__/farmware_test.tsx | jest.mock("react-redux", () => ({
connect: jest.fn()
}));
import * as React from "react";
import { mount } from "enzyme";
import { FarmwarePage } from "../index";
import { FarmwareProps } from "../../devices/interfaces";
describe("<FarmwarePage />", () => {
it("renders widgets", () => {
const props: FarmwareProps = {
farmwares: {},
syncStatus: "unknown",
env: {},
dispatch: jest.fn(),
currentImage: undefined,
images: []
};
const wrapper = mount(<FarmwarePage {...props} />);
expect(wrapper.text()).toContain("Take Photo");
expect(wrapper.text()).toContain("Farmware");
expect(wrapper.text()).toContain("Camera Calibration");
expect(wrapper.text()).toContain("Weed Detector");
});
});
| jest.mock("react-redux", () => ({
connect: jest.fn()
}));
jest.mock("../../session", () => ({
Session: {
getBool: () => true // Simulate opt-in to beta features.
}
}));
import * as React from "react";
import { mount } from "enzyme";
import { FarmwarePage } from "../index";
import { FarmwareProps } from "../../devices/interfaces";
describe("<FarmwarePage />", () => {
it("renders widgets", () => {
const props: FarmwareProps = {
farmwares: {},
syncStatus: "unknown",
env: {},
dispatch: jest.fn(),
currentImage: undefined,
images: []
};
const wrapper = mount(<FarmwarePage {...props} />);
expect(wrapper.text()).toContain("Take Photo");
expect(wrapper.text()).toContain("Farmware");
expect(wrapper.text()).toContain("Camera Calibration");
expect(wrapper.text()).toContain("Weed Detector");
});
});
| Fix false positive test failure | Fix false positive test failure
| TypeScript | mit | gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API | ---
+++
@@ -1,5 +1,11 @@
jest.mock("react-redux", () => ({
connect: jest.fn()
+}));
+
+jest.mock("../../session", () => ({
+ Session: {
+ getBool: () => true // Simulate opt-in to beta features.
+ }
}));
import * as React from "react"; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.