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
|
---|---|---|---|---|---|---|---|---|---|---|
4ad88f935cd1440e101c47644ed55c4e38afc117 | packages/components/hooks/useOrganization.ts | packages/components/hooks/useOrganization.ts | import { useCallback } from 'react';
import { Organization } from '@proton/shared/lib/interfaces';
import { FREE_ORGANIZATION } from '@proton/shared/lib/constants';
import { OrganizationModel } from '@proton/shared/lib/models/organizationModel';
import { UserModel } from '@proton/shared/lib/models/userModel';
import useCachedModelResult, { getPromiseValue } from './useCachedModelResult';
import useApi from './useApi';
import useCache from './useCache';
export const useGetOrganization = (): (() => Promise<Organization>) => {
const api = useApi();
const cache = useCache();
const miss = useCallback(() => {
// Not using use user since it's better to read from the cache
// It will be updated from the event manager.
const user = cache.get(UserModel.key).value;
if (user.isPaid) {
return OrganizationModel.get(api);
}
return Promise.resolve(FREE_ORGANIZATION);
}, [api, cache]);
return useCallback(() => {
return getPromiseValue(cache, OrganizationModel.key, miss);
}, [cache, miss]);
};
export const useOrganization = (): [Organization, boolean, any] => {
const cache = useCache();
const miss = useGetOrganization();
return useCachedModelResult(cache, OrganizationModel.key, miss);
};
| import { useCallback } from 'react';
import { Organization } from '@proton/shared/lib/interfaces';
import { FREE_ORGANIZATION } from '@proton/shared/lib/constants';
import { OrganizationModel } from '@proton/shared/lib/models/organizationModel';
import useCachedModelResult, { getPromiseValue } from './useCachedModelResult';
import useApi from './useApi';
import useCache from './useCache';
import { useGetUser } from './useUser';
export const useGetOrganization = (): (() => Promise<Organization>) => {
const api = useApi();
const cache = useCache();
const getUser = useGetUser();
const miss = useCallback(async () => {
const user = await getUser();
if (user.isPaid) {
return OrganizationModel.get(api);
}
return Promise.resolve(FREE_ORGANIZATION);
}, [api, cache]);
return useCallback(() => {
return getPromiseValue(cache, OrganizationModel.key, miss);
}, [cache, miss]);
};
export const useOrganization = (): [Organization, boolean, any] => {
const cache = useCache();
const miss = useGetOrganization();
return useCachedModelResult(cache, OrganizationModel.key, miss);
};
| Use async user hook in organization | Use async user hook in organization
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -2,19 +2,18 @@
import { Organization } from '@proton/shared/lib/interfaces';
import { FREE_ORGANIZATION } from '@proton/shared/lib/constants';
import { OrganizationModel } from '@proton/shared/lib/models/organizationModel';
-import { UserModel } from '@proton/shared/lib/models/userModel';
import useCachedModelResult, { getPromiseValue } from './useCachedModelResult';
import useApi from './useApi';
import useCache from './useCache';
+import { useGetUser } from './useUser';
export const useGetOrganization = (): (() => Promise<Organization>) => {
const api = useApi();
const cache = useCache();
- const miss = useCallback(() => {
- // Not using use user since it's better to read from the cache
- // It will be updated from the event manager.
- const user = cache.get(UserModel.key).value;
+ const getUser = useGetUser();
+ const miss = useCallback(async () => {
+ const user = await getUser();
if (user.isPaid) {
return OrganizationModel.get(api);
} |
579c8c20d48bb5288724d755eae0a9dd94b88ef5 | src/Engines/WebGPU/webgpuHardwareTexture.ts | src/Engines/WebGPU/webgpuHardwareTexture.ts | import { HardwareTextureWrapper } from '../../Materials/Textures/hardwareTextureWrapper';
import { Nullable } from '../../types';
import * as WebGPUConstants from './webgpuConstants';
/** @hidden */
export class WebGPUHardwareTexture implements HardwareTextureWrapper {
private _webgpuTexture: Nullable<GPUTexture>;
private _webgpuTextureView: Nullable<GPUTextureView>;
private _webgpuSampler: Nullable<GPUSampler>;
public get underlyingResource(): Nullable<GPUTexture> {
return this._webgpuTexture;
}
public get view(): Nullable<GPUTextureView> {
return this._webgpuTextureView;
}
public get sampler(): Nullable<GPUSampler> {
return this._webgpuSampler;
}
public format: GPUTextureFormat = WebGPUConstants.TextureFormat.RGBA8Unorm;
constructor(existingTexture: Nullable<GPUTexture> = null) {
this._webgpuTexture = existingTexture;
this._webgpuTextureView = null;
this._webgpuSampler = null;
}
public set(hardwareTexture: GPUTexture) {
this._webgpuTexture = hardwareTexture;
}
public createView(descriptor?: GPUTextureViewDescriptor) {
this._webgpuTextureView = this._webgpuTexture!.createView(descriptor);
}
public setSampler(sampler: GPUSampler) {
this._webgpuSampler = sampler;
}
public reset() {
this._webgpuTexture = null;
this._webgpuTextureView = null as any;
this._webgpuSampler = null as any;
}
public release() {
this._webgpuTexture?.destroy();
this.reset();
}
}
| import { HardwareTextureWrapper } from '../../Materials/Textures/hardwareTextureWrapper';
import { Nullable } from '../../types';
import * as WebGPUConstants from './webgpuConstants';
/** @hidden */
export class WebGPUHardwareTexture implements HardwareTextureWrapper {
private _webgpuTexture: Nullable<GPUTexture>;
public get underlyingResource(): Nullable<GPUTexture> {
return this._webgpuTexture;
}
public view: Nullable<GPUTextureView>;
public sampler: Nullable<GPUSampler>;
public format: GPUTextureFormat = WebGPUConstants.TextureFormat.RGBA8Unorm;
constructor(existingTexture: Nullable<GPUTexture> = null) {
this._webgpuTexture = existingTexture;
this.view = null;
this.sampler = null;
}
public set(hardwareTexture: GPUTexture) {
this._webgpuTexture = hardwareTexture;
}
public createView(descriptor?: GPUTextureViewDescriptor) {
this.view = this._webgpuTexture!.createView(descriptor);
}
public reset() {
this._webgpuTexture = null;
this.view = null;
this.sampler = null;
}
public release() {
this._webgpuTexture?.destroy();
this.reset();
}
}
| Remove the accessors, use public properties instead | Remove the accessors, use public properties instead
| TypeScript | apache-2.0 | NicolasBuecher/Babylon.js,NicolasBuecher/Babylon.js,sebavan/Babylon.js,Kesshi/Babylon.js,RaananW/Babylon.js,sebavan/Babylon.js,Kesshi/Babylon.js,NicolasBuecher/Babylon.js,BabylonJS/Babylon.js,RaananW/Babylon.js,RaananW/Babylon.js,Kesshi/Babylon.js,BabylonJS/Babylon.js,sebavan/Babylon.js,BabylonJS/Babylon.js | ---
+++
@@ -6,27 +6,19 @@
export class WebGPUHardwareTexture implements HardwareTextureWrapper {
private _webgpuTexture: Nullable<GPUTexture>;
- private _webgpuTextureView: Nullable<GPUTextureView>;
- private _webgpuSampler: Nullable<GPUSampler>;
public get underlyingResource(): Nullable<GPUTexture> {
return this._webgpuTexture;
}
- public get view(): Nullable<GPUTextureView> {
- return this._webgpuTextureView;
- }
-
- public get sampler(): Nullable<GPUSampler> {
- return this._webgpuSampler;
- }
-
+ public view: Nullable<GPUTextureView>;
+ public sampler: Nullable<GPUSampler>;
public format: GPUTextureFormat = WebGPUConstants.TextureFormat.RGBA8Unorm;
constructor(existingTexture: Nullable<GPUTexture> = null) {
this._webgpuTexture = existingTexture;
- this._webgpuTextureView = null;
- this._webgpuSampler = null;
+ this.view = null;
+ this.sampler = null;
}
public set(hardwareTexture: GPUTexture) {
@@ -34,17 +26,13 @@
}
public createView(descriptor?: GPUTextureViewDescriptor) {
- this._webgpuTextureView = this._webgpuTexture!.createView(descriptor);
- }
-
- public setSampler(sampler: GPUSampler) {
- this._webgpuSampler = sampler;
+ this.view = this._webgpuTexture!.createView(descriptor);
}
public reset() {
this._webgpuTexture = null;
- this._webgpuTextureView = null as any;
- this._webgpuSampler = null as any;
+ this.view = null;
+ this.sampler = null;
}
public release() { |
9d1fcb8ccf18102dafca47d5b1a28a765ea4bb49 | src/ts/worker/senders.ts | src/ts/worker/senders.ts | /// <reference path="../../../node_modules/typescript/lib/lib.webworker.d.ts" />
import { ClearMessage, DisplayMessage, InputType } from '../messages'
import { State } from './state'
import { stringToUtf8ByteArray } from '../util'
export function sendClear(type: InputType) {
const message: ClearMessage = {
action: 'clear',
type
}
self.postMessage(message)
}
export function sendCharacter(input: string) {
const codePoint = input.codePointAt(0)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block,
bytes,
character,
codePoint,
name
}
self.postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16))
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
| /// <reference path="../../../node_modules/typescript/lib/lib.webworker.d.ts" />
import { ClearMessage, DisplayMessage, InputType } from '../messages'
import { State } from './state'
import { stringToUtf8ByteArray } from '../util'
export function sendClear(type: InputType) {
const message: ClearMessage = {
action: 'clear',
type
}
self.postMessage(message)
}
export function sendCharacter(input?: string) {
if (input === undefined) return
const codePoint = input.codePointAt(0)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block,
bytes,
character,
codePoint,
name
}
self.postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16))
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
| Handle undefined input to sendCharacter | Handle undefined input to sendCharacter
| TypeScript | mit | Alexendoo/utf,Alexendoo/utf,Alexendoo/utf,Alexendoo/utf | ---
+++
@@ -13,7 +13,8 @@
self.postMessage(message)
}
-export function sendCharacter(input: string) {
+export function sendCharacter(input?: string) {
+ if (input === undefined) return
const codePoint = input.codePointAt(0)
const block = getBlock(codePoint) |
bb3b93fa0473504db53b5fc135ea855a2e8946d5 | source/main/trezor/connection.ts | source/main/trezor/connection.ts | import TrezorConnect from 'trezor-connect';
import { logger } from '../utils/logging';
import { manifest } from './manifest';
export const initTrezorConnect = async () => {
try {
await TrezorConnect.init({
popup: false, // render your own UI
webusb: false, // webusb is not supported in electron
debug: process.env.DEBUG_TREZOR === 'true',
manifest,
});
logger.info('[TREZOR-CONNECT] Called TrezorConnect.init()');
} catch (error) {
logger.info('[TREZOR-CONNECT] Failed to call TrezorConnect.init()');
throw error;
}
};
export const reinitTrezorConnect = () => {
try {
logger.info('[TREZOR-CONNECT] Called TrezorConnect.dispose()');
TrezorConnect.dispose();
} catch (error) {
// ignore any TrezorConnect instance disposal errors
logger.info('[TREZOR-CONNECT] Failed to call TrezorConnect.dispose()');
}
return initTrezorConnect();
};
| import TrezorConnect from 'trezor-connect';
import { logger } from '../utils/logging';
import { manifest } from './manifest';
export const initTrezorConnect = async () => {
try {
await TrezorConnect.init({
popup: false, // render your own UI
webusb: false, // webusb is not supported in electron
debug: process.env.DEBUG_TREZOR === 'true',
manifest,
});
logger.info('[TREZOR-CONNECT] Called TrezorConnect.init()');
} catch (error) {
logger.info('[TREZOR-CONNECT] Failed to call TrezorConnect.init()');
}
};
export const reinitTrezorConnect = () => {
try {
logger.info('[TREZOR-CONNECT] Called TrezorConnect.dispose()');
TrezorConnect.dispose();
} catch (error) {
// ignore any TrezorConnect instance disposal errors
logger.info('[TREZOR-CONNECT] Failed to call TrezorConnect.dispose()');
}
return initTrezorConnect();
};
| Stop re-throwing Trezor initialization errors | [DDW-1108] Stop re-throwing Trezor initialization errors
| TypeScript | apache-2.0 | input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus | ---
+++
@@ -14,7 +14,6 @@
logger.info('[TREZOR-CONNECT] Called TrezorConnect.init()');
} catch (error) {
logger.info('[TREZOR-CONNECT] Failed to call TrezorConnect.init()');
- throw error;
}
};
|
bae68a89a603158267d1edfb79e5c5b4b08a40f6 | src/renderer/transcriptEditor.ts | src/renderer/transcriptEditor.ts | import { Quill } from "quill";
import { formatTimestampsOnTextChange } from "./formatTimestamps";
const customBlots = ["Timestamp"];
const registerBlots = (blotNames: string[]) => {
blotNames.map(
( blotName ) => {
const blotPath = `./../blots/${blotName}`;
const blot = require(blotPath);
Quill.register(blot);
},
);
};
export let transcriptEditor = new Quill(".transcript-editor", {
modules: {
toolbar: "#toolbar",
},
theme: "snow",
placeholder: "Transcribe away...",
});
formatTimestampsOnTextChange(transcriptEditor);
registerBlots(customBlots);
| import { Quill } from "quill";
import { formatTimestampsOnTextChange } from "./formatTimestamps";
const customBlots = ["Timestamp"];
const registerBlots = (blotNames: string[]) => {
blotNames.map((blotName) => {
const blotPath = `./../blots/${blotName}`;
const blot = require(blotPath);
Quill.register(blot);
});
};
const transcriptEditor = new Quill(".transcript-editor", {
modules: {
toolbar: "#toolbar",
},
theme: "snow",
placeholder: "Transcribe away...",
});
formatTimestampsOnTextChange(transcriptEditor);
registerBlots(customBlots);
export { transcriptEditor };
| Add a separate `export { }` directive | Add a separate `export { }` directive
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -4,16 +4,14 @@
const customBlots = ["Timestamp"];
const registerBlots = (blotNames: string[]) => {
- blotNames.map(
- ( blotName ) => {
- const blotPath = `./../blots/${blotName}`;
- const blot = require(blotPath);
- Quill.register(blot);
- },
- );
+ blotNames.map((blotName) => {
+ const blotPath = `./../blots/${blotName}`;
+ const blot = require(blotPath);
+ Quill.register(blot);
+ });
};
-export let transcriptEditor = new Quill(".transcript-editor", {
+const transcriptEditor = new Quill(".transcript-editor", {
modules: {
toolbar: "#toolbar",
},
@@ -23,3 +21,4 @@
formatTimestampsOnTextChange(transcriptEditor);
registerBlots(customBlots);
+export { transcriptEditor }; |
aa0707fa2775d9c07858046245c0d6f0280828cd | src/components/calendar/calendar.module.ts | src/components/calendar/calendar.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CalendarComponent } from './calendar.component';
@NgModule({
declarations: [CalendarComponent],
exports: [CalendarComponent],
imports: [BrowserModule, FormsModule]
})
export class CalendarModule { }
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CalendarComponent } from './calendar.component';
@NgModule({
declarations: [CalendarComponent],
exports: [CalendarComponent],
imports: [CommonModule, FormsModule]
})
export class CalendarModule { }
| Replace BrowserModule with CommonModule in calendar | Replace BrowserModule with CommonModule in calendar
| TypeScript | mit | swimlane/ngx-ui,swimlane/ngx-ui,Hypercubed/ngx-ui,swimlane/ngx-ui,Hypercubed/ngx-ui,Hypercubed/ngx-ui,Hypercubed/ngx-ui,swimlane/ngx-ui | ---
+++
@@ -1,5 +1,5 @@
import { NgModule } from '@angular/core';
-import { BrowserModule } from '@angular/platform-browser';
+import { CommonModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CalendarComponent } from './calendar.component';
@@ -7,6 +7,6 @@
@NgModule({
declarations: [CalendarComponent],
exports: [CalendarComponent],
- imports: [BrowserModule, FormsModule]
+ imports: [CommonModule, FormsModule]
})
export class CalendarModule { } |
c0effc11163ea16d8213613deeed44f911e9aeb1 | apps/docs/src/common/page-wrap.tsx | apps/docs/src/common/page-wrap.tsx | import { FC, createElement as h } from 'react';
import { PageProps } from '@not-govuk/app-composer';
import { Page } from '@hods/components';
import './app.scss';
export const PageWrap: FC<PageProps> = ({ children }) => {
const navigation = [
{ href: '/get-started', text: 'Get started' },
{ href: '/styles', text: 'Styles' },
{ href: '/components', text: 'Components' },
{ href: '/patterns', text: 'Patterns' },
{ href: '/resources', text: 'Resources' },
{ href: '/get-involved', text: 'Get involved' }
];
const footerNavigation = [
{ href: 'https://github.com/UKHomeOffice/hods-poc/', text: 'GitHub' },
{ href: '/cookies', text: 'Cookies' },
{ href: 'https://github.com/UKHomeOffice/hods-poc/issues/new', text: 'Feedback' },
{ href: 'https://design-system.service.gov.uk/', text: 'Gov.UK Design System' }
];
return (
<Page
footerNavigation={footerNavigation}
navigation={navigation}
title="Design System"
>
{children}
</Page>
);
};
export default PageWrap;
| import { FC, createElement as h } from 'react';
import { PageProps } from '@not-govuk/app-composer';
import { Page } from '@hods/components';
import './app.scss';
export const PageWrap: FC<PageProps> = ({ children }) => {
const navigation = [
{ href: '/get-started', text: 'Get started' },
{ href: '/styles', text: 'Styles' },
{ href: '/components', text: 'Components' },
{ href: '/patterns', text: 'Patterns' },
{ href: '/resources', text: 'Resources' },
{ href: '/get-involved', text: 'Get involved' }
];
const footerNavigation = [
{ href: 'https://github.com/UKHomeOffice/hods-poc/', text: 'GitHub' },
{ href: '/cookies', text: 'Cookies' },
{ href: 'https://github.com/UKHomeOffice/hods-poc/issues/new', text: 'Feedback' },
{ href: 'https://design-system.service.gov.uk/', text: 'Gov.UK Design System' }
];
return (
<Page
footerNavigation={footerNavigation}
navigation={navigation}
serviceName="Design System"
title="Home Office Design System"
>
{children}
</Page>
);
};
export default PageWrap;
| Update use of Page component | docs: Update use of Page component
| TypeScript | mit | eliothill/home-office-digital-patterns,eliothill/home-office-digital-patterns,eliothill/home-office-digital-patterns | ---
+++
@@ -24,7 +24,8 @@
<Page
footerNavigation={footerNavigation}
navigation={navigation}
- title="Design System"
+ serviceName="Design System"
+ title="Home Office Design System"
>
{children}
</Page> |
43d671dc661a23df2da41f93e5a6c7c5784b0cac | test/_builders/stream-builder.ts | test/_builders/stream-builder.ts | import { IStream } from "../../src/stream/stream.i";
export class StreamBuilder {
public build(): IStream {
return <IStream> {
writeLine: (message: string) => { }
};
}
}
| import { IStream } from "../../src/stream/stream.i";
export class StreamBuilder {
public build(): IStream {
return <IStream> {
writeLine: (message: string) => { },
write: (message: string) => { },
moveCursor: (x: number, y: number) => { },
cursorTo: (x: number, y: number) => { },
clearLine: () => { }
};
}
}
| Add new methods to StreamBuilders | Add new methods to StreamBuilders
| TypeScript | mit | alsatian-test/tap-bark,alsatian-test/tap-bark | ---
+++
@@ -4,7 +4,11 @@
public build(): IStream {
return <IStream> {
- writeLine: (message: string) => { }
+ writeLine: (message: string) => { },
+ write: (message: string) => { },
+ moveCursor: (x: number, y: number) => { },
+ cursorTo: (x: number, y: number) => { },
+ clearLine: () => { }
};
}
|
4ef928ca86b88b22b88295815e3f4812540fcf9f | scripts/utils/generateTypings.ts | scripts/utils/generateTypings.ts | import * as fs from 'fs';
import * as path from 'path';
import { Definition } from '../../src/components/definition';
const configs = require('../configs.json');
const cwd = process.cwd();
export type Logger = (data: LoggerData) => void;
export interface LoggerData {
input: string;
output: string;
}
const templateDir = path.resolve(cwd, configs.templateDir);
const outputDir = path.resolve(cwd, configs.outputDir);
const extRegex = /\.md$/;
export default (templateFiles: string[], logger: Logger) => {
const templateTsFiles = Array.from(new Set(templateFiles.map(
file => extRegex.test(file) ? file.replace(extRegex, '.ts') : file)));
templateTsFiles.forEach(templateTsFile => {
const templateModule = require(templateTsFile).default;
delete require.cache[require.resolve(templateTsFile)];
if (!(templateModule instanceof Definition)) {
console.log(`WARN: Module '${templateTsFile}' should be an instance of Definition`);
return;
}
const outputFile = templateTsFile
.replace(templateDir, outputDir)
.replace(/\.ts$/, '.d.ts');
fs.writeFileSync(outputFile, templateModule.toString());
logger({
input: path.relative(cwd, templateTsFile),
output: path.relative(cwd, outputFile),
});
});
};
| import * as fs from 'fs';
import * as path from 'path';
import { Definition } from '../../src/components/definition';
const configs = require('../configs.json');
const cwd = process.cwd();
export type Logger = (data: LoggerData) => void;
export interface LoggerData {
input: string;
output: string;
}
const templateDir = path.resolve(cwd, configs.templateDir);
const outputDir = path.resolve(cwd, configs.outputDir);
const extRegex = /\.md$/;
export default (templateFiles: string[], logger: Logger) => {
const templateTsFiles = Array.from(new Set(templateFiles.map(
file => extRegex.test(file) ? file.replace(extRegex, '.ts') : file)));
templateTsFiles.forEach(templateTsFile => {
let templateModule;
try {
templateModule = require(templateTsFile).default;
} catch (error) {
console.log((error as Error).message);
return;
}
delete require.cache[require.resolve(templateTsFile)];
if (!(templateModule instanceof Definition)) {
console.log(`WARN: Module '${templateTsFile}' should be an instance of Definition`);
return;
}
const outputFile = templateTsFile
.replace(templateDir, outputDir)
.replace(/\.ts$/, '.d.ts');
fs.writeFileSync(outputFile, templateModule.toString());
logger({
input: path.relative(cwd, templateTsFile),
output: path.relative(cwd, outputFile),
});
});
};
| Update scripts catch compile error | Update scripts
catch compile error
| TypeScript | mit | ikatyang/types-ramda,ikatyang/types-ramda | ---
+++
@@ -21,7 +21,13 @@
const templateTsFiles = Array.from(new Set(templateFiles.map(
file => extRegex.test(file) ? file.replace(extRegex, '.ts') : file)));
templateTsFiles.forEach(templateTsFile => {
- const templateModule = require(templateTsFile).default;
+ let templateModule;
+ try {
+ templateModule = require(templateTsFile).default;
+ } catch (error) {
+ console.log((error as Error).message);
+ return;
+ }
delete require.cache[require.resolve(templateTsFile)];
if (!(templateModule instanceof Definition)) {
console.log(`WARN: Module '${templateTsFile}' should be an instance of Definition`); |
5741a4ff4ebf7c1a92f6374ba4334540beddba9e | types/fast-ratelimit/fast-ratelimit-tests.ts | types/fast-ratelimit/fast-ratelimit-tests.ts | import { FastRateLimit } from 'fast-ratelimit';
const limit = new FastRateLimit({ // $type: FastRateLimit
threshold: 20,
ttl: 60,
});
const someNamespace = 'some-namespace';
const consume = limit.consume(someNamespace); // $type: Promise<any>
consume.then(() => {}); // User can send message.
consume.catch(() => {}); // Use cannot send message.
const hasToken = limit.hasToken(someNamespace); // $type: Promise<any>
consume.then(() => {}); // User has remaining token.
consume.catch(() => {}); // User does not have remaining token.
// Synchronously check if user is allowed to send message.
const consumeSync = limit.consumeSync(someNamespace); // $type: boolean
// Synchronously check if user has remaining token.
const hasTokenSync = limit.hasTokenSync(someNamespace); // $type: boolean | import { FastRateLimit } from 'fast-ratelimit';
const limit = new FastRateLimit({ // $type: FastRateLimit
threshold: 20,
ttl: 60,
});
const someNamespace = 'some-namespace';
const consume = limit.consume(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User can send message.
consume.catch(() => {}); // Use cannot send message.
const hasToken = limit.hasToken(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User has remaining token.
consume.catch(() => {}); // User does not have remaining token.
// Synchronously check if user is allowed to send message.
const consumeSync = limit.consumeSync(someNamespace); // $type: boolean
// Synchronously check if user has remaining token.
const hasTokenSync = limit.hasTokenSync(someNamespace); // $type: boolean | Correct expected promise type in fast-ratelimit test comments. | Correct expected promise type in fast-ratelimit test comments.
| TypeScript | mit | dsebastien/DefinitelyTyped,mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped | ---
+++
@@ -7,11 +7,11 @@
const someNamespace = 'some-namespace';
-const consume = limit.consume(someNamespace); // $type: Promise<any>
+const consume = limit.consume(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User can send message.
consume.catch(() => {}); // Use cannot send message.
-const hasToken = limit.hasToken(someNamespace); // $type: Promise<any>
+const hasToken = limit.hasToken(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User has remaining token.
consume.catch(() => {}); // User does not have remaining token.
|
7227ca7449fbfea85b662ef7847c2ba2f135d832 | packages/presentational-components/src/components/source.tsx | packages/presentational-components/src/components/source.tsx | import * as React from "react";
import Highlighter from "../syntax-highlighter";
export type SourceProps = {
language: string;
children: React.ReactNode[];
className: string;
theme: "light" | "dark";
};
export class Source extends React.Component<SourceProps> {
static defaultProps = {
children: "",
language: "text",
className: "input",
theme: "light"
};
render() {
// Build in a default renderer when they pass a plain string
// This is primarily for use with non-editable contexts (notebook-preview)
// to make rendering much faster (compared to codemirror)
// Ref: https://github.com/nteract/notebook-preview/issues/20
if (typeof this.props.children === "string") {
return (
<Highlighter
language={this.props.language}
className={this.props.className}
>
{this.props.children}
</Highlighter>
);
}
// Otherwise assume they have their own editor component
return <div className="input">{this.props.children}</div>;
}
}
| import * as React from "react";
import Highlighter from "../syntax-highlighter";
export type SourceProps = {
language: string;
children: React.ReactNode;
className: string;
theme: "light" | "dark";
};
export class Source extends React.Component<SourceProps> {
static defaultProps = {
children: "",
language: "text",
className: "input",
theme: "light"
};
render() {
// Build in a default renderer when they pass a plain string
// This is primarily for use with non-editable contexts (notebook-preview)
// to make rendering much faster (compared to codemirror)
// Ref: https://github.com/nteract/notebook-preview/issues/20
if (typeof this.props.children === "string") {
return (
<Highlighter
language={this.props.language}
className={this.props.className}
>
{this.props.children}
</Highlighter>
);
}
// Otherwise assume they have their own editor component
return <div className="input">{this.props.children}</div>;
}
}
| Fix types for Source presentational component | Fix types for Source presentational component
| TypeScript | bsd-3-clause | nteract/nteract,nteract/composition,nteract/composition,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract | ---
+++
@@ -4,7 +4,7 @@
export type SourceProps = {
language: string;
- children: React.ReactNode[];
+ children: React.ReactNode;
className: string;
theme: "light" | "dark";
}; |
e12ae55aa7ab192b262a0c2ad4f017af1cc3c740 | src/client/VSTS/authMM.ts | src/client/VSTS/authMM.ts | import { Rest } from '../RestHelpers/rest';
/**
* interface for callback
* @interface IAuthStateCallback
*/
export interface IAuthStateCallback { (state: string): void; }
/**
* Connects to user database
* @class Auth
*/
export class Auth {
/**
* check user database for token associated with user email
* @param {string} user - user's email address
* @param {IAuthStateCallback} callback
* @return {void}
*/
public static getAuthState(callback: IAuthStateCallback): void {
Rest.getUser((user: string) => {
$.get('./authenticate/db?user=' + user, (output) => {
if (output === 'success') {
callback('success');
} else {
callback('failure');
}
});
});
}
}
| import { Rest } from '../RestHelpers/rest';
/**
* interface for callback
* @interface IAuthStateCallback
*/
export interface IAuthStateCallback { (state: string): void; }
/**
* Connects to user database
* @class Auth
*/
export class Auth {
/**
* check user database for token associated with user email
* @param {string} user - user's email address
* @param {IAuthStateCallback} callback
* @return {void}
*/
public static getAuthState(callback: IAuthStateCallback): void {
Rest.getUser((user: string) => {
$.get('./authenticate/db?user=' + user + '&trash=' + (Math.random() * 1000), (output) => {
if (output === 'success') {
callback('success');
} else {
callback('failure');
}
});
});
}
}
| Fix Auth issue in desktop | Fix Auth issue in desktop
| TypeScript | mit | annich-MS/OutlookVSTS,annich-MS/OutlookVSTS,annich-MS/OutlookVSTS | ---
+++
@@ -19,7 +19,7 @@
*/
public static getAuthState(callback: IAuthStateCallback): void {
Rest.getUser((user: string) => {
- $.get('./authenticate/db?user=' + user, (output) => {
+ $.get('./authenticate/db?user=' + user + '&trash=' + (Math.random() * 1000), (output) => {
if (output === 'success') {
callback('success');
} else { |
58defee7e6bbf1d85d0743c382d2c88d8db72eac | web-ng/src/app/components/project-header/project-header.component.ts | web-ng/src/app/components/project-header/project-header.component.ts | /**
* Copyright 2020 Google LLC
*
* 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
*
* https://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 { Component, OnInit, ElementRef } from '@angular/core';
import { AuthService } from './../../services/auth/auth.service';
import { UserProfilePopupComponent } from '../../components/user-profile-popup/user-profile-popup.component';
import { MatDialog } from '@angular/material/dialog';
import { ShareDialogComponent } from '../share-dialog/share-dialog.component';
@Component({
selector: 'app-project-header',
templateUrl: './project-header.component.html',
styleUrls: ['./project-header.component.scss'],
})
export class ProjectHeaderComponent implements OnInit {
constructor(public auth: AuthService, private dialog: MatDialog) {}
ngOnInit() {}
openProfileDialog(evt: MouseEvent): void {
const target = new ElementRef(evt.currentTarget);
this.dialog.open(UserProfilePopupComponent, {
data: { trigger: target },
});
}
private openShareDialog(): void {
this.dialog.open(ShareDialogComponent);
}
}
| /**
* Copyright 2020 Google LLC
*
* 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
*
* https://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 { Component, OnInit, ElementRef } from '@angular/core';
import { AuthService } from './../../services/auth/auth.service';
import { UserProfilePopupComponent } from '../../components/user-profile-popup/user-profile-popup.component';
import { MatDialog } from '@angular/material/dialog';
import { ShareDialogComponent } from '../share-dialog/share-dialog.component';
@Component({
selector: 'app-project-header',
templateUrl: './project-header.component.html',
styleUrls: ['./project-header.component.scss'],
})
export class ProjectHeaderComponent implements OnInit {
constructor(public auth: AuthService, private dialog: MatDialog) {}
ngOnInit() {}
openProfileDialog(evt: MouseEvent): void {
const target = new ElementRef(evt.currentTarget);
this.dialog.open(UserProfilePopupComponent, {
data: { trigger: target },
});
}
private openShareDialog(): void {
this.dialog.open(ShareDialogComponent, { autoFocus: false });
}
}
| Disable auto focus when opening share dialog | Disable auto focus when opening share dialog
| TypeScript | apache-2.0 | google/ground-platform,google/ground-platform,google/ground-platform,google/ground-platform | ---
+++
@@ -38,6 +38,6 @@
}
private openShareDialog(): void {
- this.dialog.open(ShareDialogComponent);
+ this.dialog.open(ShareDialogComponent, { autoFocus: false });
}
} |
86e85fd0e0e69e887ca75c1d8ab3650d9b66e8d8 | types/get-caller-file/index.d.ts | types/get-caller-file/index.d.ts | // Type definitions for get-caller-file 1.0
// Project: https://github.com/stefanpenner/get-caller-file#readme
// Definitions by: Klaus Meinhardt <https://github.com/ajafff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function getCallerFile(position?: number): string;
declare namespace getCallerFile {}
export = getCallerFile;
| // Type definitions for get-caller-file 1.0
// Project: https://github.com/stefanpenner/get-caller-file#readme
// Definitions by: Klaus Meinhardt <https://github.com/ajafff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function getCallerFile(position?: number): string;
export = getCallerFile;
| Remove namespace per review comment | Remove namespace per review comment
| TypeScript | mit | chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,mcliment/DefinitelyTyped | ---
+++
@@ -4,6 +4,5 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function getCallerFile(position?: number): string;
-declare namespace getCallerFile {}
export = getCallerFile; |
7fc647fe64b53e2802e8950ce9a70c36b14c263c | app.ts | app.ts | export class App {
private _events: Object;
public start;
public h;
public createElement;
constructor() {
this._events = {};
}
on(name: string, fn: (...args) => void, options: any = {}) {
if (options.debug) console.debug('on: ' + name);
this._events[name] = this._events[name] || [];
this._events[name].push({ fn: fn, options: options });
}
run(name: string, ...args) {
const subscribers = this._events[name];
console.assert(!!subscribers, 'No subscriber for event: ' + name);
if (subscribers) this._events[name] = subscribers.filter((sub) => {
let {fn, options} = sub;
if (options.delay) {
this.delay(name, fn, args, options);
} else {
if (options.debug) console.debug('run: ' + name, args);
fn.apply(this, args);
}
return !sub.options.once;
});
}
private delay(name, fn, args, options) {
if (options._t) clearTimeout(options._t);
options._t = setTimeout(() => {
clearTimeout(options._t);
if (options.debug) console.debug(`run-delay ${options.delay}:` + name, args);
fn.apply(this, args);
}, options.delay);
}
}
let app = new App();
export default app;
| import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/debounceTime';
export class App {
private subjects = {}
public start;
public h;
public createElement;
constructor() {
}
on(name: string, fn: Function, options: any = {}) {
if (options.debug) console.debug('on: ' + name);
this.subjects[name] || (this.subjects[name] = new Subject);
let subject = this.subjects[name] as Observable<{}>;
if (options.delay) subject = subject.debounceTime(options.delay);
if (options.once) subject = subject.first();
return subject.subscribe((args) => {
if (options.debug) console.debug('run: ' + name);
fn.apply(this, args);
});
}
run(name: string, ...args: any[]) {
const subject = this.subjects[name];
console.assert(!!subject, 'No subscriber for event: ' + name);
this.subjects[name].next(args);
}
}
export default new App(); | Use RxJS for event pubsub | Use RxJS for event pubsub
| TypeScript | mit | yysun/apprun,yysun/apprun,yysun/apprun | ---
+++
@@ -1,44 +1,34 @@
+import {Subject} from 'rxjs/Subject';
+import {Observable} from 'rxjs/Observable';
+import 'rxjs/add/operator/first';
+import 'rxjs/add/operator/debounceTime';
+
export class App {
- private _events: Object;
+ private subjects = {}
public start;
public h;
public createElement;
constructor() {
- this._events = {};
}
- on(name: string, fn: (...args) => void, options: any = {}) {
+ on(name: string, fn: Function, options: any = {}) {
if (options.debug) console.debug('on: ' + name);
- this._events[name] = this._events[name] || [];
- this._events[name].push({ fn: fn, options: options });
- }
-
- run(name: string, ...args) {
- const subscribers = this._events[name];
- console.assert(!!subscribers, 'No subscriber for event: ' + name);
- if (subscribers) this._events[name] = subscribers.filter((sub) => {
- let {fn, options} = sub;
- if (options.delay) {
- this.delay(name, fn, args, options);
- } else {
- if (options.debug) console.debug('run: ' + name, args);
- fn.apply(this, args);
- }
- return !sub.options.once;
+ this.subjects[name] || (this.subjects[name] = new Subject);
+ let subject = this.subjects[name] as Observable<{}>;
+ if (options.delay) subject = subject.debounceTime(options.delay);
+ if (options.once) subject = subject.first();
+ return subject.subscribe((args) => {
+ if (options.debug) console.debug('run: ' + name);
+ fn.apply(this, args);
});
}
- private delay(name, fn, args, options) {
- if (options._t) clearTimeout(options._t);
- options._t = setTimeout(() => {
- clearTimeout(options._t);
- if (options.debug) console.debug(`run-delay ${options.delay}:` + name, args);
- fn.apply(this, args);
- }, options.delay);
+ run(name: string, ...args: any[]) {
+ const subject = this.subjects[name];
+ console.assert(!!subject, 'No subscriber for event: ' + name);
+ this.subjects[name].next(args);
}
}
-
-let app = new App();
-export default app;
+export default new App(); |
b5dced02027577ac4ff5773290bfd5053da03280 | packages/stateful-components/__tests__/inputs/editor.spec.tsx | packages/stateful-components/__tests__/inputs/editor.spec.tsx | import { selectors } from "@nteract/core";
import { mockAppState } from "@nteract/fixtures";
import { makeMapStateToProps } from "../../src/inputs/editor";
describe("makeMapStateToProps", () => {
it("returns default values if input document is not a notebook", () => {
const state = mockAppState();
const ownProps = {
contentRef: "anyContentRef",
id: "nonExistantCell",
children: []
};
const mapStateToProps = makeMapStateToProps(state, ownProps);
expect(mapStateToProps(state)).toEqual({
editorType: "codemirror",
editorFocused: false,
channels: null,
theme: "light",
kernelStatus: "not connected",
value: ""
});
});
it("returns kernel and channels if input cell is code cell", () => {
const state = mockAppState({ codeCellCount: 1 });
const contentRef = state.core.entities.contents.byRef.keySeq().first();
const model = selectors.model(state, { contentRef });
const id = selectors.notebook.cellOrder(model).first();
const ownProps = {
contentRef,
id,
children: []
};
const mapStateToProps = makeMapStateToProps(state, ownProps);
expect(mapStateToProps(state).channels).not.toBeNull();
});
});
| import React from "react";
import { mount } from "enzyme";
import { selectors } from "@nteract/core";
import { mockAppState } from "@nteract/fixtures";
import { makeMapStateToProps, Editor } from "../../src/inputs/editor";
describe("makeMapStateToProps", () => {
it("returns default values if input document is not a notebook", () => {
const state = mockAppState();
const ownProps = {
contentRef: "anyContentRef",
id: "nonExistantCell",
children: []
};
const mapStateToProps = makeMapStateToProps(state, ownProps);
expect(mapStateToProps(state)).toEqual({
editorType: "codemirror",
editorFocused: false,
channels: null,
theme: "light",
kernelStatus: "not connected",
value: ""
});
});
it("returns kernel and channels if input cell is code cell", () => {
const state = mockAppState({ codeCellCount: 1 });
const contentRef = state.core.entities.contents.byRef.keySeq().first();
const model = selectors.model(state, { contentRef });
const id = selectors.notebook.cellOrder(model).first();
const ownProps = {
contentRef,
id,
children: []
};
const mapStateToProps = makeMapStateToProps(state, ownProps);
expect(mapStateToProps(state).channels).not.toBeNull();
});
});
describe("<Editor/>", () => {
it("returns nothing if it has no children", () => {
const component = mount(<Editor editorType="monaco" />);
expect(component).toBeNull();
});
it("renders the matching child");
});
| Add tests for Editor stateful component | Add tests for Editor stateful component
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition,nteract/nteract | ---
+++
@@ -1,7 +1,10 @@
+import React from "react";
+import { mount } from "enzyme";
+
import { selectors } from "@nteract/core";
import { mockAppState } from "@nteract/fixtures";
-import { makeMapStateToProps } from "../../src/inputs/editor";
+import { makeMapStateToProps, Editor } from "../../src/inputs/editor";
describe("makeMapStateToProps", () => {
it("returns default values if input document is not a notebook", () => {
@@ -35,3 +38,11 @@
expect(mapStateToProps(state).channels).not.toBeNull();
});
});
+
+describe("<Editor/>", () => {
+ it("returns nothing if it has no children", () => {
+ const component = mount(<Editor editorType="monaco" />);
+ expect(component).toBeNull();
+ });
+ it("renders the matching child");
+}); |
dd80f53b1f8bab81a7fc083ce486e2520df2f584 | console/src/app/core/models/chart/mongoose-chart-interface/mongoose-chart-options.ts | console/src/app/core/models/chart/mongoose-chart-interface/mongoose-chart-options.ts | export class MongooseChartOptions {
// NOTE: Fields are public since they should match ng-chart2 library naming
// link: https://github.com/valor-software/ng2-charts
public scaleShowVerticalLines: boolean = false;
public responsive: boolean = true;
public responsiveAnimationDuration: number = 0;
public animation: any = {
duration: 0
}
constructor(shouldScaleShowVerticalLines: boolean = false, isResponsive: boolean = true) {
this.scaleShowVerticalLines = shouldScaleShowVerticalLines;
this.responsive = isResponsive;
}
}
| export class MongooseChartOptions {
// NOTE: Fields are public since they should match ng-chart2 library naming
// link: https://github.com/valor-software/ng2-charts
public scaleShowVerticalLines: boolean = false;
public responsive: boolean = true;
public responsiveAnimationDuration: number = 0;
public animation: any = {
duration: 0
}
public scales: any = {
yAxes: [{
type: 'logarithmic'
}]
}
constructor(shouldScaleShowVerticalLines: boolean = false, isResponsive: boolean = true) {
this.scaleShowVerticalLines = shouldScaleShowVerticalLines;
this.responsive = isResponsive;
}
}
| Add logatirhmic scaling to Y axes on every chart. | Add logatirhmic scaling to Y axes on every chart.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -8,6 +8,11 @@
public animation: any = {
duration: 0
}
+ public scales: any = {
+ yAxes: [{
+ type: 'logarithmic'
+ }]
+ }
constructor(shouldScaleShowVerticalLines: boolean = false, isResponsive: boolean = true) {
this.scaleShowVerticalLines = shouldScaleShowVerticalLines; |
71a02408291654f5a810e7b6409a051b978bcbae | src/marketplace/offerings/service-providers/ServiceProvidersGrid.tsx | src/marketplace/offerings/service-providers/ServiceProvidersGrid.tsx | import { FunctionComponent, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { SERVICE_PROVIDERS_GRID } from '@waldur/marketplace/offerings/service-providers/constants';
import Grid from '@waldur/marketplace/offerings/service-providers/shared/grid/Grid';
import { ServiceProviderDetailsCard } from '@waldur/marketplace/offerings/service-providers/shared/ServiceProviderDetailsCard';
import { connectTable, createFetcher } from '@waldur/table';
import { updatePageSize } from '@waldur/table/actions';
import { ANONYMOUS_CONFIG } from '@waldur/table/api';
const GridComponent: FunctionComponent<any> = (props) => {
const { translate } = props;
const dispatch = useDispatch();
useEffect(() => {
dispatch(updatePageSize(SERVICE_PROVIDERS_GRID, { label: '', value: 8 }));
}, [dispatch]);
return (
<Grid
{...props}
verboseName={translate('Service providers')}
hasQuery={true}
queryPlaceholder={translate('Search by name or abbreviation')}
gridItemComponent={ServiceProviderDetailsCard}
/>
);
};
const GridOptions = {
table: SERVICE_PROVIDERS_GRID,
fetchData: createFetcher('marketplace-service-providers', ANONYMOUS_CONFIG),
queryField: 'query',
};
export const ServiceProvidersGrid = connectTable(GridOptions)(GridComponent);
| import { FunctionComponent, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { SERVICE_PROVIDERS_GRID } from '@waldur/marketplace/offerings/service-providers/constants';
import Grid from '@waldur/marketplace/offerings/service-providers/shared/grid/Grid';
import { ServiceProviderDetailsCard } from '@waldur/marketplace/offerings/service-providers/shared/ServiceProviderDetailsCard';
import { connectTable, createFetcher } from '@waldur/table';
import { updatePageSize } from '@waldur/table/actions';
import { ANONYMOUS_CONFIG } from '@waldur/table/api';
const GridComponent: FunctionComponent<any> = (props) => {
const { translate } = props;
const dispatch = useDispatch();
useEffect(() => {
dispatch(updatePageSize(SERVICE_PROVIDERS_GRID, { label: '', value: 8 }));
}, [dispatch]);
return (
<Grid
{...props}
verboseName={translate('Service providers')}
hasQuery={true}
queryPlaceholder={translate('Search by name or abbreviation')}
gridItemComponent={ServiceProviderDetailsCard}
/>
);
};
const GridOptions = {
table: SERVICE_PROVIDERS_GRID,
fetchData: createFetcher('marketplace-service-providers', ANONYMOUS_CONFIG),
queryField: 'customer_keyword',
};
export const ServiceProvidersGrid = connectTable(GridOptions)(GridComponent);
| Use customer_keyword query param for filtering service-providers by name or abbreviation | Use customer_keyword query param for filtering service-providers by name or abbreviation
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -28,7 +28,7 @@
const GridOptions = {
table: SERVICE_PROVIDERS_GRID,
fetchData: createFetcher('marketplace-service-providers', ANONYMOUS_CONFIG),
- queryField: 'query',
+ queryField: 'customer_keyword',
};
export const ServiceProvidersGrid = connectTable(GridOptions)(GridComponent); |
bc3256d2e9622a640a0373f63f6155be120d49cb | index.d.ts | index.d.ts | // Copyright 2021 Google LLC
//
// 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
//
// https://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.
interface $ {
(pieces: TemplateStringsArray, ...args: string[]): Promise<ProcessOutput>
verbose: boolean
shell: string
cwd: string
prefix: string
quote: (input: string) => string
}
export const $: $
export function cd(path: string)
export function question(query?: string, options?: QuestionOptions): Promise<string>
export type QuestionOptions = { choices: string[] }
export function sleep(ms: number): Promise<void>
export class ProcessOutput {
readonly exitCode: number
readonly stdout: string
readonly stderr: string
toString(): string
}
| // Copyright 2021 Google LLC
//
// 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
//
// https://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.
interface $ {
(pieces: TemplateStringsArray, ...args: any[]): Promise<ProcessOutput>
verbose: boolean
shell: string
cwd: string
prefix: string
quote: (input: string) => string
}
export const $: $
export function cd(path: string)
export function question(query?: string, options?: QuestionOptions): Promise<string>
export type QuestionOptions = { choices: string[] }
export function sleep(ms: number): Promise<void>
export class ProcessOutput {
readonly exitCode: number
readonly stdout: string
readonly stderr: string
toString(): string
}
| Fix types for $ func | Fix types for $ func
| TypeScript | apache-2.0 | google/zx,google/zx | ---
+++
@@ -13,7 +13,7 @@
// limitations under the License.
interface $ {
- (pieces: TemplateStringsArray, ...args: string[]): Promise<ProcessOutput>
+ (pieces: TemplateStringsArray, ...args: any[]): Promise<ProcessOutput>
verbose: boolean
shell: string
cwd: string |
f010aec5620f5e339c35f3430b1cd438e3726d16 | src/lib/generate.ts | src/lib/generate.ts | import 'colors'
import path = require('path')
import ts = require('typescript')
import { LanguageService } from './language-service'
import { writeFile } from './file-util'
import { logEmitted, logError } from './logger'
export function generate (filenames: string[], options: ts.CompilerOptions): Promise<never> {
const vueFiles = filenames
.filter(file => /\.vue$/.test(file))
.map(file => path.resolve(file))
// Should not emit if some errors are occurred
const service = new LanguageService(vueFiles, {
...options,
noEmitOnError: true
})
return Promise.all(
vueFiles.map(file => {
const dts = service.getDts(file)
const dtsPath = file + '.d.ts'
if (dts.errors.length > 0) {
logError(dtsPath, dts.errors)
return
}
if (dts.result === null) return
return writeFile(dtsPath, dts.result)
.then(() => {
logEmitted(dtsPath)
})
})
)
}
| import 'colors'
import path = require('path')
import ts = require('typescript')
import { LanguageService } from './language-service'
import { writeFile } from './file-util'
import { logEmitted, logError } from './logger'
export function generate (filenames: string[], options: ts.CompilerOptions): Promise<never> {
const vueFiles = filenames
.filter(file => /\.vue$/.test(file))
.map(file => path.resolve(file))
// Should not emit if some errors are occurred
const service = new LanguageService(vueFiles, {
...options,
declaration: true,
noEmitOnError: true
})
return Promise.all(
vueFiles.map(file => {
const dts = service.getDts(file)
const dtsPath = file + '.d.ts'
if (dts.errors.length > 0) {
logError(dtsPath, dts.errors)
return
}
if (dts.result === null) return
return writeFile(dtsPath, dts.result)
.then(() => {
logEmitted(dtsPath)
})
})
)
}
| Print errors that is specific when declaration: true | Print errors that is specific when declaration: true
| TypeScript | mit | ktsn/vuetype,ktsn/vuetype | ---
+++
@@ -14,6 +14,7 @@
// Should not emit if some errors are occurred
const service = new LanguageService(vueFiles, {
...options,
+ declaration: true,
noEmitOnError: true
})
|
9a783c27e74169e85cc6d1974d0ab09f0c52b80d | code-samples/Angular6/chapter14/ng-auction/client/e2e/search.e2e-spec.ts | code-samples/Angular6/chapter14/ng-auction/client/e2e/search.e2e-spec.ts | import { SearchPage } from './search.po';
import {browser} from 'protractor';
describe('ngAuction search', () => {
let searchPage: SearchPage;
beforeEach(() => {
searchPage = new SearchPage();
});
it('should perform the search for products that cost from $10 to $100', () => {
searchPage.navigateToLandingPage();
let url = browser.getCurrentUrl();
expect(url).toContain('/categories/all');
searchPage.performSearch(10, 100);
url = browser.getCurrentUrl();
expect(url).toContain('/search?minPrice=10&maxPrice=100');
const firstProductPrice = searchPage.getFirstProductPrice();
expect(firstProductPrice).toBeGreaterThan(10);
expect(firstProductPrice).toBeLessThan(100);
});
});
/*
import { SearchPage } from './search.po';
import {browser} from 'protractor';
describe('Landing page', () => {
let searchPage: SearchPage;
beforeEach(() => {
searchPage = new SearchPage();
browser.waitForAngularEnabled(false);
});
it('should navigate to landing page and open the search panel', async () => {
await searchPage.navigateToLanding();
let url = await browser.getCurrentUrl();
console.log('url1: ' + url);
expect(url).toContain('/categories/all');
await searchPage.performSearch();
url = await browser.getCurrentUrl();
console.log('url2: ' + url);
expect(url).toContain('/search');
});
});
*/
| import { SearchPage } from './search.po';
import {browser} from 'protractor';
describe('ngAuction search', () => {
let searchPage: SearchPage;
beforeEach(() => {
searchPage = new SearchPage();
});
it('should perform the search for products that cost from $10 to $100', async () => {
searchPage.navigateToLandingPage();
let url = await browser.getCurrentUrl();
expect(url).toContain('/categories/all');
searchPage.performSearch(10, 100);
url = await browser.getCurrentUrl();
expect(url).toContain('/search?minPrice=10&maxPrice=100');
const firstProductPrice = await searchPage.getFirstProductPrice();
expect(firstProductPrice).toBeGreaterThan(10);
expect(firstProductPrice).toBeLessThan(100);
});
});
/*
import { SearchPage } from './search.po';
import {browser} from 'protractor';
describe('Landing page', () => {
let searchPage: SearchPage;
beforeEach(() => {
searchPage = new SearchPage();
browser.waitForAngularEnabled(false);
});
it('should navigate to landing page and open the search panel', async () => {
await searchPage.navigateToLanding();
let url = await browser.getCurrentUrl();
console.log('url1: ' + url);
expect(url).toContain('/categories/all');
await searchPage.performSearch();
url = await browser.getCurrentUrl();
console.log('url2: ' + url);
expect(url).toContain('/search');
});
});
*/
| Fix e2e test in ch14 | Fix e2e test in ch14
| TypeScript | mit | Farata/angulartypescript,Farata/angulartypescript,Farata/angulartypescript | ---
+++
@@ -8,16 +8,16 @@
searchPage = new SearchPage();
});
- it('should perform the search for products that cost from $10 to $100', () => {
+ it('should perform the search for products that cost from $10 to $100', async () => {
searchPage.navigateToLandingPage();
- let url = browser.getCurrentUrl();
+ let url = await browser.getCurrentUrl();
expect(url).toContain('/categories/all');
searchPage.performSearch(10, 100);
- url = browser.getCurrentUrl();
+ url = await browser.getCurrentUrl();
expect(url).toContain('/search?minPrice=10&maxPrice=100');
- const firstProductPrice = searchPage.getFirstProductPrice();
+ const firstProductPrice = await searchPage.getFirstProductPrice();
expect(firstProductPrice).toBeGreaterThan(10);
expect(firstProductPrice).toBeLessThan(100);
}); |
5617f1bac1cc33055ef4854591a5513858493157 | packages/@sanity/field/src/types/reference/diff/ReferenceFieldDiff.tsx | packages/@sanity/field/src/types/reference/diff/ReferenceFieldDiff.tsx | import React from 'react'
import {DiffComponent, ReferenceDiff} from '../../../diff'
import {Change} from '../../../diff/components'
import {ReferencePreview} from '../preview/ReferencePreview'
export const ReferenceFieldDiff: DiffComponent<ReferenceDiff> = ({diff, schemaType}) => {
return (
<Change
previewComponent={ReferencePreview}
layout={diff.fromValue && diff.toValue ? 'grid' : 'inline'}
path="_ref"
diff={diff}
schemaType={schemaType}
/>
)
}
| import React from 'react'
import {DiffComponent, ReferenceDiff} from '../../../diff'
import {Change} from '../../../diff/components'
import {ReferencePreview} from '../preview/ReferencePreview'
export const ReferenceFieldDiff: DiffComponent<ReferenceDiff> = ({diff, schemaType}) => {
return (
<Change
diff={diff}
layout="grid"
path="_ref"
previewComponent={ReferencePreview}
schemaType={schemaType}
/>
)
}
| Use grid layout for reference changes | [field] Use grid layout for reference changes
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -6,10 +6,10 @@
export const ReferenceFieldDiff: DiffComponent<ReferenceDiff> = ({diff, schemaType}) => {
return (
<Change
+ diff={diff}
+ layout="grid"
+ path="_ref"
previewComponent={ReferencePreview}
- layout={diff.fromValue && diff.toValue ? 'grid' : 'inline'}
- path="_ref"
- diff={diff}
schemaType={schemaType}
/>
) |
60d1d112cfcb958e99369d06eba8aea1148c8444 | src/wrapped_native_key.ts | src/wrapped_native_key.ts |
import { NativeCryptoKey } from "webcrypto-core";
import { CryptoKey } from "./key";
export class WrappedNativeCryptoKey extends CryptoKey {
constructor(
algorithm: KeyAlgorithm,
extractable: boolean,
type: KeyType,
usages: KeyUsage[],
public nativeKey: NativeCryptoKey) {
super(algorithm, extractable, type, usages);
}
}
|
import { NativeCryptoKey } from "webcrypto-core";
import { CryptoKey } from "./key";
export class WrappedNativeCryptoKey extends CryptoKey {
// tslint:disable-next-line: member-access
#nativeKey: CryptoKey;
constructor(
algorithm: KeyAlgorithm,
extractable: boolean,
type: KeyType,
usages: KeyUsage[],
nativeKey: NativeCryptoKey) {
super(algorithm, extractable, type, usages);
this.#nativeKey = nativeKey;
}
// @internal
public getNative() {
return this.#nativeKey;
}
}
| Move nativeKey to private field | chore: Move nativeKey to private field
| TypeScript | mit | PeculiarVentures/webcrypto-liner,PeculiarVentures/webcrypto-liner | ---
+++
@@ -4,13 +4,22 @@
export class WrappedNativeCryptoKey extends CryptoKey {
+ // tslint:disable-next-line: member-access
+ #nativeKey: CryptoKey;
+
constructor(
algorithm: KeyAlgorithm,
extractable: boolean,
type: KeyType,
usages: KeyUsage[],
- public nativeKey: NativeCryptoKey) {
+ nativeKey: NativeCryptoKey) {
super(algorithm, extractable, type, usages);
+ this.#nativeKey = nativeKey;
+ }
+
+ // @internal
+ public getNative() {
+ return this.#nativeKey;
}
} |
816ff80db7d51f79009d67635541bac32451afa1 | src/front-end/js/directory/modules/geocoder.module.ts | src/front-end/js/directory/modules/geocoder.module.ts | declare let google;
import { Event, IEvent } from "../utils/event";
export class GeocoderModule
{
onResult = new Event<any>();
geocodeAddress( address, callbackComplete?, callbackFail? ) {
console.log("geocode address : ", address);
let geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, (results, status) =>
{
if (status == google.maps.GeocoderStatus.OK)
{
if (callbackComplete) callbackComplete(results);
console.log("geocode result", results);
let zoom = this.calculateAppropriateZoomForResults(results[0]);
this.onResult.emit({location : results[0].geometry.location, zoom : zoom});
}
else
{
if (callbackFail) callbackFail();
}
});
};
calculateAppropriateZoomForResults( result) {
// TODO
return 12;
};
} | declare let GeocoderJS;
declare let App : AppModule;
declare var L;
import { AppModule } from "../app.module";
import { Event, IEvent } from "../utils/event";
export class GeocodeResult
{
}
export class GeocoderModule
{
onResult = new Event<any>();
geocoder : any = null;
geocoderOSM : any = null;
constructor()
{
this.geocoder = GeocoderJS.createGeocoder('openstreetmap');
//this.geocoder = GeocoderJS.createGeocoder({'provider': 'google'});
}
geocodeAddress( address, callbackComplete?, callbackFail? ) {
console.log("geocode address : ", address);
this.geocoder.geocode( address, (results) =>
{
if (results !== null)
{
if (callbackComplete) callbackComplete(results[0]);
var corner1 = L.latLng(results[0].bounds[0], results[0].bounds[1]),
corner2 = L.latLng(results[0].bounds[2], results[0].bounds[3]),
bounds = L.latLngBounds(corner1, corner2);
setTimeout( () => { console.log("fitbounds OSM", bounds); App.map().fitBounds(bounds);}, 500);
//this.onResult.emit(results[0]);
}
else
{
if (callbackFail) callbackFail();
}
});
};
} | Change google geocoder to geocoder-js | Change google geocoder to geocoder-js | TypeScript | mit | Biopenlandes/PagesVertes,Biopenlandes/PagesVertes,Biopenlandes/PagesVertes | ---
+++
@@ -1,25 +1,44 @@
-declare let google;
+declare let GeocoderJS;
+declare let App : AppModule;
+declare var L;
+import { AppModule } from "../app.module";
import { Event, IEvent } from "../utils/event";
+
+export class GeocodeResult
+{
+
+}
export class GeocoderModule
{
onResult = new Event<any>();
+ geocoder : any = null;
+ geocoderOSM : any = null;
+
+ constructor()
+ {
+ this.geocoder = GeocoderJS.createGeocoder('openstreetmap');
+ //this.geocoder = GeocoderJS.createGeocoder({'provider': 'google'});
+ }
geocodeAddress( address, callbackComplete?, callbackFail? ) {
console.log("geocode address : ", address);
- let geocoder = new google.maps.Geocoder();
- geocoder.geocode( { 'address': address}, (results, status) =>
- {
- if (status == google.maps.GeocoderStatus.OK)
+ this.geocoder.geocode( address, (results) =>
+ {
+ if (results !== null)
{
- if (callbackComplete) callbackComplete(results);
- console.log("geocode result", results);
-
- let zoom = this.calculateAppropriateZoomForResults(results[0]);
- this.onResult.emit({location : results[0].geometry.location, zoom : zoom});
+ if (callbackComplete) callbackComplete(results[0]);
+
+ var corner1 = L.latLng(results[0].bounds[0], results[0].bounds[1]),
+ corner2 = L.latLng(results[0].bounds[2], results[0].bounds[3]),
+ bounds = L.latLngBounds(corner1, corner2);
+
+ setTimeout( () => { console.log("fitbounds OSM", bounds); App.map().fitBounds(bounds);}, 500);
+
+ //this.onResult.emit(results[0]);
}
else
{
@@ -28,9 +47,5 @@
});
};
- calculateAppropriateZoomForResults( result) {
- // TODO
- return 12;
- };
} |
5a32a070c4ea6852d40fcdb55afa78cd7f0fa1ff | examples/react-babel-allowjs/src/main.tsx | examples/react-babel-allowjs/src/main.tsx | import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
ReactDOM.render(
<App />,
document.getElementById('appContainer')
);
console.log(App) | import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
function getContainer (id: string) {
return document.getElementById(id)
}
ReactDOM.render(
<App />,
getContainer('appContainer')
); | Update example to actually include some typed code | Update example to actually include some typed code
| TypeScript | mit | TypeStrong/ts-loader,jbrantly/ts-loader,jbrantly/ts-loader,jbrantly/ts-loader,TypeStrong/ts-loader | ---
+++
@@ -2,8 +2,11 @@
import ReactDOM from 'react-dom';
import App from './app.js';
+function getContainer (id: string) {
+ return document.getElementById(id)
+}
+
ReactDOM.render(
<App />,
- document.getElementById('appContainer')
+ getContainer('appContainer')
);
-console.log(App) |
83e3632b527bd5bf7451e7c29257cef702b2fe9b | demo/app/color-selector/color-selector-demo.ts | demo/app/color-selector/color-selector-demo.ts | /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component } from '@angular/core';
import { Color } from '../../../src/common/core/graphics/color';
import { ColorEvent } from '../../../src/common/core/graphics/color-event';
import { MaterialColors } from '../../../src/common/core/style/material-colors';
@Component({
selector: 'deja-color-selector-demo',
styleUrls: ['./color-selector-demo.scss'],
templateUrl: './color-selector-demo.html',
})
export class DejaColorSelectorDemoComponent {
public tabIndex = 1;
protected selectedColor = Color.fromHex('#FFA000');
protected invalidColor = Color.fromHex('#FFA012');
private hoveredColor: Color;
constructor(protected materialColors: MaterialColors) { }
protected onColorPickerHover(event: ColorEvent) {
this.hoveredColor = event.color;
}
protected onColorPickerChange(event: ColorEvent) {
this.hoveredColor = event.color;
}
}
| /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component } from '@angular/core';
import { Color } from '../../../src/common/core/graphics/color';
import { ColorEvent } from '../../../src/common/core/graphics/color-event';
import { MaterialColors } from '../../../src/common/core/style/material-colors';
@Component({
selector: 'deja-color-selector-demo',
styleUrls: ['./color-selector-demo.scss'],
templateUrl: './color-selector-demo.html',
})
export class DejaColorSelectorDemoComponent {
public tabIndex = 1;
protected selectedColor = Color.fromHex('#25C337');
protected invalidColor = Color.fromHex('#D02D06');
private hoveredColor: Color;
constructor(protected materialColors: MaterialColors) { }
protected onColorPickerHover(event: ColorEvent) {
this.hoveredColor = event.color;
}
protected onColorPickerChange(event: ColorEvent) {
this.hoveredColor = event.color;
}
}
| Change colors to see a problem more quickly | quiet(DejaColorSelector): Change colors to see a problem more quickly
| TypeScript | apache-2.0 | DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components,DSI-HUG/dejajs-components | ---
+++
@@ -19,8 +19,8 @@
export class DejaColorSelectorDemoComponent {
public tabIndex = 1;
- protected selectedColor = Color.fromHex('#FFA000');
- protected invalidColor = Color.fromHex('#FFA012');
+ protected selectedColor = Color.fromHex('#25C337');
+ protected invalidColor = Color.fromHex('#D02D06');
private hoveredColor: Color;
constructor(protected materialColors: MaterialColors) { } |
8a3efe03b8e6a84005e24d88450cb8eb8ee320d9 | jSlider/JSliderOptions.ts | jSlider/JSliderOptions.ts | module jSlider {
export class JSliderOptions {
private static _defaults = {
"delay" : 4000, //Delay between each slide
"duration" : 200, //The duration of the slide animation
"button" : {}
};
private options : Object = {
"delay" : null,
"duration" : null,
"button" : {
"next" : null,
"prev" : null,
"stop" : null,
"start" : null
},
"on" : {
"slide" : null,
"next" : null,
"prev" : null,
"start" : null,
"stop" : null
}
};
constructor(options : Object = {}) {
var option : string;
for (option in this.options) {
if (!this.options.hasOwnProperty(option)) continue;
this.options[option] = options[option] || JSliderOptions._defaults[option] || null;
}
//Change event listeners to [function(){}] if function(){}
var eventListeners = this.options['on'];
var key : string;
for (key in eventListeners) {
if (!eventListeners.hasOwnProperty(key)) continue;
if (typeof eventListeners[key] === 'function') {
eventListeners[key] = Array(eventListeners[key]);
}
}
}
/**
* Get an option
* @param optionName
* @returns {string}
*/
public get(optionName : string) : any {
return this.options[optionName];
}
}
} | module jSlider {
export class JSliderOptions {
private options : Object = {
"delay" : 4000,
"duration" : 200,
"button" : {
"next" : null,
"prev" : null,
"stop" : null,
"start" : null
},
"on" : {
"slide" : [],
"next" : [],
"prev" : [],
"start" : [],
"stop" : []
}
};
constructor(options : Object = {}) {
var option : string;
for (option in this.options) {
if (!this.options.hasOwnProperty(option)) continue;
this.options[option] = options[option] || this.options[option];
}
//Change event listeners to [function(){}] if function(){}
var eventListeners = this.options['on'];
var key : string;
for (key in eventListeners) {
if (!eventListeners.hasOwnProperty(key)) continue;
if (typeof eventListeners[key] === 'function') {
this.options['on'][key] = Array(eventListeners[key]);
}
}
}
/**
* Get an option
* @param optionName
* @returns {string}
*/
public get(optionName : string) : any {
return this.options[optionName];
}
}
} | Remove the ever so poinless _defaults object, and fix the event object | Remove the ever so poinless _defaults object, and fix the event object
| TypeScript | lgpl-2.1 | sigurdsvela/JSlider | ---
+++
@@ -1,14 +1,8 @@
module jSlider {
export class JSliderOptions {
- private static _defaults = {
- "delay" : 4000, //Delay between each slide
- "duration" : 200, //The duration of the slide animation
- "button" : {}
- };
-
private options : Object = {
- "delay" : null,
- "duration" : null,
+ "delay" : 4000,
+ "duration" : 200,
"button" : {
"next" : null,
"prev" : null,
@@ -16,11 +10,11 @@
"start" : null
},
"on" : {
- "slide" : null,
- "next" : null,
- "prev" : null,
- "start" : null,
- "stop" : null
+ "slide" : [],
+ "next" : [],
+ "prev" : [],
+ "start" : [],
+ "stop" : []
}
};
@@ -28,7 +22,7 @@
var option : string;
for (option in this.options) {
if (!this.options.hasOwnProperty(option)) continue;
- this.options[option] = options[option] || JSliderOptions._defaults[option] || null;
+ this.options[option] = options[option] || this.options[option];
}
//Change event listeners to [function(){}] if function(){}
@@ -37,7 +31,7 @@
for (key in eventListeners) {
if (!eventListeners.hasOwnProperty(key)) continue;
if (typeof eventListeners[key] === 'function') {
- eventListeners[key] = Array(eventListeners[key]);
+ this.options['on'][key] = Array(eventListeners[key]);
}
}
} |
3f280d297b548c6108602d1f4069808c8aafe9fa | knockoutapp/app/services/utils.ts | knockoutapp/app/services/utils.ts | /**
* Created by rtorres on 9/25/16.
*/
export function getCookie(cname: string): string {
let name: string = cname + '=';
let ca: string[] = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
let c: any = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return null;
} | /**
* Created by rtorres on 9/25/16.
*/
import * as Cookies from 'js-cookie';
export function getCookie(cname: string): string {
return Cookies.get(cname);
} | Use js-cookies to get cookie | Use js-cookies to get cookie
| TypeScript | mit | rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel | ---
+++
@@ -1,19 +1,8 @@
/**
* Created by rtorres on 9/25/16.
*/
-
+import * as Cookies from 'js-cookie';
export function getCookie(cname: string): string {
- let name: string = cname + '=';
- let ca: string[] = document.cookie.split(';');
- for(var i = 0; i <ca.length; i++) {
- let c: any = ca[i];
- while (c.charAt(0)==' ') {
- c = c.substring(1);
- }
- if (c.indexOf(name) == 0) {
- return c.substring(name.length,c.length);
- }
- }
- return null;
+ return Cookies.get(cname);
} |
0d502b78d4916fe983aba6bee0be66b55951a62f | applications/drive/src/app/components/sections/SharedLinks/ContextMenuButtons/StopSharingButton.tsx | applications/drive/src/app/components/sections/SharedLinks/ContextMenuButtons/StopSharingButton.tsx | import { c } from 'ttag';
import useToolbarActions from '../../../../hooks/drive/useActions';
import { FileBrowserItem } from '../../../FileBrowser';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
shareId: string;
items: FileBrowserItem[];
close: () => void;
}
const StopSharingButton = ({ shareId, items, close }: Props) => {
const { openStopSharing } = useToolbarActions();
return (
<ContextMenuButton
name={c('Action').t`Stop sharing`}
icon="broken-link"
testId="context-menu-stop-sharing"
action={() => openStopSharing(shareId, items)}
close={close}
/>
);
};
export default StopSharingButton;
| import { c } from 'ttag';
import useToolbarActions from '../../../../hooks/drive/useActions';
import { FileBrowserItem } from '../../../FileBrowser';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
shareId: string;
items: FileBrowserItem[];
close: () => void;
}
const StopSharingButton = ({ shareId, items, close }: Props) => {
const { openStopSharing } = useToolbarActions();
return (
<ContextMenuButton
name={c('Action').t`Stop sharing`}
icon="link-broken"
testId="context-menu-stop-sharing"
action={() => openStopSharing(shareId, items)}
close={close}
/>
);
};
export default StopSharingButton;
| Fix icon name for stop sharing context menu | Fix icon name for stop sharing context menu | TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -16,7 +16,7 @@
return (
<ContextMenuButton
name={c('Action').t`Stop sharing`}
- icon="broken-link"
+ icon="link-broken"
testId="context-menu-stop-sharing"
action={() => openStopSharing(shareId, items)}
close={close} |
b732c0ce444728b4d0f2386f34784741414d921d | packages/@glimmer/component/addon/-private/base-component-manager.ts | packages/@glimmer/component/addon/-private/base-component-manager.ts | import { DEBUG } from '@glimmer/env';
import { ComponentManager, ComponentCapabilities, TemplateArgs } from '@glimmer/core';
import BaseComponent, { ARGS_SET } from './component';
export interface Constructor<T> {
new (owner: unknown, args: Record<string, unknown>): T;
}
export default abstract class BaseComponentManager<GlimmerComponent extends BaseComponent>
implements ComponentManager<GlimmerComponent> {
abstract capabilities: ComponentCapabilities;
private owner: unknown;
constructor(owner: unknown) {
this.owner = owner;
}
createComponent(
ComponentClass: Constructor<GlimmerComponent>,
args: TemplateArgs
): GlimmerComponent {
if (DEBUG) {
ARGS_SET.set(args.named, true);
}
return new ComponentClass(this.owner, args.named);
}
getContext(component: GlimmerComponent): GlimmerComponent {
return component;
}
}
| import { DEBUG } from '@glimmer/env';
import { ComponentManager, ComponentCapabilities } from '@glimmer/core';
import { Arguments } from '@glimmer/interfaces';
import BaseComponent, { ARGS_SET } from './component';
export interface Constructor<T> {
new (owner: unknown, args: Record<string, unknown>): T;
}
export default abstract class BaseComponentManager<GlimmerComponent extends BaseComponent>
implements ComponentManager<GlimmerComponent> {
abstract capabilities: ComponentCapabilities;
private owner: unknown;
constructor(owner: unknown) {
this.owner = owner;
}
createComponent(
ComponentClass: Constructor<GlimmerComponent>,
args: Arguments
): GlimmerComponent {
if (DEBUG) {
ARGS_SET.set(args.named, true);
}
return new ComponentClass(this.owner, args.named);
}
getContext(component: GlimmerComponent): GlimmerComponent {
return component;
}
}
| Fix type errors on canary | Fix type errors on canary
| TypeScript | mit | glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js | ---
+++
@@ -1,5 +1,6 @@
import { DEBUG } from '@glimmer/env';
-import { ComponentManager, ComponentCapabilities, TemplateArgs } from '@glimmer/core';
+import { ComponentManager, ComponentCapabilities } from '@glimmer/core';
+import { Arguments } from '@glimmer/interfaces';
import BaseComponent, { ARGS_SET } from './component';
export interface Constructor<T> {
@@ -18,7 +19,7 @@
createComponent(
ComponentClass: Constructor<GlimmerComponent>,
- args: TemplateArgs
+ args: Arguments
): GlimmerComponent {
if (DEBUG) {
ARGS_SET.set(args.named, true); |
438a578cfb20b3debdeec7ca762731db8b60033a | src/tests/definitions/interface/interfaceWriteTests.ts | src/tests/definitions/interface/interfaceWriteTests.ts | import * as assert from "assert";
import {getInfoFromString} from "./../../../main";
const code =
`interface MyInterface {
myString: string;
mySecond: number;
myMethod(): void;
myMethodWithTypeParameter<T>(): void;
myMethod2<T>(): string;
myMethod2<T>(str?: string): string;
}
interface NewSignatureInterface {
new<T>(str: string, t: T): string;
new(any: any): string;
}
interface CallSignatureInterface {
<T>(str: string, t: T): string;
(num: number): number;
(any: any): any;
}
interface IndexSignatureInterface {
[str: string]: Date;
[num: number]: Date;
}
interface MyTypeParameterInterface<T> {
}
interface MyExtenedInterface extends MyTypeParameterInterface<string> {
}
interface MyMultipleExtenedInterface extends MyTypeParameterInterface<string>, MyInterface {
}
`;
describe("InterfaceDefinition", () => {
const file = getInfoFromString(code);
describe("write()", () => {
it("should have the same output as the input", () => {
assert.equal(file.write(), code);
});
});
});
| import * as assert from "assert";
import {getInfoFromString} from "./../../../main";
const code =
`interface SimpleInterface {
}
interface MyInterface {
myString: string;
mySecond: number;
myMethod(): void;
myMethodWithTypeParameter<T>(): void;
myMethod2<T>(): string;
myMethod2<T>(str?: string): string;
}
interface NewSignatureInterface {
new<T>(str: string, t: T): string;
new(any: any): string;
}
interface CallSignatureInterface {
<T>(str: string, t: T): string;
(num: number): number;
(any: any): any;
}
interface IndexSignatureInterface {
[str: string]: Date;
[num: number]: Date;
}
interface MyTypeParameterInterface<T> {
}
interface MyExtenedInterface extends MyTypeParameterInterface<string> {
}
interface MyMultipleExtenedInterface extends MyTypeParameterInterface<string>, MyInterface {
}
`;
describe("InterfaceDefinition", () => {
const file = getInfoFromString(code);
describe("write()", () => {
it("should have the same output as the input", () => {
assert.equal(file.write(), code);
});
it("should write when calling it on the interface", () => {
const expectedCode =
`interface SimpleInterface {
}
`;
assert.equal(file.interfaces[0].write(), expectedCode);
});
});
});
| Add tests for InterfaceDefinition -> write. | Add tests for InterfaceDefinition -> write.
| TypeScript | mit | dsherret/ts-type-info,dsherret/type-info-ts,dsherret/ts-type-info,dsherret/type-info-ts | ---
+++
@@ -2,7 +2,10 @@
import {getInfoFromString} from "./../../../main";
const code =
-`interface MyInterface {
+`interface SimpleInterface {
+}
+
+interface MyInterface {
myString: string;
mySecond: number;
@@ -45,5 +48,13 @@
it("should have the same output as the input", () => {
assert.equal(file.write(), code);
});
+
+ it("should write when calling it on the interface", () => {
+ const expectedCode =
+`interface SimpleInterface {
+}
+`;
+ assert.equal(file.interfaces[0].write(), expectedCode);
+ });
});
}); |
7dd4f72ed23bf2d0806f192614225e8b09a473e4 | extraterm/src/render_process/settings/extensions/ExtensionSettingsUi.ts | extraterm/src/render_process/settings/extensions/ExtensionSettingsUi.ts | /*
* Copyright 2020 Simon Edwards <[email protected]>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import Component from 'vue-class-component';
import Vue from 'vue';
import { } from '../../../Config';
import { trimBetweenTags } from 'extraterm-trim-between-tags';
import { ExtensionMetadata } from 'extraterm/src/ExtensionMetadata';
@Component(
{
template: trimBetweenTags(`
<div class="settings-page">
<h2><i class="fas fa-puzzle-piece"></i> Extensions</h2>
<div v-for="extension in allExtensions" v-bind:key="extension.path" class="card">
<h3>{{ extension.displayName || extension.name }} <span class="extension-version">{{ extension.version }}</span></h3>
<div>{{ extension.description}}</div>
</div>
</div>
`)
}
)
export class ExtensionSettingsUi extends Vue {
allExtensions: ExtensionMetadata[];
constructor() {
super();
this.allExtensions = [];
}
}
| /*
* Copyright 2020 Simon Edwards <[email protected]>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import Component from 'vue-class-component';
import Vue from 'vue';
import { } from '../../../Config';
import { trimBetweenTags } from 'extraterm-trim-between-tags';
import { ExtensionMetadata } from 'extraterm/src/ExtensionMetadata';
import { isSupportedOnThisPlatform } from '../../extension/InternalTypes';
@Component(
{
template: trimBetweenTags(`
<div class="settings-page">
<h2><i class="fas fa-puzzle-piece"></i> Extensions</h2>
<div v-for="extension in allUserExtensions" v-bind:key="extension.path" class="card">
<h3>{{ extension.displayName || extension.name }} <span class="extension-version">{{ extension.version }}</span></h3>
<div>{{ extension.description}}</div>
</div>
</div>
`)
}
)
export class ExtensionSettingsUi extends Vue {
allExtensions: ExtensionMetadata[];
constructor() {
super();
this.allExtensions = [];
}
get allUserExtensions(): ExtensionMetadata[] {
return this.allExtensions.filter(ex => ! ex.isInternal && isSupportedOnThisPlatform(ex));
}
}
| Hide internal extensions from the settings page | Hide internal extensions from the settings page
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -9,6 +9,7 @@
import { } from '../../../Config';
import { trimBetweenTags } from 'extraterm-trim-between-tags';
import { ExtensionMetadata } from 'extraterm/src/ExtensionMetadata';
+import { isSupportedOnThisPlatform } from '../../extension/InternalTypes';
@Component(
@@ -17,7 +18,7 @@
<div class="settings-page">
<h2><i class="fas fa-puzzle-piece"></i> Extensions</h2>
- <div v-for="extension in allExtensions" v-bind:key="extension.path" class="card">
+ <div v-for="extension in allUserExtensions" v-bind:key="extension.path" class="card">
<h3>{{ extension.displayName || extension.name }} <span class="extension-version">{{ extension.version }}</span></h3>
<div>{{ extension.description}}</div>
</div>
@@ -33,4 +34,8 @@
super();
this.allExtensions = [];
}
+
+ get allUserExtensions(): ExtensionMetadata[] {
+ return this.allExtensions.filter(ex => ! ex.isInternal && isSupportedOnThisPlatform(ex));
+ }
} |
12e888b4668a250e00f9a30ed8d5856d0f76c66b | components/captcha.ts | components/captcha.ts | import {
Component,
OnInit,
Input,
Output,
EventEmitter,
NgZone} from '@angular/core';
@Component({
selector: 're-captcha',
template: '<div class="g-recaptcha" [attr.data-sitekey]="site_key" data-callback="verifyCallback"></div>'
})
/*Captcha functionality component*/
export class ReCaptchaComponent implements OnInit {
@Input()
site_key:string = null;
@Output()
captchaResponse:EventEmitter<string>;
constructor(private _zone: NgZone) {
window['verifyCallback'] = (response: any) => this._zone.run(this.recaptchaCallback.bind(this, response));
this.captchaResponse = new EventEmitter<string>();
}
recaptchaCallback(response) {
this.captchaResponse.emit(response);
}
ngOnInit() {
var doc = <HTMLDivElement> document.body;
var script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js';
script.async = true;
script.defer = true;
doc.appendChild(script);
}
}
| import {
Component,
OnInit,
Input,
Output,
EventEmitter,
NgZone} from '@angular/core';
@Component({
selector: 're-captcha',
template: '<div class="g-recaptcha" [attr.data-sitekey]="site_key" data-callback="verifyCallback"></div>'
})
export class ReCaptchaComponent implements OnInit {
@Input()
site_key: string = null;
/* Available languages: https://developers.google.com/recaptcha/docs/language */
@Input()
language: string = null;
@Output()
captchaResponse: EventEmitter<string>;
constructor(private _zone: NgZone) {
window['verifyCallback'] = (response: any) => this._zone.run(this.recaptchaCallback.bind(this, response));
this.captchaResponse = new EventEmitter<string>();
}
recaptchaCallback(response) {
this.captchaResponse.emit(response);
}
ngOnInit() {
var doc = <HTMLDivElement> document.body;
var script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://www.google.com/recaptcha/api.js' + (this.language ? '?hl=' + this.language : '');
script.async = true;
script.defer = true;
doc.appendChild(script);
}
}
| Support user interface language input parameter | Support user interface language input parameter | TypeScript | isc | xmaestro/angular2-recaptcha | ---
+++
@@ -11,14 +11,16 @@
template: '<div class="g-recaptcha" [attr.data-sitekey]="site_key" data-callback="verifyCallback"></div>'
})
-/*Captcha functionality component*/
export class ReCaptchaComponent implements OnInit {
@Input()
- site_key:string = null;
+ site_key: string = null;
+ /* Available languages: https://developers.google.com/recaptcha/docs/language */
+ @Input()
+ language: string = null;
@Output()
- captchaResponse:EventEmitter<string>;
+ captchaResponse: EventEmitter<string>;
constructor(private _zone: NgZone) {
window['verifyCallback'] = (response: any) => this._zone.run(this.recaptchaCallback.bind(this, response));
@@ -33,7 +35,7 @@
var doc = <HTMLDivElement> document.body;
var script = document.createElement('script');
script.innerHTML = '';
- script.src = 'https://www.google.com/recaptcha/api.js';
+ script.src = 'https://www.google.com/recaptcha/api.js' + (this.language ? '?hl=' + this.language : '');
script.async = true;
script.defer = true;
doc.appendChild(script); |
5f4c1e977c92268f9e3a01e2560f06e6f29e9024 | src/app/map/suitability-map-panel/suitability-map-panel.component.spec.ts | src/app/map/suitability-map-panel/suitability-map-panel.component.spec.ts | /* tslint:disable:no-unused-variable */
/*!
* Suitability Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { provideStore } from '@ngrx/store';
import { LeafletMapService } from '../../leaflet';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapLayersReducer, SuitabilityLevelsReducer } from '../../store';
import { MockRouter } from '../../mocks/router';
import { MockSuitabilityMapService } from '../../mocks/map';
import { SuitabilityMapPanelComponent } from './suitability-map-panel.component';
describe('Component: SuitabilityMapPanel', () => {
let mockRouter: MockRouter;
beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
SuitabilityMapPanelComponent,
{ provide: SuitabilityMapService, useClass: MockSuitabilityMapService }
{ provide: Router, useValue: mockRouter },
provideStore({
mapLayers: MapLayersReducer,
suitabilityLevels: SuitabilityLevelsReducer
})
]
});
});
it('should create an instance', inject([SuitabilityMapPanelComponent], (component: SuitabilityMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Suitability Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <[email protected]>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { provideStore } from '@ngrx/store';
import { LeafletMapService } from '../../leaflet';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapLayersReducer, SuitabilityLevelsReducer } from '../../store';
import { MockRouter } from '../../mocks/router';
import { MockSuitabilityMapService } from '../../mocks/map';
import { SuitabilityMapPanelComponent } from './suitability-map-panel.component';
describe('Component: SuitabilityMapPanel', () => {
let mockRouter: MockRouter;
beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
SuitabilityMapPanelComponent,
{ provide: SuitabilityMapService, useClass: MockSuitabilityMapService },
{ provide: Router, useValue: mockRouter },
provideStore({
mapLayers: MapLayersReducer,
suitabilityLevels: SuitabilityLevelsReducer
})
]
});
});
it('should create an instance', inject([SuitabilityMapPanelComponent], (component: SuitabilityMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
| Fix syntax error due to missing comma | Fix syntax error due to missing comma
| TypeScript | mit | ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps | ---
+++
@@ -30,7 +30,7 @@
LeafletMapService,
SuitabilityMapPanelComponent,
- { provide: SuitabilityMapService, useClass: MockSuitabilityMapService }
+ { provide: SuitabilityMapService, useClass: MockSuitabilityMapService },
{ provide: Router, useValue: mockRouter },
provideStore({ |
3113a24cf7e9ff34a03977b90cadcd544369ff0a | src/charts/ParallelCoordinates.ts | src/charts/ParallelCoordinates.ts | import Chart from './Chart';
import SvgStrategyParallelCoordinates from '../svg/strategies/SvgStrategyParallelCoordinates';
import { defaults } from '../utils/defaults/parallelCoordinates';
import { copy, isValuesInObjectKeys } from '../utils/functions';
class ParallelCoordinates extends Chart {
constructor(data: any, userConfig: any = {}) {
super(
SvgStrategyParallelCoordinates,
data,
userConfig,
defaults
);
}
public keepDrawing(datum: any) {
let pause: boolean = this.config.get('pause');
this.data = datum;
if (pause) {
this.pauseDrawing();
} else {
if (this.storedData.length > 0) { // resume
this.resumeDrawing();
} else {
this.streamDrawing();
}
}
}
}
export default ParallelCoordinates;
| import Chart from './Chart';
import SvgStrategyParallelCoordinates from '../svg/strategies/SvgStrategyParallelCoordinates';
import { defaults } from '../utils/defaults/parallelCoordinates';
import { copy, isValuesInObjectKeys } from '../utils/functions';
class ParallelCoordinates extends Chart {
constructor(data: any, userConfig: any = {}) {
super(
SvgStrategyParallelCoordinates,
data,
userConfig,
defaults
);
}
public keepDrawing(datum: any) {
let pause: boolean = this.config.get('pause');
if (!Array.isArray(datum)) {
this.data = [datum];
} else {
this.data = datum;
}
if (pause) {
this.pauseDrawing();
} else {
if (this.storedData.length > 0) { // resume
this.resumeDrawing();
} else {
this.streamDrawing();
}
}
}
}
export default ParallelCoordinates;
| Add data type check whether array or not in Parallel Coordinates | Add data type check whether array or not in Parallel Coordinates
| TypeScript | apache-2.0 | proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic | ---
+++
@@ -16,8 +16,12 @@
public keepDrawing(datum: any) {
let pause: boolean = this.config.get('pause');
-
- this.data = datum;
+
+ if (!Array.isArray(datum)) {
+ this.data = [datum];
+ } else {
+ this.data = datum;
+ }
if (pause) {
this.pauseDrawing(); |
aff211820893c81d0768931ea2b9d9592919dc85 | src/models/requestParserFactory.ts | src/models/requestParserFactory.ts | "use strict";
import { IRequestParser } from '../models/IRequestParser';
import { CurlRequestParser } from '../utils/curlRequestParser';
import { HttpRequestParser } from '../utils/httpRequestParser';
export interface IRequestParserFactory {
createRequestParser(rawHttpRequest: string);
}
export class RequestParserFactory implements IRequestParserFactory {
public createRequestParser(rawHttpRequest: string): IRequestParser {
if (rawHttpRequest.trim().toLowerCase().startsWith('curl'.toLowerCase())) {
return new CurlRequestParser();
} else {
return new HttpRequestParser();
}
}
} | "use strict";
import { IRequestParser } from '../models/IRequestParser';
import { CurlRequestParser } from '../utils/curlRequestParser';
import { HttpRequestParser } from '../utils/httpRequestParser';
export interface IRequestParserFactory {
createRequestParser(rawHttpRequest: string);
}
export class RequestParserFactory implements IRequestParserFactory {
private static readonly curlRegex: RegExp = /^\s*curl/i;
public createRequestParser(rawHttpRequest: string): IRequestParser {
if (RequestParserFactory.curlRegex.test(rawHttpRequest)) {
return new CurlRequestParser();
} else {
return new HttpRequestParser();
}
}
} | Update the way to check curl request | Update the way to check curl request
| TypeScript | mit | Huachao/vscode-restclient,Huachao/vscode-restclient | ---
+++
@@ -9,8 +9,11 @@
}
export class RequestParserFactory implements IRequestParserFactory {
+
+ private static readonly curlRegex: RegExp = /^\s*curl/i;
+
public createRequestParser(rawHttpRequest: string): IRequestParser {
- if (rawHttpRequest.trim().toLowerCase().startsWith('curl'.toLowerCase())) {
+ if (RequestParserFactory.curlRegex.test(rawHttpRequest)) {
return new CurlRequestParser();
} else {
return new HttpRequestParser(); |
9baa8767b7f2069131b577eca2a0eedb61adf58a | src/reactors/make-upload-button.ts | src/reactors/make-upload-button.ts | import { fileSize } from "../format/filesize";
import platformData from "../constants/platform-data";
import { DateTimeField, toDateTimeField } from "../db/datetime-field";
import { IUpload, ILocalizedString, IModalButtonTag } from "../types";
interface IUploadButton {
label: ILocalizedString;
tags: IModalButtonTag[];
icon: string;
timeAgo: {
date: DateTimeField;
};
}
interface IMakeUploadButtonOpts {
/** Whether to show the size of uploads (default: true) */
showSize?: boolean;
}
export default function makeUploadButton(
upload: IUpload,
opts = { showSize: true } as IMakeUploadButtonOpts
): IUploadButton {
let label = `${upload.displayName || upload.filename}`;
let tags: IModalButtonTag[] = [];
if (upload.size > 0 && opts.showSize) {
tags.push({
label: `${fileSize(upload.size)}`,
});
}
if (upload.demo) {
tags.push({
label: ["pick_update_upload.tags.demo"],
});
}
if (upload.type === "html") {
tags.push({
icon: "earth",
});
}
for (const prop of Object.keys(platformData)) {
if ((upload as any)[prop]) {
tags.push({
icon: platformData[prop].icon,
});
}
}
const timeAgo = {
date: toDateTimeField(upload.updatedAt),
};
const icon = "download";
return { label, tags, icon, timeAgo };
}
| import { fileSize } from "../format/filesize";
import platformData from "../constants/platform-data";
import { DateTimeField, toDateTimeField } from "../db/datetime-field";
import { IUpload, ILocalizedString, IModalButtonTag } from "../types";
interface IUploadButton {
label: ILocalizedString;
tags: IModalButtonTag[];
icon: string;
timeAgo: {
date: DateTimeField;
};
}
interface IMakeUploadButtonOpts {
/** Whether to show the size of uploads (default: true) */
showSize?: boolean;
}
export default function makeUploadButton(
upload: IUpload,
opts = { showSize: true } as IMakeUploadButtonOpts
): IUploadButton {
let label = `${upload.displayName || upload.filename}`;
let tags: IModalButtonTag[] = [];
if (upload.size > 0 && opts.showSize) {
tags.push({
label: `${fileSize(upload.size)}`,
});
}
if (upload.demo) {
tags.push({
label: ["pick_update_upload.tags.demo"],
});
}
if (upload.type === "html") {
tags.push({
icon: "html5",
});
}
for (const prop of Object.keys(platformData)) {
if ((upload as any)[prop]) {
tags.push({
icon: platformData[prop].icon,
});
}
}
const timeAgo = {
date: toDateTimeField(upload.updatedAt),
};
const icon = "download";
return { label, tags, icon, timeAgo };
}
| Use html5 icon instead of earth icon for html5 uploads | Use html5 icon instead of earth icon for html5 uploads
| TypeScript | mit | itchio/itchio-app,itchio/itch,itchio/itch,itchio/itch,leafo/itchio-app,leafo/itchio-app,itchio/itchio-app,itchio/itch,leafo/itchio-app,itchio/itch,itchio/itch,itchio/itchio-app | ---
+++
@@ -40,7 +40,7 @@
if (upload.type === "html") {
tags.push({
- icon: "earth",
+ icon: "html5",
});
}
|
f66f5fcc6d74ebc2b4100afe35f69cac04f19376 | src/datasets/types.ts | src/datasets/types.ts | import { DataCube } from 'src/models/data-cube/data-cube.model';
export interface Dataset {
metas: Array<Meta>;
dataCube: DataCube;
}
export type Meta = TabbedChartsMeta | ChartMeta;
export interface ComponentMeta<T extends string> {
type: T;
title: string;
}
export interface DataComponentMeta<T extends string, QueryT> extends ComponentMeta<T> {
query: QueryT;
}
export interface ContainerComponentMeta<T extends string, MetaT> extends ComponentMeta<T> {
metas: MetaT;
}
export type TabbedChartsMeta = ContainerComponentMeta<'tabbed', ChartMeta[]>;
export type ChartMeta = LineChartMeta;
export interface XYChartMeta<T extends string, QueryT> extends DataComponentMeta<T, QueryT> {
xlabel?: string;
ylabel?: string;
}
export interface XYPoint<T, U> {
x: T;
y: U;
}
export type XYChartData = LineChartData;
export type LineChartMeta = XYChartMeta<'line', LineChartQuery>;
export type LineChartQuery = (options: LineChartQueryOptions) => LineChartData[];
export interface LineChartQueryOptions {
range: [Date, Date];
}
export interface LineChartData {
points: XYPoint<Date, number>[];
legend?: string;
style?: LineChartStyle;
}
export interface LineChartStyle {
color: string;
width: number;
opacity: number;
dashes: number[];
}
| import { DataCube } from 'src/models/data-cube/data-cube.model';
export interface Dataset {
metas: Array<Meta>;
dataCube: DataCube;
}
export type Meta = TabbedChartsMeta | ChartMeta;
export interface ComponentMeta<T extends string> {
type: T;
title: string;
}
export interface DataComponentMeta<T extends string, QueryT> extends ComponentMeta<T> {
query: QueryT;
}
export interface TabbedChartsMeta extends ComponentMeta<'tabbed'> {
metas: ChartMeta[];
}
export type ChartMeta = LineChartMeta;
export interface XYChartMeta<T extends string, QueryT> extends DataComponentMeta<T, QueryT> {
xlabel?: string;
ylabel?: string;
}
export interface XYPoint<T, U> {
x: T;
y: U;
}
export type XYChartData = LineChartData;
export type LineChartMeta = XYChartMeta<'line', LineChartQuery>;
export type LineChartQuery = (options: LineChartQueryOptions) => LineChartData[];
export interface LineChartQueryOptions {
range: [Date, Date];
}
export interface LineChartData {
points: XYPoint<Date, number>[];
legend?: string;
style?: LineChartStyle;
}
export interface LineChartStyle {
color: string;
width: number;
opacity: number;
dashes: number[];
}
| Remove unnecessary parent type of TabbedChartsMeta | Remove unnecessary parent type of TabbedChartsMeta
| TypeScript | apache-2.0 | googleinterns/guide-doge,googleinterns/guide-doge,googleinterns/guide-doge | ---
+++
@@ -16,11 +16,9 @@
query: QueryT;
}
-export interface ContainerComponentMeta<T extends string, MetaT> extends ComponentMeta<T> {
- metas: MetaT;
+export interface TabbedChartsMeta extends ComponentMeta<'tabbed'> {
+ metas: ChartMeta[];
}
-
-export type TabbedChartsMeta = ContainerComponentMeta<'tabbed', ChartMeta[]>;
export type ChartMeta = LineChartMeta;
|
6d222f60cb1be7133bef19386a85e5a31c498be8 | test/testRunner.ts | test/testRunner.ts | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as glob from "glob";
import * as Mocha from "mocha";
import * as path from "path";
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: !process.env.TF_BUILD, // colored output from test results
reporter: "mocha-multi-reporters",
timeout: 5000,
reporterOptions: {
reporterEnabled: "spec, mocha-junit-reporter",
mochaJunitReporterReporterOptions: {
mochaFile: path.join(__dirname, "..", "..", "test-results.xml"),
},
},
});
const testsRoot = path.resolve(__dirname, "..");
return new Promise((c, e) => {
glob("**/**.test.js", { cwd: testsRoot }, (err: any, files: any[]) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run((failures) => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as glob from "glob";
import * as Mocha from "mocha";
import * as path from "path";
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
color: !process.env.TF_BUILD, // colored output from test results
reporter: "mocha-multi-reporters",
timeout: 5000,
reporterOptions: {
reporterEnabled: "spec, mocha-junit-reporter",
mochaJunitReporterReporterOptions: {
mochaFile: path.join(__dirname, "..", "..", "test-results.xml"),
},
},
});
const testsRoot = path.resolve(__dirname, "..");
return new Promise((c, e) => {
glob("**/**.test.js", { cwd: testsRoot }, (err: any, files: any[]) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run((failures) => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}
| Fix deprecated use of `mocha` | Fix deprecated use of `mocha`
The `useColors` option was replaced with `color`.
| TypeScript | mit | PowerShell/vscode-powershell | ---
+++
@@ -9,7 +9,7 @@
// Create the mocha test
const mocha = new Mocha({
ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
- useColors: !process.env.TF_BUILD, // colored output from test results
+ color: !process.env.TF_BUILD, // colored output from test results
reporter: "mocha-multi-reporters",
timeout: 5000,
reporterOptions: { |
a4adde6f536b8498e1495768ee3c51c97cef649a | src/shadowbox/model/access_key.ts | src/shadowbox/model/access_key.ts |
// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export type AccessKeyId = string;
export interface ProxyParams {
hostname: string;
portNumber: number;
encryptionMethod: string;
password: string;
}
export interface AccessKey {
// The unique identifier for this access key.
id: AccessKeyId;
// Admin-controlled, editable name for this access key.
name: string;
// Used in metrics reporting to decouple from the real id. Can change.
metricsId: AccessKeyId;
// Parameters to access the proxy
proxyParams: ProxyParams;
}
export interface AccessKeyRepository {
// Creates a new access key. Parameters are chosen automatically.
createNewAccessKey(): Promise<AccessKey>;
// Removes the access key given its id. Returns true if successful.
removeAccessKey(id: AccessKeyId): boolean;
// Lists all existing access keys
listAccessKeys(): IterableIterator<AccessKey>;
// Apply the specified update to the specified access key.
// Returns true if successful.
renameAccessKey(id: AccessKeyId, name: string): boolean;
} | // Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export type AccessKeyId = string;
export interface ProxyParams {
hostname: string;
portNumber: number;
encryptionMethod: string;
password: string;
}
export interface AccessKey {
// The unique identifier for this access key.
id: AccessKeyId;
// Admin-controlled, editable name for this access key.
name: string;
// Used in metrics reporting to decouple from the real id. Can change.
metricsId: AccessKeyId;
// Parameters to access the proxy
proxyParams: ProxyParams;
}
export interface AccessKeyRepository {
// Creates a new access key. Parameters are chosen automatically.
createNewAccessKey(): Promise<AccessKey>;
// Removes the access key given its id. Returns true if successful.
removeAccessKey(id: AccessKeyId): boolean;
// Lists all existing access keys
listAccessKeys(): IterableIterator<AccessKey>;
// Apply the specified update to the specified access key.
// Returns true if successful.
renameAccessKey(id: AccessKeyId, name: string): boolean;
} | Remove blank line at the top | Remove blank line at the top
| TypeScript | apache-2.0 | Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server | ---
+++
@@ -1,4 +1,3 @@
-
// Copyright 2018 The Outline Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); |
de9a5b71173e0fd9485387c1ed936a5ebba77dfb | src/types/future.d.ts | src/types/future.d.ts | /**
* This file is part of Threema Web.
*
* Threema Web is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* A future similar to Python's asyncio.Future. Allows to resolve or reject
* outside of the executor and query the current status.
*/
interface Future<T> extends Promise<T> {
/**
* Return whether the future is done (resolved or rejected).
*/
readonly done: boolean;
/**
* Resolve the future.
*/
resolve(value?: T | PromiseLike<T>): void;
/**
* Reject the future.
*/
reject(reason?: any): void;
}
interface FutureStatic {
new<T>(executor?: (resolveFn: (value?: T | PromiseLike<T>) => void,
rejectFn: (reason?: any) => void) => void,
): Future<T>
withMinDuration<T>(promise: Promise<T>, minDuration: Number): Future<T>
}
declare var Future: FutureStatic;
| /**
* This file is part of Threema Web.
*
* Threema Web is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* A future similar to Python's asyncio.Future. Allows to resolve or reject
* outside of the executor and query the current status.
*/
interface Future<T> extends Promise<T> {
/**
* Return whether the future is done (resolved or rejected).
*/
readonly done: boolean;
/**
* Resolve the future.
*/
resolve(value?: T | PromiseLike<T>): void;
/**
* Reject the future.
*/
reject(reason?: any): void;
}
interface FutureStatic extends PromiseConstructor {
new<T>(executor?: (resolveFn: (value?: T | PromiseLike<T>) => void,
rejectFn: (reason?: any) => void) => void,
): Future<T>
withMinDuration<T>(promise: Promise<T>, minDuration: Number): Future<T>
}
declare var Future: FutureStatic;
| Fix let FutureStatic inherit from PromiseConstructor | Fix let FutureStatic inherit from PromiseConstructor
| TypeScript | agpl-3.0 | threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web | ---
+++
@@ -36,7 +36,7 @@
reject(reason?: any): void;
}
-interface FutureStatic {
+interface FutureStatic extends PromiseConstructor {
new<T>(executor?: (resolveFn: (value?: T | PromiseLike<T>) => void,
rejectFn: (reason?: any) => void) => void,
): Future<T> |
a23747f415b9d926025d4789d09bd6a0c5b8a2e7 | lib/jsonparser.ts | lib/jsonparser.ts | import epcis = require('./epcisevents');
export module EPCIS {
export class EpcisJsonParser {
constructor() {}
static parseObj(obj: Object) : epcis.EPCIS.EpcisEvent {
if(EpcisJsonParser.isEvent(obj)) {
if(obj['type'] === 'AggregationEvent') {
var agg = new epcis.EPCIS.AggregationEvent();
agg.loadFromObj(obj);
return agg;
} else if(obj['type'] === 'TransformationEvent') {
var trans = new epcis.EPCIS.TransformationEvent();
trans.loadFromObj(obj);
return trans;
}
}
}
static parseJson(json: string) : epcis.EPCIS.Events {
var obj = JSON.parse(json);
return this.parseObj(obj);
}
// just check whether the given object is a valid event object already
static isEvent(obj:any): boolean {
var allowedTypes:Array<string> = ['ObjectEvent', 'AggregationEvent', 'TransactionEvent'];
var type = obj['type'];
if(allowedTypes.indexOf(type) != -1) {
// allowed type
return true;
}
return false;
}
}
} | import epcis = require('./epcisevents');
export module EPCIS {
export class EpcisJsonParser {
constructor() {}
static parseObj(obj: Object) : epcis.EPCIS.EpcisEvent {
if(EpcisJsonParser.isEvent(obj)) {
if(obj['type'] === 'AggregationEvent') {
var agg = epcis.EPCIS.AggregationEvent.loadFromObj(obj);
return agg;
} else if(obj['type'] === 'TransformationEvent') {
var trans = epcis.EPCIS.TransformationEvent.loadFromObj(obj);
return trans;
}
}
}
static parseJson(json: string) : epcis.EPCIS.EpcisEvent {
var obj = JSON.parse(json);
return EpcisJsonParser.parseObj(obj);
}
// just check whether the given object is a valid event object already
static isEvent(obj:any): boolean {
var allowedTypes:Array<string> = ['ObjectEvent', 'AggregationEvent', 'TransactionEvent'];
var type = obj['type'];
if(allowedTypes.indexOf(type) != -1) {
// allowed type
return true;
}
return false;
}
}
} | Use new static parser functions | Use new static parser functions
| TypeScript | mit | matgnt/epcis-js,matgnt/epcis-js | ---
+++
@@ -6,20 +6,18 @@
static parseObj(obj: Object) : epcis.EPCIS.EpcisEvent {
if(EpcisJsonParser.isEvent(obj)) {
if(obj['type'] === 'AggregationEvent') {
- var agg = new epcis.EPCIS.AggregationEvent();
- agg.loadFromObj(obj);
+ var agg = epcis.EPCIS.AggregationEvent.loadFromObj(obj);
return agg;
} else if(obj['type'] === 'TransformationEvent') {
- var trans = new epcis.EPCIS.TransformationEvent();
- trans.loadFromObj(obj);
+ var trans = epcis.EPCIS.TransformationEvent.loadFromObj(obj);
return trans;
}
}
}
- static parseJson(json: string) : epcis.EPCIS.Events {
+ static parseJson(json: string) : epcis.EPCIS.EpcisEvent {
var obj = JSON.parse(json);
- return this.parseObj(obj);
+ return EpcisJsonParser.parseObj(obj);
}
// just check whether the given object is a valid event object already |
e52551931440101f6204151d6f8ae165bb3b7559 | ui/src/Project.tsx | ui/src/Project.tsx | import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { search } from './search';
import DocumentTeaser from './DocumentTeaser';
import { Container, Row, Col } from 'react-bootstrap';
import DocumentDetails from './DocumentDetails';
export default () => {
const { id } = useParams();
const [documents, setDocuments] = useState([]);
const [projectDocument, setProjectDocument] = useState(null);
useEffect(() => {
const query = { q: `project:${id}`, skipTypes: ['Project', 'Image', 'Photo', 'Drawing'] };
search(query).then(setDocuments);
getProjectDocument(id).then(setProjectDocument);
}, [id]);
return (
<Container fluid>
<Row>
<Col sm={ 4 }>
{ renderProjectDocument(projectDocument) }
</Col>
<Col>
{ renderResultList(documents) }
</Col>
</Row>
</Container>
);
};
const renderProjectDocument = (projectDocument: any) =>
projectDocument ? <DocumentDetails document={ projectDocument } /> : '';
const renderResultList = (documents: any) =>
documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />);
const getProjectDocument = async (id: string): Promise<any> => {
const response = await fetch(`/documents/${id}`);
return await response.json();
};
| import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { search } from './search';
import DocumentTeaser from './DocumentTeaser';
import { Container, Row, Col } from 'react-bootstrap';
import DocumentDetails from './DocumentDetails';
export default () => {
const { id } = useParams();
const [documents, setDocuments] = useState([]);
const [projectDocument, setProjectDocument] = useState(null);
useEffect(() => {
const query = { q: `project:${id}`, skipTypes: ['Project', 'Image', 'Photo', 'Drawing'] };
search(query).then(setDocuments);
getProjectDocument(id).then(setProjectDocument);
}, [id]);
return (
<Container fluid>
<Row>
<Col sm={ 3 }>
{ renderProjectTeaser(projectDocument) }
</Col>
<Col>
{ renderResultList(documents) }
</Col>
</Row>
</Container>
);
};
const renderProjectTeaser = (projectDocument: any) =>
projectDocument ? <DocumentTeaser document={ projectDocument } /> : '';
const renderResultList = (documents: any) =>
documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />);
const getProjectDocument = async (id: string): Promise<any> => {
const response = await fetch(`/documents/${id}`);
return await response.json();
};
| Use document teaser for project metadata | Use document teaser for project metadata
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -20,8 +20,8 @@
return (
<Container fluid>
<Row>
- <Col sm={ 4 }>
- { renderProjectDocument(projectDocument) }
+ <Col sm={ 3 }>
+ { renderProjectTeaser(projectDocument) }
</Col>
<Col>
{ renderResultList(documents) }
@@ -32,8 +32,8 @@
};
-const renderProjectDocument = (projectDocument: any) =>
- projectDocument ? <DocumentDetails document={ projectDocument } /> : '';
+const renderProjectTeaser = (projectDocument: any) =>
+ projectDocument ? <DocumentTeaser document={ projectDocument } /> : '';
const renderResultList = (documents: any) =>
documents.map(document => <DocumentTeaser document={ document } key={ document.resource.id } />); |
8207d65c2228ecd75142f1e160c7028959069db9 | src/event/Event.ts | src/event/Event.ts | import { Client } from '../client/Client';
/**
* Method to be implemented that will be executed whenever the event this handler
* is for is emitted by the Client
* @abstact
* @method Event#action
* @param {any[]} args - The args your event handler will be receiving
* from the event it handles
* @returns {void}
*/
/**
* Event class to extend when writing your own custom event handlers
* @abstract
* @param {string} name - Name of the Client event this event handler
* will handle
*/
export abstract class Event<T extends Client = Client>
{
public name: string;
public client!: T;
public constructor(name: string)
{
this.name = name;
}
/**
* Receive the client instance and save it
* @private
*/
public _register(client: T): void
{
this.client = client;
}
// Docs above class
public abstract action(...args: any[]): void;
}
| import { Client } from '../client/Client';
/**
* Method to be implemented that will be executed whenever the event this handler
* is for is emitted by the Client
* @abstact
* @method Event#action
* @param {any[]} ...args - The args your event handler will be receiving
* from the event it handles
* @returns {void}
*/
/**
* Event class to extend when writing your own custom event handlers
* @abstract
* @param {string} name - Name of the Client event this event handler
* will handle
*/
export abstract class Event<T extends Client = Client>
{
public name: string;
public client!: T;
public constructor(name: string)
{
this.name = name;
}
/**
* Receive the client instance and save it
* @private
*/
public _register(client: T): void
{
this.client = client;
}
// Docs above class
public abstract action(...args: any[]): void;
}
| Test how jsdoc will render rest args | Test how jsdoc will render rest args
Because I just realized I'm not aware of anywhere I'm using them in the docs | TypeScript | mit | zajrik/yamdbf,zajrik/yamdbf | ---
+++
@@ -5,7 +5,7 @@
* is for is emitted by the Client
* @abstact
* @method Event#action
- * @param {any[]} args - The args your event handler will be receiving
+ * @param {any[]} ...args - The args your event handler will be receiving
* from the event it handles
* @returns {void}
*/ |
5a28fe0242ed53c7df77b53302dcfe43c84dca9f | jovo-clients/jovo-client-web-vue/src/index.ts | jovo-clients/jovo-client-web-vue/src/index.ts | import { Client, Config, DeepPartial } from 'jovo-client-web';
import { PluginObject } from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: DeepPartial<Config>;
}
const plugin: PluginObject<JovoWebClientVueConfig> = {
install: (vue, config) => {
if (!config) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
vue.prototype.$client = new Client(config.url, config.client);
},
};
export default plugin;
export * from 'jovo-client-web';
| import { Client, Config, DeepPartial } from 'jovo-client-web';
import { PluginObject } from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: DeepPartial<Config>;
}
const plugin: PluginObject<JovoWebClientVueConfig> = {
install: (vue, config) => {
if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
const client = new Client(config.url, config.client);
// make the client reactive
vue.prototype.$client = vue.observable(client);
},
};
export default plugin;
export * from 'jovo-client-web';
| Make Client reactive and add check if url is set in config | :sparkles: Make Client reactive and add check if url is set in config
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -14,12 +14,14 @@
const plugin: PluginObject<JovoWebClientVueConfig> = {
install: (vue, config) => {
- if (!config) {
+ if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
- vue.prototype.$client = new Client(config.url, config.client);
+ const client = new Client(config.url, config.client);
+ // make the client reactive
+ vue.prototype.$client = vue.observable(client);
},
};
|
f69ce2593842b7f9d5e99f78d3b575e3982b3094 | src/HttpContainer.ts | src/HttpContainer.ts | import { Controllers, Controller, HttpController } from './decorators/Controller';
import { IHttpMethod, HttpMethods, HttpGet, HttpPost, HttpPut, HttpDelete } from './decorators/HttpMethod';
import * as express from 'express';
export class HttpContainer {
constructor() {}
register (router: express.Router) {
const controllers: HttpController[] = Controllers;
const decorators: IHttpMethod[] = HttpMethods;
for (let i in decorators) {
const decorator: IHttpMethod = decorators[i];
for (let j in controllers) {
const controller: HttpController = controllers[j];
if (controller.targetClass === decorator.targetClass) {
const path = `${controller.path}${decorator.path}`;
console.log(`${decorator.method} ${path}`);
switch (decorator.method) {
case 'GET':
router.get(path, decorator.fcn);
break;
case 'POST':
router.post(path, decorator.fcn);
break;
case 'PUT':
router.put(path, decorator.fcn);
break;
case 'DELETE':
router.delete(path, decorator.fcn);
break;
}
}
}
}
}
} | import { Controllers, Controller, HttpController } from './decorators/Controller';
import { IHttpMethod, HttpMethods, HttpGet, HttpPost, HttpPut, HttpDelete } from './decorators/HttpMethod';
import * as express from 'express';
export class HttpContainer {
constructor() {}
register (router: express.Router) {
const controllers: HttpController[] = Controllers;
const decorators: IHttpMethod[] = HttpMethods;
decorators.forEach((decorator) => {
controllers.forEach((controller) => {
if (controller.targetClass === decorator.targetClass) {
const path = `${controller.path}${decorator.path}`;
console.log(`[Restorator] Registered ${decorator.method} ${path}`);
switch (decorator.method) {
case 'GET':
router.get(path, decorator.fcn);
break;
case 'POST':
router.post(path, decorator.fcn);
break;
case 'PUT':
router.put(path, decorator.fcn);
break;
case 'DELETE':
router.delete(path, decorator.fcn);
break;
}
}
});
});
}
} | Use forEach instead of 'for in' | Use forEach instead of 'for in'
| TypeScript | mit | mborders/restorator | ---
+++
@@ -10,15 +10,11 @@
const controllers: HttpController[] = Controllers;
const decorators: IHttpMethod[] = HttpMethods;
- for (let i in decorators) {
- const decorator: IHttpMethod = decorators[i];
-
- for (let j in controllers) {
- const controller: HttpController = controllers[j];
-
+ decorators.forEach((decorator) => {
+ controllers.forEach((controller) => {
if (controller.targetClass === decorator.targetClass) {
const path = `${controller.path}${decorator.path}`;
- console.log(`${decorator.method} ${path}`);
+ console.log(`[Restorator] Registered ${decorator.method} ${path}`);
switch (decorator.method) {
case 'GET':
@@ -35,7 +31,7 @@
break;
}
}
- }
- }
+ });
+ });
}
} |
f7fb5e59325f7f4fb670d92d5fe68be38255ccd6 | applications/mail/src/app/components/message/extras/ExtraDecryptedSubject.tsx | applications/mail/src/app/components/message/extras/ExtraDecryptedSubject.tsx | import React from 'react';
import { Icon, Tooltip } from 'react-components';
import { c } from 'ttag';
import { MessageExtended } from '../../../models/message';
interface Props {
message: MessageExtended;
}
const ExtraDecryptedSubject = ({ message }: Props) => {
if (!message.decryptedSubject) {
return null;
}
return (
<div className="bg-white-dm rounded bordered-container p0-5 mb0-5 flex flex-nowrap flex-items-center flex-spacebetween">
<div className="flex">
<Tooltip title={c('Info').t`Subject is end-to-end encrypted`}>
<Icon
name="lock"
className="mtauto mbauto mr0-5"
alt={c('Info').t`Subject is end-to-end encrypted`}
/>
</Tooltip>
<div className="mr0-5">
{c('Info').t`Subject:`} {message.decryptedSubject}
</div>
</div>
</div>
);
};
export default ExtraDecryptedSubject;
| import React from 'react';
import { Icon, Tooltip } from 'react-components';
import { c } from 'ttag';
import { MessageExtended } from '../../../models/message';
interface Props {
message: MessageExtended;
}
const ExtraDecryptedSubject = ({ message }: Props) => {
if (!message.decryptedSubject) {
return null;
}
return (
<div className="bg-white-dm rounded bordered-container p0-5 mb0-5 flex flex-nowrap flex-items-center flex-spacebetween">
<div className="flex">
<Tooltip className="flex" title={c('Info').t`Subject is end-to-end encrypted`}>
<Icon
name="lock"
className="mtauto mbauto mr0-5"
alt={c('Info').t`Subject is end-to-end encrypted`}
/>
</Tooltip>
<div className="mr0-5">
{c('Info').t`Subject:`} {message.decryptedSubject}
</div>
</div>
</div>
);
};
export default ExtraDecryptedSubject;
| Fix icon alignment for encrpyted subject | [MAILWEB-1791] Fix icon alignment for encrpyted subject
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -16,7 +16,7 @@
return (
<div className="bg-white-dm rounded bordered-container p0-5 mb0-5 flex flex-nowrap flex-items-center flex-spacebetween">
<div className="flex">
- <Tooltip title={c('Info').t`Subject is end-to-end encrypted`}>
+ <Tooltip className="flex" title={c('Info').t`Subject is end-to-end encrypted`}>
<Icon
name="lock"
className="mtauto mbauto mr0-5" |
9c3e2db094d06ddc4a7dc3c8a9de899140e4ff7d | packages/core/src/store.ts | packages/core/src/store.ts | import { Store } from 'redux';
import { JsonSchema } from './models/jsonSchema';
import { UISchemaElement } from './models/uischema';
export interface JsonFormsStore extends Store<any> {
}
export interface JsonFormsState {
jsonforms: {
common: {
data: any;
schema?: JsonSchema;
uischema?: UISchemaElement;
};
renderers?: any[];
fields?: any[];
// allow additional state for JSONForms
[x: string]: any;
};
}
export interface JsonFormsInitialState {
data: any;
schema?: JsonSchema;
uischema?: UISchemaElement;
// allow additional state
[x: string]: any;
}
| import { Store } from 'redux';
import { JsonSchema } from './models/jsonSchema';
import { UISchemaElement } from './models/uischema';
import { ValidationState } from './reducers/validation';
export interface JsonFormsStore extends Store<any> {
}
export interface JsonFormsState {
jsonforms: {
common: {
data: any;
schema?: JsonSchema;
uischema?: UISchemaElement;
};
validation?: ValidationState,
renderers?: any[];
fields?: any[];
// allow additional state for JSONForms
[x: string]: any;
};
}
export interface JsonFormsInitialState {
data: any;
schema?: JsonSchema;
uischema?: UISchemaElement;
// allow additional state
[x: string]: any;
}
| Add validationState to JsonFormsState type | Add validationState to JsonFormsState type
| TypeScript | mit | qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms | ---
+++
@@ -1,6 +1,7 @@
import { Store } from 'redux';
import { JsonSchema } from './models/jsonSchema';
import { UISchemaElement } from './models/uischema';
+import { ValidationState } from './reducers/validation';
export interface JsonFormsStore extends Store<any> {
}
@@ -11,6 +12,7 @@
schema?: JsonSchema;
uischema?: UISchemaElement;
};
+ validation?: ValidationState,
renderers?: any[];
fields?: any[];
// allow additional state for JSONForms |
8c8057b657d725417748b4a89174006ea3acbc15 | src/utils/index.ts | src/utils/index.ts | import { Grid, Row, Column, Diagonal } from '../definitions';
export function getRows(grid: Grid): Row[] {
const length = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(length).map(() => copy.splice(0, length));
}
export function getColumns(grid: Grid): Column[] {
return getRows(transpose(grid));
}
export function getDiagonals(grid: Grid): Diagonal[] {
// TODO: Make it work
return [];
}
function getArray(length: number) {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
const transposed = grid.filter(() => false);
for (let j = 0; j < size; ++j) {
for (let i = 0; i < size; ++i) {
transposed.push(grid[j + (i * size)]);
}
}
return transposed;
}
| import { Grid, Row, Column, Diagonal } from '../definitions';
export function getRows(grid: Grid): Row[] {
const length = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(length).map(() => copy.splice(0, length));
}
export function getColumns(grid: Grid): Column[] {
return getRows(transpose(grid));
}
export function getDiagonals(grid: Grid): Diagonal[] {
// TODO: Make it work
return [];
}
function getArray(length: number) {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
}
| Convert imperative code to declarative code | Convert imperative code to declarative code
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -21,11 +21,5 @@
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
- const transposed = grid.filter(() => false);
- for (let j = 0; j < size; ++j) {
- for (let i = 0; i < size; ++i) {
- transposed.push(grid[j + (i * size)]);
- }
- }
- return transposed;
+ return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
} |
12f638a0eb1fcdf6276488248b3d4678da283138 | src/app/add-assignment/add-assignment.component.spec.ts | src/app/add-assignment/add-assignment.component.spec.ts | import {
beforeEachProviders,
describe,
inject,
it
} from '@angular/core/testing';
import { AddAssignmentComponent } from './add-assignment.component';
describe('AddAssignmentComponent', () => {
beforeEachProviders(() => [
AddAssignmentComponent
]);
let component: AddAssignmentComponent;
beforeEach(inject([AddAssignmentComponent], (comp: AddAssignmentComponent) => {
component = comp;
}));
it('should initialize array of number of possible answer on construction', () => {
expect(component.numOfPossibleAnswers).toEqual([1, 2, 3, 4, 5]);
});
it('should emit closeModal event', () => {
component.close.subscribe(event => {
expect(event.value).toBe('closeModal');
});
component.closeModal();
});
});
| import {
beforeEachProviders,
describe,
inject,
it
} from '@angular/core/testing';
import { AddAssignmentComponent } from './add-assignment.component';
describe('AddAssignmentComponent', () => {
beforeEachProviders(() => [
AddAssignmentComponent
]);
let component: AddAssignmentComponent;
beforeEach(inject([AddAssignmentComponent], (comp: AddAssignmentComponent) => {
component = comp;
}));
it('should initialize array of number of possible answer on construction', () => {
expect(component.numOfPossibleAnswers).toEqual([1, 2, 3, 4, 5]);
});
it('should emit closeModal event', () => {
component.close.subscribe(event => {
expect(event.value).toBe('closeModal');
});
component.closeModal();
});
it('there should be no possible answers if numOfAnswersPerQuestion is 0', () => {
component.numAnswersPerQuestion = 0;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual([]);
});
it('possible answers should be A if numOfAnswersPerQuestion is 1', () => {
component.numAnswersPerQuestion = 1;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual(['A']);
});
it('possible answers should be A, B if numOfAnswersPerQuestion is 2', () => {
component.numAnswersPerQuestion = 2;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual(['A', 'B']);
});
it('possible answers should be A, B, C if numOfAnswersPerQuestion is 3', () => {
component.numAnswersPerQuestion = 3;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual(['A', 'B', 'C']);
});
it('possible answers should be A, B, C, D if numOfAnswersPerQuestion is 4', () => {
component.numAnswersPerQuestion = 4;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual(['A', 'B', 'C', 'D']);
});
it('possible answers should be A, B, C, D, E if numOfAnswersPerQuestion is 5', () => {
component.numAnswersPerQuestion = 5;
component.changePossibleAnswers();
expect(component.possibleAnswers).toEqual(['A', 'B', 'C', 'D', 'E']);
});
});
| Add tests for changePossibleAnswers in add-assignment component | Add tests for changePossibleAnswers in add-assignment component
| TypeScript | mit | bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder,bryant-pham/brograder | ---
+++
@@ -29,4 +29,52 @@
component.closeModal();
});
+
+ it('there should be no possible answers if numOfAnswersPerQuestion is 0', () => {
+ component.numAnswersPerQuestion = 0;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual([]);
+ });
+
+ it('possible answers should be A if numOfAnswersPerQuestion is 1', () => {
+ component.numAnswersPerQuestion = 1;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual(['A']);
+ });
+
+ it('possible answers should be A, B if numOfAnswersPerQuestion is 2', () => {
+ component.numAnswersPerQuestion = 2;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual(['A', 'B']);
+ });
+
+ it('possible answers should be A, B, C if numOfAnswersPerQuestion is 3', () => {
+ component.numAnswersPerQuestion = 3;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual(['A', 'B', 'C']);
+ });
+
+ it('possible answers should be A, B, C, D if numOfAnswersPerQuestion is 4', () => {
+ component.numAnswersPerQuestion = 4;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual(['A', 'B', 'C', 'D']);
+ });
+
+ it('possible answers should be A, B, C, D, E if numOfAnswersPerQuestion is 5', () => {
+ component.numAnswersPerQuestion = 5;
+
+ component.changePossibleAnswers();
+
+ expect(component.possibleAnswers).toEqual(['A', 'B', 'C', 'D', 'E']);
+ });
}); |
d2f1e052f6379d799b57831e8a0847d181153188 | src/db/repositories/postRepository.ts | src/db/repositories/postRepository.ts | import {Id} from '../types'
import {isObjectId} from '../helpers'
import Post, {DbPost, UpsertPost} from '../models/Post'
export const findPostById = async (id: Id): Promise<DbPost> => {
return isObjectId(id) ? await Post.findById(id) : undefined
}
export const upsertPost = async (payload: UpsertPost): Promise<DbPost> => {
const isNew = !payload._id
const post = {
title: payload.title,
body: payload.body,
}
return isNew
? await Post.create(post)
: await Post.update({_id: payload._id}, post)
}
| import {Id} from '../types'
import {isObjectId} from '../helpers'
import Post, {DbPost, UpsertPost} from '../models/Post'
export const findPostById = async (id: Id): Promise<DbPost|undefined> => {
return isObjectId(id) ? await Post.findById(id) : undefined
}
export const upsertPost = async (payload: UpsertPost): Promise<DbPost> => {
const isNew = !payload._id
const post = {
title: payload.title,
body: payload.body,
}
return isNew
? await Post.create(post)
: await Post.update({_id: payload._id}, post)
}
| Annotate resolved value as nullable | Annotate resolved value as nullable
| TypeScript | mit | ericnishio/express-boilerplate,ericnishio/express-boilerplate,ericnishio/express-boilerplate | ---
+++
@@ -2,7 +2,7 @@
import {isObjectId} from '../helpers'
import Post, {DbPost, UpsertPost} from '../models/Post'
-export const findPostById = async (id: Id): Promise<DbPost> => {
+export const findPostById = async (id: Id): Promise<DbPost|undefined> => {
return isObjectId(id) ? await Post.findById(id) : undefined
}
|
6de608a3595470c673067774506de73d6f2a0111 | src/components/course-summary.tsx | src/components/course-summary.tsx | import * as React from "react";
import {Class, Course} from "../class"
import {Toggle} from "./utilities/toggle"
import {ClassList} from "./class-list"
import {Department} from "./department"
export interface CourseSummaryProps {
classes: Class[],
course: Course
}
export class CourseSummary extends React.Component<CourseSummaryProps, {}> {
state: {expanded: boolean} = {expanded: false};
render() {
return <div className={"course" + (this.state.expanded?" expanded":"")}>
<h1 onClick={ () => this.setState({"expanded": !this.state.expanded}) }>
<span className="department-acronym"><Department departmentID={this.props.course.department}/></span>
<span> </span>
<span className="course-number">{this.props.course.course}</span>
<span> </span>
<span className="title">{this.props.course.title} </span>
</h1>
<Toggle expanded={this.state.expanded}>
<div className="description">
{this.props.course.description}
</div>
<div className="classes">
<ClassList classes={this.props.classes}/>
</div>
</Toggle>
</div>
}
} | import * as React from "react";
import {Class, Course} from "../class"
import {Toggle} from "./utilities/toggle"
import {ClassList} from "./class-list"
import {Department} from "./department"
export interface CourseSummaryProps {
classes: Class[],
course: Course
}
export class CourseSummary extends React.Component<CourseSummaryProps, {}> {
state: {expanded: boolean} = {expanded: false};
render() {
return <div className={"course" + (this.state.expanded?" expanded":"")}>
<h1 onClick={ () => this.setState({"expanded": !this.state.expanded}) }>
<span className="department-acronym"><Department departmentID={this.props.course.department}/></span>
<span> </span>
<span className="course-number">{this.props.course.course}</span>
<span>: </span>
<span className="title">{this.props.course.title}</span>
</h1>
<Toggle expanded={this.state.expanded}>
<div className="description">
{this.props.course.description}
</div>
<div className="classes">
<ClassList classes={this.props.classes}/>
</div>
</Toggle>
</div>
}
} | Add a : after the course number | Add a : after the course number
| TypeScript | mit | goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End | ---
+++
@@ -16,8 +16,8 @@
<span className="department-acronym"><Department departmentID={this.props.course.department}/></span>
<span> </span>
<span className="course-number">{this.props.course.course}</span>
- <span> </span>
- <span className="title">{this.props.course.title} </span>
+ <span>: </span>
+ <span className="title">{this.props.course.title}</span>
</h1>
<Toggle expanded={this.state.expanded}>
<div className="description"> |
d47c9aff6ad222e4a2bffda15828c5f5c043b63d | types/react-hyperscript/index.d.ts | types/react-hyperscript/index.d.ts | // Type definitions for react-hyperscript 3.0
// Project: https://github.com/mlmorg/react-hyperscript
// Definitions by: tock203 <https://github.com/tock203>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { ComponentClass, StatelessComponent, ReactElement } from 'react';
declare namespace h {}
type Element = ReactElement<any> | string | null;
declare function h<P>(
componentOrTag: ComponentClass<P> | StatelessComponent<P> | string,
properties?: P,
children?: ReadonlyArray<Element> | Element
): ReactElement<P>;
export = h;
| // Type definitions for react-hyperscript 3.0
// Project: https://github.com/mlmorg/react-hyperscript
// Definitions by: tock203 <https://github.com/tock203>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { ComponentClass, StatelessComponent, ReactElement } from 'react';
declare namespace h {}
type Element = ReactElement<any> | string | null;
declare function h(
componentOrTag: ComponentClass | StatelessComponent | string,
children?: ReadonlyArray<Element> | Element
): ReactElement<any>;
declare function h<P extends {[attr: string]: any}>(
componentOrTag: ComponentClass<P> | StatelessComponent<P> | string,
properties: P,
children?: ReadonlyArray<Element> | Element
): ReactElement<P>;
export = h;
| Stop treating Element as props | Stop treating Element as props
| TypeScript | mit | borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,mcliment/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,rolandzwaga/DefinitelyTyped,chrootsu/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,alexdresko/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped | ---
+++
@@ -10,9 +10,14 @@
type Element = ReactElement<any> | string | null;
-declare function h<P>(
+declare function h(
+ componentOrTag: ComponentClass | StatelessComponent | string,
+ children?: ReadonlyArray<Element> | Element
+): ReactElement<any>;
+
+declare function h<P extends {[attr: string]: any}>(
componentOrTag: ComponentClass<P> | StatelessComponent<P> | string,
- properties?: P,
+ properties: P,
children?: ReadonlyArray<Element> | Element
): ReactElement<P>;
|
a441297e6f5c4492318a6d60bbc292ca4da64b50 | src/app/utils/url.utils.ts | src/app/utils/url.utils.ts | import {Injectable, Inject} from '@angular/core';
@Injectable()
export class UrlUtils {
constructor(@Inject('DataPathUtils') private dataPathUtils) {
}
public urlIsClearOfParams(url) {
if (url.indexOf(':') >= 0) {
return false;
}
return url;
}
public extractIdFieldName(url) {
const matcher = /http[s]?:\/\/.*\/:([a-zA-Z0-9_-]*)[\/|\?|#]?.*/;
const extractArr = url.match(matcher);
if (extractArr.length > 1) {
return extractArr[1];
}
return null;
}
public getUrlWithReplacedId(url, fieldName, fieldValue) {
return url.replace(':' + fieldName, fieldValue);
}
public getParsedUrl(url, data, dataPath) {
const fieldName = this.extractIdFieldName(url);
const fieldValue = this.dataPathUtils.getFieldValueInPath(fieldName, dataPath, data);
if (fieldValue) {
url = this.getUrlWithReplacedId(url, fieldName, fieldValue);
return url;
}
}
}
| import {Injectable, Inject} from '@angular/core';
@Injectable()
export class UrlUtils {
constructor(@Inject('DataPathUtils') private dataPathUtils) {
}
public urlIsClearOfParams(url) {
if (url.indexOf(':') >= 0) {
return false;
}
return url;
}
public extractIdFieldName(url) {
const matcher = /:([a-zA-Z0-9_-]+)[\/?#&]?.*/;
const extractArr = url.match(matcher);
if (extractArr.length > 1) {
return extractArr[1];
}
return null;
}
public getUrlWithReplacedId(url, fieldName, fieldValue) {
return url.replace(':' + fieldName, fieldValue);
}
public getParsedUrl(url, data, dataPath) {
const fieldName = this.extractIdFieldName(url);
const fieldValue = this.dataPathUtils.getFieldValueInPath(fieldName, dataPath, data);
if (fieldValue) {
url = this.getUrlWithReplacedId(url, fieldName, fieldValue);
return url;
}
}
}
| Support relative urls in config file | Support relative urls in config file
| TypeScript | mit | dsternlicht/RESTool,dsternlicht/RESTool,dsternlicht/RESTool | ---
+++
@@ -14,7 +14,7 @@
}
public extractIdFieldName(url) {
- const matcher = /http[s]?:\/\/.*\/:([a-zA-Z0-9_-]*)[\/|\?|#]?.*/;
+ const matcher = /:([a-zA-Z0-9_-]+)[\/?#&]?.*/;
const extractArr = url.match(matcher);
if (extractArr.length > 1) {
return extractArr[1]; |
a30e9355cf98a8d8f6590187de6b58d7f4f9fd3a | src/service/quoting-styles/style-registry.ts | src/service/quoting-styles/style-registry.ts | /// <reference path="../../common/models.ts" />
/// <reference path="../../../typings/tsd.d.ts" />
import StyleHelpers = require("./helpers");
import Models = require("../../common/models");
import _ = require("lodash");
export class QuotingStyleRegistry {
private _mapping : StyleHelpers.QuoteStyle[];
constructor(private _modules: StyleHelpers.QuoteStyle[]) {}
private static NullQuoteGenerator : StyleHelpers.QuoteStyle = new NullQuoteGenerator();
public Get = (mode : Models.QuotingMode) : StyleHelpers.QuoteStyle => {
var mod = this._modules[mode];
if (typeof mod === "undefined")
return QuotingStyleRegistry.NullQuoteGenerator;
return mod;
};
}
class NullQuoteGenerator implements StyleHelpers.QuoteStyle {
Mode = null;
GenerateQuote = (market: Models.Market, fv: Models.FairValue, params: Models.QuotingParameters) : StyleHelpers.GeneratedQuote => {
return null;
};
} | /// <reference path="../../common/models.ts" />
/// <reference path="../../../typings/tsd.d.ts" />
import StyleHelpers = require("./helpers");
import Models = require("../../common/models");
import _ = require("lodash");
class NullQuoteGenerator implements StyleHelpers.QuoteStyle {
Mode = null;
GenerateQuote = (market: Models.Market, fv: Models.FairValue, params: Models.QuotingParameters) : StyleHelpers.GeneratedQuote => {
return null;
};
}
export class QuotingStyleRegistry {
private _mapping : StyleHelpers.QuoteStyle[];
constructor(private _modules: StyleHelpers.QuoteStyle[]) {}
private static NullQuoteGenerator : StyleHelpers.QuoteStyle = new NullQuoteGenerator();
public Get = (mode : Models.QuotingMode) : StyleHelpers.QuoteStyle => {
var mod = this._modules[mode];
if (typeof mod === "undefined")
return QuotingStyleRegistry.NullQuoteGenerator;
return mod;
};
} | Fix null ref on startup | Fix null ref on startup
| TypeScript | isc | michaelgrosner/tribeca,michaelgrosner/tribeca,michaelgrosner/tribeca | ---
+++
@@ -4,6 +4,14 @@
import StyleHelpers = require("./helpers");
import Models = require("../../common/models");
import _ = require("lodash");
+
+class NullQuoteGenerator implements StyleHelpers.QuoteStyle {
+ Mode = null;
+
+ GenerateQuote = (market: Models.Market, fv: Models.FairValue, params: Models.QuotingParameters) : StyleHelpers.GeneratedQuote => {
+ return null;
+ };
+}
export class QuotingStyleRegistry {
private _mapping : StyleHelpers.QuoteStyle[];
@@ -21,11 +29,3 @@
return mod;
};
}
-
-class NullQuoteGenerator implements StyleHelpers.QuoteStyle {
- Mode = null;
-
- GenerateQuote = (market: Models.Market, fv: Models.FairValue, params: Models.QuotingParameters) : StyleHelpers.GeneratedQuote => {
- return null;
- };
-} |
8d0651a0943990c994dc41ce23a8ae8857d09778 | cypress/integration/navigation.spec.ts | cypress/integration/navigation.spec.ts | import { visit } from '../helper';
describe('Navigation', () => {
before(() => {
visit('official-storybook');
});
it('should search navigation item', () => {
cy.get('#storybook-explorer-searchfield').click().clear().type('persisting the action logger');
cy.get('.sidebar-container a')
.should('contain', 'Persisting the action logger')
.and('not.contain', 'a11y');
});
it('should display no results after searching a non-existing navigation item', () => {
cy.get('#storybook-explorer-searchfield').click().clear().type('zzzzzzzzzz');
cy.get('.sidebar-container').should('contain', 'This filter resulted in 0 results');
});
});
describe('Routing', () => {
it('should navigate to story addons-a11y-basebutton--default', () => {
visit('official-storybook');
cy.get('#addons-a11y-basebutton--label').click();
cy.url().should('include', 'path=/story/addons-a11y-basebutton--label');
});
it('should directly visit a certain story and render correctly', () => {
visit('official-storybook/?path=/story/addons-a11y-basebutton--label');
cy.getStoryElement().should('contain.text', 'Testing the a11y addon');
});
});
| import { visit } from '../helper';
describe('Navigation', () => {
before(() => {
visit('official-storybook');
});
it('should search navigation item', () => {
cy.get('#storybook-explorer-searchfield').click().clear().type('syntax');
cy.get('#storybook-explorer-menu button')
.should('contain', 'SyntaxHighlighter')
.and('not.contain', 'a11y');
});
it('should display no results after searching a non-existing navigation item', () => {
cy.get('#storybook-explorer-searchfield').click().clear().type('zzzzzzzzzz');
cy.get('#storybook-explorer-menu button').should('not.exist');
});
});
describe('Routing', () => {
it('should navigate to story addons-a11y-basebutton--default', () => {
visit('official-storybook');
cy.get('#addons-a11y-basebutton--label').click();
cy.url().should('include', 'path=/story/addons-a11y-basebutton--label');
});
it('should directly visit a certain story and render correctly', () => {
visit('official-storybook/?path=/story/addons-a11y-basebutton--label');
cy.getStoryElement().should('contain.text', 'Testing the a11y addon');
});
});
| Update e2e test for search. | Update e2e test for search.
| TypeScript | mit | storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,kadirahq/react-storybook,storybooks/storybook | ---
+++
@@ -6,17 +6,17 @@
});
it('should search navigation item', () => {
- cy.get('#storybook-explorer-searchfield').click().clear().type('persisting the action logger');
+ cy.get('#storybook-explorer-searchfield').click().clear().type('syntax');
- cy.get('.sidebar-container a')
- .should('contain', 'Persisting the action logger')
+ cy.get('#storybook-explorer-menu button')
+ .should('contain', 'SyntaxHighlighter')
.and('not.contain', 'a11y');
});
it('should display no results after searching a non-existing navigation item', () => {
cy.get('#storybook-explorer-searchfield').click().clear().type('zzzzzzzzzz');
- cy.get('.sidebar-container').should('contain', 'This filter resulted in 0 results');
+ cy.get('#storybook-explorer-menu button').should('not.exist');
});
});
|
dc3f85a68ebd00b2c07fc18ff6fe5cbb8e227984 | ui/puz/src/run.ts | ui/puz/src/run.ts | import { Run } from './interfaces';
import { Config as CgConfig } from 'chessground/config';
import { uciToLastMove } from './util';
import { makeFen } from 'chessops/fen';
import { chessgroundDests } from 'chessops/compat';
export const makeCgOpts = (run: Run, canMove: boolean): CgConfig => {
const cur = run.current;
const pos = cur.position();
return {
fen: makeFen(pos.toSetup()),
orientation: run.pov,
turnColor: pos.turn,
movable: {
color: run.pov,
dests: canMove ? chessgroundDests(pos) : undefined,
},
check: !!pos.isCheck(),
lastMove: uciToLastMove(cur.lastMove()),
};
};
export const povMessage = (run: Run) => `You play the ${run.pov} pieces in all puzzles`;
// `youPlayThe${run.pov == 'white' ? 'White' : 'Black'}PiecesInAllPuzzles`;
| import { Run } from './interfaces';
import { Config as CgConfig } from 'chessground/config';
import { uciToLastMove } from './util';
import { makeFen } from 'chessops/fen';
import { chessgroundDests } from 'chessops/compat';
export const makeCgOpts = (run: Run, canMove: boolean): CgConfig => {
const cur = run.current;
const pos = cur.position();
return {
fen: makeFen(pos.toSetup()),
orientation: run.pov,
turnColor: pos.turn,
movable: {
color: run.pov,
dests: canMove ? chessgroundDests(pos) : undefined,
},
check: !!pos.isCheck(),
lastMove: uciToLastMove(cur.lastMove()),
};
};
export const povMessage = (run: Run) =>
`youPlayThe${run.pov == 'white' ? 'White' : 'Black'}PiecesInAllPuzzles`;
| Revert "hardcode text until translations are available - REVERT ME" | Revert "hardcode text until translations are available - REVERT ME"
This reverts commit 2e482f2c97d9258a48adc0c259e368765eefdc27.
| TypeScript | agpl-3.0 | luanlv/lila,luanlv/lila,luanlv/lila,luanlv/lila,arex1337/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila | ---
+++
@@ -20,5 +20,5 @@
};
};
-export const povMessage = (run: Run) => `You play the ${run.pov} pieces in all puzzles`;
-// `youPlayThe${run.pov == 'white' ? 'White' : 'Black'}PiecesInAllPuzzles`;
+export const povMessage = (run: Run) =>
+ `youPlayThe${run.pov == 'white' ? 'White' : 'Black'}PiecesInAllPuzzles`; |
bb68475dbb2a4b33d2ac382fa0f1f697b9038adb | services/QuillDiagnostic/app/components/eslDiagnostic/titleCard.tsx | services/QuillDiagnostic/app/components/eslDiagnostic/titleCard.tsx | import React, { Component } from 'react';
const beginArrow = 'https://assets.quill.org/images/icons/begin_arrow.svg';
import translations from '../../libs/translations/index.js';
class TitleCard extends Component {
getContentHTML() {
let html = this.props.data.content ? this.props.data.content : translations.english[this.props.data.key];
if (this.props.language !== 'english') {
const textClass = this.props.language === 'arabic' ? 'right-to-left arabic-title-div' : '';
html += `<br/><div class="${textClass}">${translations[this.props.language][this.props.data.key]}</div>`;
}
return html;
}
getButtonText() {
let text = translations.english['continue button text']
if (this.props.language !== 'english') {
text += ` / ${translations[this.props.language]['continue button text']}`
}
return text
}
render() {
return (
<div className="landing-page">
<div className="landing-page-html" dangerouslySetInnerHTML={{ __html: this.getContentHTML(), }} />
<button className="button student-begin" onClick={this.props.nextQuestion}>
{this.getButtonText()}
<img className="begin-arrow" src={beginArrow} />
</button>
</div>
);
}
}
export default TitleCard;
| import React, { Component } from 'react';
const beginArrow = 'https://assets.quill.org/images/icons/begin_arrow.svg';
import translations from '../../libs/translations/index.js';
export interface ComponentProps {
data: any
language: string
nextQuestion(): void
}
class TitleCard extends Component<ComponentProps, any> {
getContentHTML() {
let html = this.props.data.content ? this.props.data.content : translations.english[this.props.data.key];
if (this.props.language !== 'english') {
const textClass = this.props.language === 'arabic' ? 'right-to-left arabic-title-div' : '';
html += `<br/><div class="${textClass}">${translations[this.props.language][this.props.data.key]}</div>`;
}
return html;
}
getButtonText() {
let text = translations.english['continue button text']
if (this.props.language !== 'english') {
text += ` / ${translations[this.props.language]['continue button text']}`
}
return text
}
render() {
return (
<div className="landing-page">
<div className="landing-page-html" dangerouslySetInnerHTML={{ __html: this.getContentHTML(), }} />
<button className="button student-begin" onClick={this.props.nextQuestion}>
{this.getButtonText()}
<img className="begin-arrow" src={beginArrow} />
</button>
</div>
);
}
}
export default TitleCard;
| Add prop declaration for titlecard tsx in esl diagnostic | Add prop declaration for titlecard tsx in esl diagnostic
| 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 | ---
+++
@@ -2,7 +2,13 @@
const beginArrow = 'https://assets.quill.org/images/icons/begin_arrow.svg';
import translations from '../../libs/translations/index.js';
-class TitleCard extends Component {
+export interface ComponentProps {
+ data: any
+ language: string
+ nextQuestion(): void
+}
+
+class TitleCard extends Component<ComponentProps, any> {
getContentHTML() {
let html = this.props.data.content ? this.props.data.content : translations.english[this.props.data.key]; |
4b34ca5b7fd4c88b464d6cec22ed4896e44f6329 | src/mergeProps.ts | src/mergeProps.ts | /** @module react-elementary/lib/mergeProps */
import classNames = require('classnames')
import { mergeWithKey } from 'ramda'
export interface IReducers { [key: string]: (...args: any[]) => any }
function customizeMerges(reducers: IReducers) {
return function mergeCustomizer(key: string, ...values: any[]) {
const reducer = reducers[key]
if (typeof reducer === 'function') {
return reducer(...values)
}
return values[values.length - 1]
}
}
/**
* Takes a map of reducer function and returns a merge function.
* @param {object.<function>} reducers - a map of keys to functions
* @return {function} - merges the props of a number of
* objects
*/
export function createCustomMerge(reducers: IReducers) {
const mergeCustomizer = customizeMerges(reducers)
return function mergeProps(...objs: object[]) {
return objs.reduce(mergeWithKey(mergeCustomizer))
}
}
/**
* Merges a number of objects, applying the classnames library to the className
* prop.
* @function
* @param {...object} objs - the objects to be merged
* @return {object} - the result of the merge
*/
export default createCustomMerge({ className: classNames })
| /** @module react-elementary/lib/mergeProps */
import classNames = require('classnames')
import {
apply,
evolve,
map,
mapObjIndexed,
merge,
mergeAll,
nth,
pickBy,
pipe,
pluck,
prop,
unapply,
} from 'ramda'
export interface IReducers {
[key: string]: (...args: any[]) => any
}
function isNotUndefined(x: any) {
return typeof x !== 'undefined'
}
/**
* Takes a map of reducer function and returns a merge function.
* @param {object.<function>} reducers - a map of keys to functions
* @return {function} - merges the props of a number of
* objects
*/
export function createCustomMerge(reducers: IReducers) {
return function mergeProps(...objs: object[]) {
const merged = mergeAll(objs)
const plucked = mapObjIndexed(
pipe(unapply(nth(1)), key => pluck(key, objs).filter(isNotUndefined)),
reducers,
)
const evolved = evolve(
map(apply, reducers),
pickBy(prop('length'), plucked),
)
return merge(merged, evolved)
}
}
/**
* Merges a number of objects, applying the classnames library to the className
* prop.
* @function
* @param {...object} objs - the objects to be merged
* @return {object} - the result of the merge
*/
export default createCustomMerge({ className: classNames })
| Rewrite to apply functions once | Rewrite to apply functions once
| TypeScript | mit | thirdhand/react-elementary,thirdhand/react-elementary | ---
+++
@@ -1,18 +1,27 @@
/** @module react-elementary/lib/mergeProps */
import classNames = require('classnames')
-import { mergeWithKey } from 'ramda'
+import {
+ apply,
+ evolve,
+ map,
+ mapObjIndexed,
+ merge,
+ mergeAll,
+ nth,
+ pickBy,
+ pipe,
+ pluck,
+ prop,
+ unapply,
+} from 'ramda'
-export interface IReducers { [key: string]: (...args: any[]) => any }
+export interface IReducers {
+ [key: string]: (...args: any[]) => any
+}
-function customizeMerges(reducers: IReducers) {
- return function mergeCustomizer(key: string, ...values: any[]) {
- const reducer = reducers[key]
- if (typeof reducer === 'function') {
- return reducer(...values)
- }
- return values[values.length - 1]
- }
+function isNotUndefined(x: any) {
+ return typeof x !== 'undefined'
}
/**
@@ -22,9 +31,17 @@
* objects
*/
export function createCustomMerge(reducers: IReducers) {
- const mergeCustomizer = customizeMerges(reducers)
return function mergeProps(...objs: object[]) {
- return objs.reduce(mergeWithKey(mergeCustomizer))
+ const merged = mergeAll(objs)
+ const plucked = mapObjIndexed(
+ pipe(unapply(nth(1)), key => pluck(key, objs).filter(isNotUndefined)),
+ reducers,
+ )
+ const evolved = evolve(
+ map(apply, reducers),
+ pickBy(prop('length'), plucked),
+ )
+ return merge(merged, evolved)
}
}
|
f08219d1d5317ca30dbadaf98dbe44aa66c80881 | client/imports/band/band.module.ts | client/imports/band/band.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { SongModule } from '../song/song.module';
import { BandComponent } from './band.component';
import { BandRoutingModule } from './band-routing.module';
@NgModule({
imports: [
CommonModule,
MaterialModule,
FlexLayoutModule,
SongModule,
BandRoutingModule
],
declarations: [
BandComponent
]
})
export class BandModule {}
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { TranslateModule } from '@ngx-translate/core';
import { SongModule } from '../song/song.module';
import { BandComponent } from './band.component';
import { BandRoutingModule } from './band-routing.module';
@NgModule({
imports: [
CommonModule,
MaterialModule,
FlexLayoutModule,
TranslateModule,
SongModule,
BandRoutingModule
],
declarations: [
BandComponent
]
})
export class BandModule {}
| Add missing TranslateModule in BandModule | Add missing TranslateModule in BandModule
| TypeScript | agpl-3.0 | singularities/song-pot,singularities/song-pot,singularities/songs-pot,singularities/songs-pot,singularities/songs-pot,singularities/song-pot | ---
+++
@@ -2,6 +2,7 @@
import { CommonModule } from '@angular/common';
import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
+import { TranslateModule } from '@ngx-translate/core';
import { SongModule } from '../song/song.module';
@@ -14,6 +15,7 @@
CommonModule,
MaterialModule,
FlexLayoutModule,
+ TranslateModule,
SongModule,
BandRoutingModule
], |
4a52da43a151e26a05946b5d60eb07841fc4160b | frontend/src/app/app-routing.module.ts | frontend/src/app/app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BuildsPage } from '@page/builds/builds.page';
import { ChampionPage } from '@page/champion/champion.page';
import { ChampionsPage } from '@page/champions/champions.page';
const routes: Routes = [
{ path: 'builds', redirectTo: '/champions', pathMatch: 'full' },
{ path: 'builds/:buildId', component: BuildsPage },
{ path: 'champions', component: ChampionsPage },
{ path: 'champions/:name', component: ChampionPage },
{ path: '', redirectTo: '/champions', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
| import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BuildsPage } from '@page/builds/builds.page';
import { ChampionPage } from '@page/champion/champion.page';
import { ChampionsPage } from '@page/champions/champions.page';
import { NotFoundPage } from '@page/error/not-found.page';
const routes: Routes = [
{ path: 'builds', redirectTo: '/champions', pathMatch: 'full' },
{ path: 'builds/:buildId', component: BuildsPage },
{ path: 'champions', component: ChampionsPage },
{ path: 'champions/:name', component: ChampionPage },
{ path: '', redirectTo: '/champions', pathMatch: 'full' },
{ path: '**', component: NotFoundPage }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
| Set ** path to NotFoundPage | Set ** path to NotFoundPage
| TypeScript | mit | drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild | ---
+++
@@ -4,6 +4,7 @@
import { BuildsPage } from '@page/builds/builds.page';
import { ChampionPage } from '@page/champion/champion.page';
import { ChampionsPage } from '@page/champions/champions.page';
+import { NotFoundPage } from '@page/error/not-found.page';
const routes: Routes = [
{ path: 'builds', redirectTo: '/champions', pathMatch: 'full' },
@@ -11,6 +12,7 @@
{ path: 'champions', component: ChampionsPage },
{ path: 'champions/:name', component: ChampionPage },
{ path: '', redirectTo: '/champions', pathMatch: 'full' },
+ { path: '**', component: NotFoundPage }
];
@NgModule({ |
d9dad52a0f837d2a7f73062a686943808cee543e | src/client/web/components/PathwayDisplay/PrerequisiteBox/JobGroupBox.tsx | src/client/web/components/PathwayDisplay/PrerequisiteBox/JobGroupBox.tsx | import * as React from 'react'
import text from '../../../../utils/text'
import { JobClassification, JobGroup } from '../../../../../definitions/auxiliary/JobClassification'
import data from '../../../../../data'
function getParentClass(jobGroup: JobGroup): JobClassification | null {
for (const region of data.regions) {
if (region.jobClassification) {
const jobClass = region.jobClassification
if (jobGroup.parentClassificationSystemId === jobClass.classificationSystemId) {
return jobClass
}
}
}
return null
}
const jobClassStyle = {
textDecoration: 'none',
fontWeight: 'bolder',
} as React.CSSProperties
const JobGroupBox = (props: { jobGroup: JobGroup }) => {
const jobGroup = props.jobGroup
const parentClass = getParentClass(jobGroup)
return (
<div>
<a style={jobClassStyle} href={jobGroup.reference && jobGroup.reference.url}>
{parentClass && text(parentClass.titleShort)}
{'-'}
{jobGroup.specification}
</a>
{' '}
{text(props.jobGroup.description)}
</div>
)
}
export default JobGroupBox
| import * as React from 'react'
import text from '../../../../utils/text'
import { JobClassification, JobGroup } from '../../../../../definitions/auxiliary/JobClassification'
import data from '../../../../../data'
function getParentClass(jobGroup: JobGroup): JobClassification | null {
for (const region of data.regions) {
if (region.jobClassification) {
const jobClass = region.jobClassification
if (jobGroup.parentClassificationSystemId === jobClass.classificationSystemId) {
return jobClass
}
}
}
return null
}
const JobGroupBox = (props: { jobGroup: JobGroup }) => {
const jobGroup = props.jobGroup
const parentClass = getParentClass(jobGroup)
return (
<a
href={jobGroup.reference && jobGroup.reference.url}
target="_blank"
style={{fontWeight: 'bolder'}}
>
{parentClass && text(parentClass.titleShort)}
{'-'}
{jobGroup.specification}
{' '}
<span style={{fontWeight: 'lighter'}}>
{text(props.jobGroup.description)}
</span>
</a>
)
}
export default JobGroupBox
| Improve link style and code style | Improve link style and code style
Signed-off-by: Andy Shu <[email protected]>
| TypeScript | agpl-3.0 | wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate | ---
+++
@@ -15,24 +15,23 @@
return null
}
-const jobClassStyle = {
- textDecoration: 'none',
- fontWeight: 'bolder',
-} as React.CSSProperties
-
const JobGroupBox = (props: { jobGroup: JobGroup }) => {
const jobGroup = props.jobGroup
const parentClass = getParentClass(jobGroup)
return (
- <div>
- <a style={jobClassStyle} href={jobGroup.reference && jobGroup.reference.url}>
- {parentClass && text(parentClass.titleShort)}
- {'-'}
- {jobGroup.specification}
- </a>
+ <a
+ href={jobGroup.reference && jobGroup.reference.url}
+ target="_blank"
+ style={{fontWeight: 'bolder'}}
+ >
+ {parentClass && text(parentClass.titleShort)}
+ {'-'}
+ {jobGroup.specification}
{' '}
- {text(props.jobGroup.description)}
- </div>
+ <span style={{fontWeight: 'lighter'}}>
+ {text(props.jobGroup.description)}
+ </span>
+ </a>
)
}
|
7212ad8f8b4d5eb7cb2916cef5f898c1c7d8797b | app/app.ts | app/app.ts | import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type} from 'angular2/core';
@App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
rootPage: Type = TabsPage;
constructor(platform: Platform) {
platform.ready().then(() => {
// The platform is now ready. Note: if this callback fails to fire, follow
// the Troubleshooting guide for a number of possible solutions:
//
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
//
// First, let's hide the keyboard accessory bar (only works natively) since
// that's a better default:
//
// Keyboard.setAccessoryBarVisible(false);
//
// For example, we might change the StatusBar color. This one below is
// good for dark backgrounds and light text:
// StatusBar.setStyle(StatusBar.LIGHT_CONTENT)
});
}
}
| import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type, enableProdMode} from 'angular2/core';
enableProdMode();
@App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
rootPage: Type = TabsPage;
constructor(platform: Platform) {
platform.ready().then(() => {
// The platform is now ready. Note: if this callback fails to fire, follow
// the Troubleshooting guide for a number of possible solutions:
//
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
//
// First, let's hide the keyboard accessory bar (only works natively) since
// that's a better default:
//
// Keyboard.setAccessoryBarVisible(false);
//
// For example, we might change the StatusBar color. This one below is
// good for dark backgrounds and light text:
// StatusBar.setStyle(StatusBar.LIGHT_CONTENT)
});
}
}
| Enable production mode in Angular2 | Enable production mode in Angular2
| TypeScript | mit | neilgoldman305/marvin-ui,neilgoldman305/marvin-ui,neilgoldman305/marvin-ui | ---
+++
@@ -2,32 +2,32 @@
import {TabsPage} from './pages/tabs/tabs';
// https://angular.io/docs/ts/latest/api/core/Type-interface.html
-import {Type} from 'angular2/core';
-
+import {Type, enableProdMode} from 'angular2/core';
+enableProdMode();
@App({
- template: '<ion-nav [root]="rootPage"></ion-nav>',
- config: {} // http://ionicframework.com/docs/v2/api/config/Config/
+ template: '<ion-nav [root]="rootPage"></ion-nav>',
+ config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
- rootPage: Type = TabsPage;
+ rootPage: Type = TabsPage;
- constructor(platform: Platform) {
- platform.ready().then(() => {
- // The platform is now ready. Note: if this callback fails to fire, follow
- // the Troubleshooting guide for a number of possible solutions:
- //
- // Okay, so the platform is ready and our plugins are available.
- // Here you can do any higher level native things you might need.
- //
- // First, let's hide the keyboard accessory bar (only works natively) since
- // that's a better default:
- //
- // Keyboard.setAccessoryBarVisible(false);
- //
- // For example, we might change the StatusBar color. This one below is
- // good for dark backgrounds and light text:
- // StatusBar.setStyle(StatusBar.LIGHT_CONTENT)
- });
- }
+ constructor(platform: Platform) {
+ platform.ready().then(() => {
+ // The platform is now ready. Note: if this callback fails to fire, follow
+ // the Troubleshooting guide for a number of possible solutions:
+ //
+ // Okay, so the platform is ready and our plugins are available.
+ // Here you can do any higher level native things you might need.
+ //
+ // First, let's hide the keyboard accessory bar (only works natively) since
+ // that's a better default:
+ //
+ // Keyboard.setAccessoryBarVisible(false);
+ //
+ // For example, we might change the StatusBar color. This one below is
+ // good for dark backgrounds and light text:
+ // StatusBar.setStyle(StatusBar.LIGHT_CONTENT)
+ });
+ }
} |
9d269849987fbe374b0f76a4893fdf9d867b8b84 | editors/code/src/utils/processes.ts | editors/code/src/utils/processes.ts | 'use strict';
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { join } from 'path';
const isWindows = process.platform === 'win32';
const isMacintosh = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
export function terminate(process: ChildProcess, cwd?: string): boolean {
if (isWindows) {
try {
// This we run in Atom execFileSync is available.
// Ignore stderr since this is otherwise piped to parent.stderr
// which might be already closed.
const options: any = {
stdio: ['pipe', 'pipe', 'ignore']
};
if (cwd) {
options.cwd = cwd;
}
cp.execFileSync(
'taskkill',
['/T', '/F', '/PID', process.pid.toString()],
options
);
return true;
} catch (err) {
return false;
}
} else if (isLinux || isMacintosh) {
try {
const cmd = join(__dirname, 'terminateProcess.sh');
const result = cp.spawnSync(cmd, [process.pid.toString()]);
return result.error ? false : true;
} catch (err) {
return false;
}
} else {
process.kill('SIGKILL');
return true;
}
}
| 'use strict';
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { join } from 'path';
const isWindows = process.platform === 'win32';
const isMacintosh = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
// this is very complex, but is basically copy-pased from VSCode implementation here:
// https://github.com/Microsoft/vscode-languageserver-node/blob/dbfd37e35953ad0ee14c4eeced8cfbc41697b47e/client/src/utils/processes.ts#L15
// And see discussion at
// https://github.com/rust-analyzer/rust-analyzer/pull/1079#issuecomment-478908109
export function terminate(process: ChildProcess, cwd?: string): boolean {
if (isWindows) {
try {
// This we run in Atom execFileSync is available.
// Ignore stderr since this is otherwise piped to parent.stderr
// which might be already closed.
const options: any = {
stdio: ['pipe', 'pipe', 'ignore']
};
if (cwd) {
options.cwd = cwd;
}
cp.execFileSync(
'taskkill',
['/T', '/F', '/PID', process.pid.toString()],
options
);
return true;
} catch (err) {
return false;
}
} else if (isLinux || isMacintosh) {
try {
const cmd = join(__dirname, 'terminateProcess.sh');
const result = cp.spawnSync(cmd, [process.pid.toString()]);
return result.error ? false : true;
} catch (err) {
return false;
}
} else {
process.kill('SIGKILL');
return true;
}
}
| Add terminate process implemntation note | Add terminate process implemntation note
| TypeScript | apache-2.0 | rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer,rust-analyzer/rust-analyzer | ---
+++
@@ -8,6 +8,13 @@
const isWindows = process.platform === 'win32';
const isMacintosh = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
+
+// this is very complex, but is basically copy-pased from VSCode implementation here:
+// https://github.com/Microsoft/vscode-languageserver-node/blob/dbfd37e35953ad0ee14c4eeced8cfbc41697b47e/client/src/utils/processes.ts#L15
+
+// And see discussion at
+// https://github.com/rust-analyzer/rust-analyzer/pull/1079#issuecomment-478908109
+
export function terminate(process: ChildProcess, cwd?: string): boolean {
if (isWindows) {
try { |
550b7714b4f680eab52c006d19164b5676925b94 | src/angular/projects/spark-angular/src/lib/components/sprk-list-item/sprk-list-item.component.ts | src/angular/projects/spark-angular/src/lib/components/sprk-list-item/sprk-list-item.component.ts | import { Component, Input, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'sprk-list-item',
template: `
<ng-template>
<ng-content></ng-content>
</ng-template>
`
})
export class SprkListItemComponent {
@Input()
analyticsString: string;
@Input()
idString: string;
@Input()
additionalClasses: string;
@ViewChild(TemplateRef) content: TemplateRef<any>;
}
| import { Component, Input, TemplateRef, ViewChild } from '@angular/core';
@Component({
selector: 'sprk-list-item',
template: `
<ng-template>
<ng-content></ng-content>
</ng-template>
`
})
export class SprkListItemComponent {
@Input()
analyticsString: string;
@Input()
idString: string;
@Input()
additionalClasses: string;
@ViewChild(TemplateRef, { static: true }) content: TemplateRef<any>;
}
| Add static true for ViewChild for Angular 8 | Add static true for ViewChild for Angular 8
| TypeScript | mit | sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system | ---
+++
@@ -16,5 +16,5 @@
@Input()
additionalClasses: string;
- @ViewChild(TemplateRef) content: TemplateRef<any>;
+ @ViewChild(TemplateRef, { static: true }) content: TemplateRef<any>;
} |
3e812032da7246f4056190dbef88fb0c85e0be7f | console/src/app/core/services/charts-provider-service/charts-provider.service.ts | console/src/app/core/services/charts-provider-service/charts-provider.service.ts | import { Injectable } from '@angular/core';
import { PrometheusApiService } from '../prometheus-api/prometheus-api.service';
import { MongooseChartDao } from '../../models/chart/mongoose-chart-interface/mongoose-chart-dao.model';
@Injectable({
providedIn: 'root'
})
export class ChartsProviderService {
private mongooseChartDao: MongooseChartDao;
constructor(prometheusApiService: PrometheusApiService) {
// NOTE: Prometheus API service is data provider for Mongoose Charts.
this.mongooseChartDao = new MongooseChartDao(prometheusApiService);
}
}
| import { Injectable } from '@angular/core';
import { PrometheusApiService } from '../prometheus-api/prometheus-api.service';
import { MongooseChartDao } from '../../models/chart/mongoose-chart-interface/mongoose-chart-dao.model';
import { MongooseMetric } from '../../models/chart/mongoose-metric.model';
import { MongooseChartsRepository } from '../../models/chart/mongoose-charts-repository';
import { MongooseDurationChart } from '../../models/chart/duration/mongoose-duration-chart.model';
import { MongooseLatencyChart } from '../../models/chart/latency/mongoose-latency-chart.model';
import { MongooseBandwidthChart } from '../../models/chart/bandwidth/mongoose-bandwidth-chart.model';
import { MongooseThroughputChart } from '../../models/chart/throughput/mongoose-throughput-chart.model';
@Injectable({
providedIn: 'root'
})
export class ChartsProviderService {
private mongooseChartDao: MongooseChartDao;
private durationChart: MongooseDurationChart;
private latencyChart: MongooseLatencyChart;
private bandwidthChart: MongooseBandwidthChart;
private throughputChart: MongooseThroughputChart;
constructor(prometheusApiService: PrometheusApiService) {
// NOTE: Prometheus API service is data provider for Mongoose Charts.
this.mongooseChartDao = new MongooseChartDao(prometheusApiService);
this.configureMongooseCharts();
}
// MARK: - Public
// MARK: - Private
private updateLatencyChart(perdiodOfLatencyUpdateMs: number, recordLoadStepId: string) {
this.mongooseChartDao.getLatencyMax(perdiodOfLatencyUpdateMs, recordLoadStepId).subscribe((maxLatencyResult: MongooseMetric) => {
this.mongooseChartDao.getLatencyMin(perdiodOfLatencyUpdateMs, recordLoadStepId).subscribe((minLatencyResult: MongooseMetric) => {
let latencyRelatedMetrics = [maxLatencyResult, minLatencyResult];
this.latencyChart.updateChart(recordLoadStepId, latencyRelatedMetrics);
});
});
}
private configureMongooseCharts() {
let mongooseChartRepository = new MongooseChartsRepository(this.mongooseChartDao);
this.durationChart = mongooseChartRepository.getDurationChart();
this.latencyChart = mongooseChartRepository.getLatencyChart();
this.bandwidthChart = mongooseChartRepository.getBandwidthChart();
this.throughputChart = mongooseChartRepository.getThoughputChart();
}
}
| Add charts to ChartsProviderService. Add larency chart updation method to it. | Add charts to ChartsProviderService. Add larency chart updation method to it.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -1,6 +1,12 @@
import { Injectable } from '@angular/core';
import { PrometheusApiService } from '../prometheus-api/prometheus-api.service';
import { MongooseChartDao } from '../../models/chart/mongoose-chart-interface/mongoose-chart-dao.model';
+import { MongooseMetric } from '../../models/chart/mongoose-metric.model';
+import { MongooseChartsRepository } from '../../models/chart/mongoose-charts-repository';
+import { MongooseDurationChart } from '../../models/chart/duration/mongoose-duration-chart.model';
+import { MongooseLatencyChart } from '../../models/chart/latency/mongoose-latency-chart.model';
+import { MongooseBandwidthChart } from '../../models/chart/bandwidth/mongoose-bandwidth-chart.model';
+import { MongooseThroughputChart } from '../../models/chart/throughput/mongoose-throughput-chart.model';
@Injectable({
providedIn: 'root'
@@ -9,8 +15,41 @@
private mongooseChartDao: MongooseChartDao;
+ private durationChart: MongooseDurationChart;
+ private latencyChart: MongooseLatencyChart;
+ private bandwidthChart: MongooseBandwidthChart;
+ private throughputChart: MongooseThroughputChart;
+
+
+
+
constructor(prometheusApiService: PrometheusApiService) {
// NOTE: Prometheus API service is data provider for Mongoose Charts.
this.mongooseChartDao = new MongooseChartDao(prometheusApiService);
- }
+ this.configureMongooseCharts();
+ }
+
+ // MARK: - Public
+
+
+ // MARK: - Private
+
+ private updateLatencyChart(perdiodOfLatencyUpdateMs: number, recordLoadStepId: string) {
+ this.mongooseChartDao.getLatencyMax(perdiodOfLatencyUpdateMs, recordLoadStepId).subscribe((maxLatencyResult: MongooseMetric) => {
+ this.mongooseChartDao.getLatencyMin(perdiodOfLatencyUpdateMs, recordLoadStepId).subscribe((minLatencyResult: MongooseMetric) => {
+ let latencyRelatedMetrics = [maxLatencyResult, minLatencyResult];
+ this.latencyChart.updateChart(recordLoadStepId, latencyRelatedMetrics);
+ });
+ });
+ }
+
+ private configureMongooseCharts() {
+ let mongooseChartRepository = new MongooseChartsRepository(this.mongooseChartDao);
+ this.durationChart = mongooseChartRepository.getDurationChart();
+ this.latencyChart = mongooseChartRepository.getLatencyChart();
+ this.bandwidthChart = mongooseChartRepository.getBandwidthChart();
+ this.throughputChart = mongooseChartRepository.getThoughputChart();
+ }
+
}
+ |
4fe61b060e307a634d912b9754e3bba77c9ae5fe | server/src/main/webapp/WEB-INF/rails/webpack/config/loaders/static-assets-loader.ts | server/src/main/webapp/WEB-INF/rails/webpack/config/loaders/static-assets-loader.ts | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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 {ConfigOptions} from "config/variables";
import webpack from "webpack";
export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: configOptions.production ? "media/" : "fonts/"
}
}
]
};
}
| /*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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 {ConfigOptions} from "config/variables";
import webpack from "webpack";
export function getStaticAssetsLoader(configOptions: ConfigOptions): webpack.RuleSetRule {
return {
test: /\.(woff|woff2|ttf|eot|svg|png|gif|jpeg|jpg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
outputPath: configOptions.production ? "media/" : "fonts/",
esModule: false
}
}
]
};
}
| Fix build that broke because of `file-loader` upgrade. | Fix build that broke because of `file-loader` upgrade.
| TypeScript | apache-2.0 | marques-work/gocd,arvindsv/gocd,marques-work/gocd,ketan/gocd,gocd/gocd,marques-work/gocd,gocd/gocd,arvindsv/gocd,ibnc/gocd,marques-work/gocd,GaneshSPatil/gocd,marques-work/gocd,ibnc/gocd,GaneshSPatil/gocd,gocd/gocd,Skarlso/gocd,Skarlso/gocd,ketan/gocd,arvindsv/gocd,ketan/gocd,Skarlso/gocd,ibnc/gocd,gocd/gocd,Skarlso/gocd,ketan/gocd,GaneshSPatil/gocd,marques-work/gocd,ketan/gocd,arvindsv/gocd,ibnc/gocd,gocd/gocd,Skarlso/gocd,Skarlso/gocd,ibnc/gocd,GaneshSPatil/gocd,ibnc/gocd,arvindsv/gocd,GaneshSPatil/gocd,gocd/gocd,ketan/gocd,arvindsv/gocd,GaneshSPatil/gocd | ---
+++
@@ -25,7 +25,8 @@
loader: "file-loader",
options: {
name: configOptions.production ? "[name]-[hash].[ext]" : "[name].[ext]",
- outputPath: configOptions.production ? "media/" : "fonts/"
+ outputPath: configOptions.production ? "media/" : "fonts/",
+ esModule: false
}
}
] |
5e6e9212aac981e9fe7801d293c125cf9371d509 | src/package-reader.ts | src/package-reader.ts | import * as fs from "fs";
/**
* Typing for the fields of package.json we care about
*/
export interface PackageJson {
readonly main: string;
}
export interface ReadPackageJson {
(file: string): PackageJson | undefined;
}
/**
* @param packageJsonPath Path to package.json
* @param loadPackageJson Function that reads and parses package.json.
* @param fileExists Function that checks for existance of a file.
* @returns string
*/
export function readPackage(
packageJsonPath: string,
loadPackageJson: ReadPackageJson = loadJsonFromDisk,
fileExists: (path: string) => boolean = fs.existsSync
): PackageJson | undefined {
return (
(packageJsonPath.match(/package\.json$/) &&
fileExists(packageJsonPath) &&
loadPackageJson(packageJsonPath)) ||
undefined
);
}
function loadJsonFromDisk(file: string): PackageJson {
// tslint:disable-next-line:no-require-imports
const packageJson = require(file);
return packageJson;
}
| /**
* Typing for the fields of package.json we care about
*/
export interface PackageJson {
readonly main: string;
}
export interface ReadPackageJson {
(file: string): PackageJson | undefined;
}
/**
* @param packageJsonPath Path to package.json
* @param readPackageJson Function that reads and parses package.json.
* @param fileExists Function that checks for existance of a file.
* @returns string
*/
export function readPackage(
packageJsonPath: string,
readPackageJson: ReadPackageJson = loadJsonFromDisk,
fileExists: (path: string) => boolean
): PackageJson | undefined {
return (
(packageJsonPath.match(/package\.json$/) &&
fileExists(packageJsonPath) &&
readPackageJson(packageJsonPath)) ||
undefined
);
}
function loadJsonFromDisk(file: string): PackageJson {
// tslint:disable-next-line:no-require-imports
const packageJson = require(file);
return packageJson;
}
| Make parameter required and rename | Make parameter required and rename
| TypeScript | mit | dividab/tsconfig-paths,jonaskello/tsconfig-paths,dividab/tsconfig-paths,jonaskello/tsconfig-paths | ---
+++
@@ -1,5 +1,3 @@
-import * as fs from "fs";
-
/**
* Typing for the fields of package.json we care about
*/
@@ -13,19 +11,19 @@
/**
* @param packageJsonPath Path to package.json
- * @param loadPackageJson Function that reads and parses package.json.
+ * @param readPackageJson Function that reads and parses package.json.
* @param fileExists Function that checks for existance of a file.
* @returns string
*/
export function readPackage(
packageJsonPath: string,
- loadPackageJson: ReadPackageJson = loadJsonFromDisk,
- fileExists: (path: string) => boolean = fs.existsSync
+ readPackageJson: ReadPackageJson = loadJsonFromDisk,
+ fileExists: (path: string) => boolean
): PackageJson | undefined {
return (
(packageJsonPath.match(/package\.json$/) &&
fileExists(packageJsonPath) &&
- loadPackageJson(packageJsonPath)) ||
+ readPackageJson(packageJsonPath)) ||
undefined
);
} |
c5d9862102c5ba69c4a27a6e89a42a15bab28362 | MonitoredSocket.ts | MonitoredSocket.ts | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this)
);
this.socket.on("error", this.onConnectFailure.bind(this));
}
onConnectSuccess(): void {
this.isUp = true;
console.log("CONNECTED"); // DEBUG
// We're good! Close the socket
this.socket.end();
}
onConnectFailure(): void {
this.isUp = false;
console.log("NOT CONNECTED"); // DEBUG
// Cleanup
this.socket.destroy();
}
toString(): string {
return "Monitoring " + this.endpoint
+ " on port " + this.port;
}
}
export = MonitoredSocket; | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(successCallback : void, failCallback : void): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this, successCallback)
);
this.socket.on("error", this.onConnectFailure.bind(this, failCallback));
}
onConnectSuccess(callback : {(): void}) {
this.isUp = true;
// We're good! Close the socket
this.socket.end();
callback();
}
onConnectFailure(callback: {(): void }) {
this.isUp = false;
// Cleanup
this.socket.destroy();
callback();
}
toString(): string {
return "Monitoring " + this.endpoint
+ " on port " + this.port;
}
}
export = MonitoredSocket; | Use callbacks instead of trying to make socket calls sync | Use callbacks instead of trying to make socket calls sync
| TypeScript | mit | OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up | ---
+++
@@ -18,30 +18,32 @@
this.socket = new net.Socket();
}
- connect(): void {
+ connect(successCallback : void, failCallback : void): void {
this.socket.connect(
this.port,
this.endpoint,
- this.onConnectSuccess.bind(this)
+ this.onConnectSuccess.bind(this, successCallback)
);
- this.socket.on("error", this.onConnectFailure.bind(this));
+ this.socket.on("error", this.onConnectFailure.bind(this, failCallback));
}
- onConnectSuccess(): void {
+ onConnectSuccess(callback : {(): void}) {
this.isUp = true;
- console.log("CONNECTED"); // DEBUG
// We're good! Close the socket
this.socket.end();
+
+ callback();
}
- onConnectFailure(): void {
+ onConnectFailure(callback: {(): void }) {
this.isUp = false;
- console.log("NOT CONNECTED"); // DEBUG
// Cleanup
this.socket.destroy();
+
+ callback();
}
toString(): string { |
53dad32841ddb39721dd6a3c44de083d507a6ee6 | test/browser/parallel.integration.specs.ts | test/browser/parallel.integration.specs.ts | import parallel from "../../src/browser/index";
describe("ParallelIntegration", function () {
it("reduce waits for the result to be computed on the workers and returns the reduced value", function (done) {
parallel
.range(100)
.reduce(0, (memo: number, value: number) => {
for (let i = 0; i < 1e7; ++i) {
// busy wait
}
return memo + value;
})
.then(result => {
expect(result).toBe(4950);
done();
});
}, 10000);
it("maps an input array to an output array", function (done) {
const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
parallel.collection(data)
.map(value => value ** 2)
.value()
.then(result => {
expect(result).toEqual([0, 1, 4, 9, 16, 25, 36, 49, 64, 81]);
done();
});
});
}); | import parallel from "../../src/browser/index";
describe("ParallelIntegration", function () {
it("reduce waits for the result to be computed on the workers and returns the reduced value", function (done) {
parallel
.range(100)
.reduce(0, (memo: number, value: number) => memo + value)
.then(result => {
expect(result).toBe(4950);
done();
});
}, 10000);
it("maps an input array to an output array", function (done) {
const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
parallel.collection(data)
.map(value => value ** 2)
.value()
.then(result => {
expect(result).toEqual([0, 1, 4, 9, 16, 25, 36, 49, 64, 81]);
done();
});
});
}); | Remove busy wait to avoid timeout on browserstack | Remove busy wait to avoid timeout on browserstack
| TypeScript | mit | MichaReiser/parallel.es,MichaReiser/parallel.es,DatenMetzgerX/parallel.es,MichaReiser/parallel.es,DatenMetzgerX/parallel.es,DatenMetzgerX/parallel.es | ---
+++
@@ -4,13 +4,7 @@
it("reduce waits for the result to be computed on the workers and returns the reduced value", function (done) {
parallel
.range(100)
- .reduce(0, (memo: number, value: number) => {
- for (let i = 0; i < 1e7; ++i) {
- // busy wait
- }
-
- return memo + value;
- })
+ .reduce(0, (memo: number, value: number) => memo + value)
.then(result => {
expect(result).toBe(4950);
done(); |
033cb0ce0b459fda8db02e77cdf17f9f4e91d5bd | app/test/unit/path-test.ts | app/test/unit/path-test.ts | import { encodePathAsUrl } from '../../src/lib/path'
describe('path', () => {
describe('encodePathAsUrl', () => {
if (__WIN32__) {
it('normalizes path separators on Windows', () => {
const dirName =
'C:/Users/shiftkey\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'folder/file.html')
expect(uri.startsWith('file:///C:/Users/shiftkey/AppData/Local/'))
})
it('encodes spaces and hashes', () => {
const dirName =
'C:/Users/The Kong #2\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'index.html')
expect(uri.startsWith('file:///C:/Users/The%20Kong%20%232/'))
})
}
it('fails, hard', () => {
expect(false).toBe(true)
})
if (__DARWIN__ || __LINUX__) {
it('encodes spaces and hashes', () => {
const dirName =
'/Users/The Kong #2\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'index.html')
expect(uri.startsWith('file:////Users/The%20Kong%20%232/'))
})
}
})
})
| import { encodePathAsUrl } from '../../src/lib/path'
describe('path', () => {
describe('encodePathAsUrl', () => {
if (__WIN32__) {
it('normalizes path separators on Windows', () => {
const dirName =
'C:/Users/shiftkey\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'folder/file.html')
expect(uri.startsWith('file:///C:/Users/shiftkey/AppData/Local/'))
})
it('encodes spaces and hashes', () => {
const dirName =
'C:/Users/The Kong #2\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'index.html')
expect(uri.startsWith('file:///C:/Users/The%20Kong%20%232/'))
})
}
if (__DARWIN__ || __LINUX__) {
it('encodes spaces and hashes', () => {
const dirName =
'/Users/The Kong #2\\AppData\\Local\\GitHubDesktop\\app-1.0.4\\resources\\app'
const uri = encodePathAsUrl(dirName, 'index.html')
expect(uri.startsWith('file:////Users/The%20Kong%20%232/'))
})
}
})
})
| Remove test that was failing on purpose | Remove test that was failing on purpose
| TypeScript | mit | say25/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,kactus-io/kactus,say25/desktop,artivilla/desktop,artivilla/desktop | ---
+++
@@ -18,10 +18,6 @@
})
}
- it('fails, hard', () => {
- expect(false).toBe(true)
- })
-
if (__DARWIN__ || __LINUX__) {
it('encodes spaces and hashes', () => {
const dirName = |
7e9b7d0d72ad92f54951d264a7bd282bd07ddff2 | lib/index.ts | lib/index.ts | export * from './src/angular-svg-icon.module';
export * from './src/svg-icon-registry.service';
export * from './src/svg-icon.component';
| export * from './src/angular-svg-icon.module';
export * from './src/svg-icon-registry.service';
export * from './src/svg-icon.component';
export * from './src/svg-loader';
| Add SVG loader to exports. | universal: Add SVG loader to exports.
| TypeScript | mit | czeckd/angular-svg-icon,czeckd/angular2-svg-icon,czeckd/angular2-svg-icon,czeckd/angular-svg-icon,czeckd/angular2-svg-icon,czeckd/angular-svg-icon | ---
+++
@@ -1,4 +1,4 @@
export * from './src/angular-svg-icon.module';
export * from './src/svg-icon-registry.service';
export * from './src/svg-icon.component';
-
+export * from './src/svg-loader'; |
f8400e0f01ed045d2c609d12fb1f6c4c040991f3 | src/Home/Home.tsx | src/Home/Home.tsx | import * as React from 'react';
import TurnatoBar from '../App/TurnatoBar';
import Header from './Header';
import GamesSection from './GamesSection';
class Home extends React.Component<{}, {}> {
render() {
return (
<TurnatoBar>
<Header />
<GamesSection />
<p style={{ fontSize: '12px', textAlign: 'center' }}>
Made with ♥ -
<a
href="https://github.com/Felizardo/turnato"
target="_blank"
rel="noopener"
>
GitHub
</a>
-
<a
href="/about"
rel="noopener"
>
About
</a>
</p>
</TurnatoBar>
);
}
}
export default Home;
| import * as React from 'react';
import TurnatoBar from '../App/TurnatoBar';
import Header from './Header';
import GamesSection from './GamesSection';
import { Link } from 'react-router-dom';
class Home extends React.Component<{}, {}> {
render() {
return (
<TurnatoBar>
<Header />
<GamesSection />
<p style={{ fontSize: '12px', textAlign: 'center' }}>
Made with ♥ -
<a
href="https://github.com/Felizardo/turnato"
target="_blank"
rel="noopener"
>
GitHub
</a>
-
<Link
to="/about"
>
About
</Link>
</p>
</TurnatoBar>
);
}
}
export default Home;
| Use <Link> instead of <a> | Use <Link> instead of <a>
| TypeScript | agpl-3.0 | Felizardo/turnato,Felizardo/turnato,Felizardo/turnato | ---
+++
@@ -2,6 +2,7 @@
import TurnatoBar from '../App/TurnatoBar';
import Header from './Header';
import GamesSection from './GamesSection';
+import { Link } from 'react-router-dom';
class Home extends React.Component<{}, {}> {
render() {
@@ -19,12 +20,11 @@
GitHub
</a>
-
- <a
- href="/about"
- rel="noopener"
+ <Link
+ to="/about"
>
About
- </a>
+ </Link>
</p>
</TurnatoBar>
); |
3cc5f55cdc15d7e0d043161b7e4b68e76bd90644 | projects/alveo-transcriber/src/lib/shared/annotation-exporter.service.spec.ts | projects/alveo-transcriber/src/lib/shared/annotation-exporter.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { AnnotationExporterService } from './annotation-exporter.service';
describe('AnnotationExporterService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AnnotationExporterService]
});
});
it('should be created', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
expect(service).toBeTruthy();
}));
});
| import { TestBed, inject } from '@angular/core/testing';
import { Annotation } from './annotation';
import { AnnotationExporterService } from './annotation-exporter.service';
describe('AnnotationExporterService', () => {
function generateAnnotations(): Array<Annotation> {
let annotations = new Array<Annotation>();
for (let i=0; i<5; i++) {
annotations.push(new Annotation(i.toString(), 0, 0, 'Speaker', 'caption', "unittest"))
}
return annotations;
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AnnotationExporterService]
});
});
it('should be created', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
expect(service).toBeTruthy();
}));
it('should create a valid csv download', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
const annotations = generateAnnotations();
let urlCreateObjectSpy = spyOn(URL, 'createObjectURL').and.callFake(
(blob) => {
expect(blob.type).toBe("text/csv");
let reader = new FileReader();
reader.onload = () => {
const csv = reader.result.split("\n");
expect(csv[0]).toBe('"id","start","end","speaker","caption","cap_type"');
for (const annotation in annotations) {
expect(csv[+annotation+1]).toBe("\"" + annotations[annotation].id + "\","
+ annotations[annotation].start.toString() + ","
+ annotations[annotation].end.toString() + ","
+ "\"" + annotations[annotation].speaker + "\","
+ "\"" + annotations[annotation].caption + "\","
+ "\"" + annotations[annotation].cap_type + "\""
);
}
}
reader.readAsText(blob);
}
);
// TODO filename?
let a = service.asCSV("test.csv", annotations);
}));
//JSON.parse
});
| Create CSV export unit test | Create CSV export unit test
| TypeScript | bsd-3-clause | Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber | ---
+++
@@ -1,8 +1,18 @@
import { TestBed, inject } from '@angular/core/testing';
+import { Annotation } from './annotation';
import { AnnotationExporterService } from './annotation-exporter.service';
+
describe('AnnotationExporterService', () => {
+ function generateAnnotations(): Array<Annotation> {
+ let annotations = new Array<Annotation>();
+ for (let i=0; i<5; i++) {
+ annotations.push(new Annotation(i.toString(), 0, 0, 'Speaker', 'caption', "unittest"))
+ }
+ return annotations;
+ }
+
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AnnotationExporterService]
@@ -12,4 +22,37 @@
it('should be created', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
expect(service).toBeTruthy();
}));
+
+ it('should create a valid csv download', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
+ const annotations = generateAnnotations();
+
+ let urlCreateObjectSpy = spyOn(URL, 'createObjectURL').and.callFake(
+ (blob) => {
+ expect(blob.type).toBe("text/csv");
+
+ let reader = new FileReader();
+ reader.onload = () => {
+ const csv = reader.result.split("\n");
+ expect(csv[0]).toBe('"id","start","end","speaker","caption","cap_type"');
+
+ for (const annotation in annotations) {
+ expect(csv[+annotation+1]).toBe("\"" + annotations[annotation].id + "\","
+ + annotations[annotation].start.toString() + ","
+ + annotations[annotation].end.toString() + ","
+ + "\"" + annotations[annotation].speaker + "\","
+ + "\"" + annotations[annotation].caption + "\","
+ + "\"" + annotations[annotation].cap_type + "\""
+ );
+ }
+ }
+ reader.readAsText(blob);
+ }
+ );
+
+ // TODO filename?
+
+ let a = service.asCSV("test.csv", annotations);
+ }));
+
+ //JSON.parse
}); |
841735c97c776f8d222e1c5ea885ccc4e5b38a60 | MonitoredSocket.ts | MonitoredSocket.ts | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(successCallback : void, failCallback : void): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this, successCallback)
);
this.socket.on("error", this.onConnectFailure.bind(this, failCallback));
}
onConnectSuccess(callback: {(sock: MonitoredSocket): void }) {
this.isUp = true;
// We're good! Close the socket
this.socket.end();
callback(this);
}
onConnectFailure(callback: {(sock: MonitoredSocket): void }) {
this.isUp = false;
// Cleanup
this.socket.destroy();
callback(this);
}
toString(): string {
return "Monitoring " + this.endpoint
+ " on port " + this.port;
}
}
export = MonitoredSocket; | import net = require("net");
/**
* Represents a given host and port. Handles checking whether a host
* is up or not, as well as if it is accessible on the given port.
*/
class MonitoredSocket {
/**
* Returns whether the host can be accessed on its port.
*/
public isUp: boolean;
private socket: net.Socket;
constructor(
public endpoint: string,
public port: number
) {
this.socket = new net.Socket();
}
connect(successCallback: { (sock: MonitoredSocket): void },
failCallback: { (sock: MonitoredSocket): void }): void {
this.socket.connect(
this.port,
this.endpoint,
this.onConnectSuccess.bind(this, successCallback)
);
this.socket.on("error", this.onConnectFailure.bind(this, failCallback));
}
onConnectSuccess(callback: {(sock: MonitoredSocket): void }) {
this.isUp = true;
// We're good! Close the socket
this.socket.end();
callback(this);
}
onConnectFailure(callback: {(sock: MonitoredSocket): void }) {
this.isUp = false;
// Cleanup
this.socket.destroy();
callback(this);
}
toString(): string {
return "Monitoring " + this.endpoint
+ " on port " + this.port;
}
}
export = MonitoredSocket; | Fix typing issues on callbacks | Fix typing issues on callbacks
| TypeScript | mit | OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up,OzuYatamutsu/is-my-server-up | ---
+++
@@ -18,7 +18,8 @@
this.socket = new net.Socket();
}
- connect(successCallback : void, failCallback : void): void {
+ connect(successCallback: { (sock: MonitoredSocket): void },
+ failCallback: { (sock: MonitoredSocket): void }): void {
this.socket.connect(
this.port,
this.endpoint, |
d6094b87df963609ce46a6dd0cee2999654072d6 | redux-logger/redux-logger-tests.ts | redux-logger/redux-logger-tests.ts | /// <reference path="./redux-logger.d.ts" />
import createLogger from 'redux-logger';
import { applyMiddleware, createStore } from 'redux'
let logger = createLogger();
let loggerWithOpts = createLogger({
actionTransformer: actn => actn,
collapsed: true,
duration: true,
level: 'error',
logger: console,
predicate: (getState, action) => true,
timestamp: true,
stateTransformer: state => state
});
let createStoreWithMiddleware = applyMiddleware(
logger, loggerWithOpts
)(createStore);
| /// <reference path="./redux-logger.d.ts" />
import * as createLogger from 'redux-logger';
import { applyMiddleware, createStore } from 'redux'
let logger = createLogger();
let loggerWithOpts = createLogger({
level: 'error',
duration: true,
timestamp: true,
colors: {
title: (action) => '#000000',
prevState: (prevState) => '#000000',
action: (action) => '#000000',
nextState: (nextState) => '#000000',
error: (error, prevState) => '#000000'
},
logger: console,
logErrors: true,
collapsed: true,
predicate: (getState, action) => true,
stateTransformer: state => state,
actionTransformer: actn => actn,
errorTransformer: err => err
});
let createStoreWithMiddleware = applyMiddleware(
logger, loggerWithOpts
)(createStore);
| Update tests for redux-logger 2.6.0. | Update tests for redux-logger 2.6.0.
| TypeScript | mit | jraymakers/DefinitelyTyped,florentpoujol/DefinitelyTyped,gandjustas/DefinitelyTyped,johan-gorter/DefinitelyTyped,smrq/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,subash-a/DefinitelyTyped,martinduparc/DefinitelyTyped,AgentME/DefinitelyTyped,eugenpodaru/DefinitelyTyped,mcrawshaw/DefinitelyTyped,johan-gorter/DefinitelyTyped,greglo/DefinitelyTyped,georgemarshall/DefinitelyTyped,martinduparc/DefinitelyTyped,Ptival/DefinitelyTyped,benliddicott/DefinitelyTyped,micurs/DefinitelyTyped,Penryn/DefinitelyTyped,Ptival/DefinitelyTyped,arma-gast/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,mattblang/DefinitelyTyped,abner/DefinitelyTyped,shlomiassaf/DefinitelyTyped,progre/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,frogcjn/DefinitelyTyped,pwelter34/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,martinduparc/DefinitelyTyped,stacktracejs/DefinitelyTyped,YousefED/DefinitelyTyped,danfma/DefinitelyTyped,dsebastien/DefinitelyTyped,use-strict/DefinitelyTyped,gcastre/DefinitelyTyped,QuatroCode/DefinitelyTyped,mhegazy/DefinitelyTyped,syuilo/DefinitelyTyped,rolandzwaga/DefinitelyTyped,psnider/DefinitelyTyped,philippstucki/DefinitelyTyped,hellopao/DefinitelyTyped,musicist288/DefinitelyTyped,ryan10132/DefinitelyTyped,trystanclarke/DefinitelyTyped,tan9/DefinitelyTyped,pocesar/DefinitelyTyped,jraymakers/DefinitelyTyped,zuzusik/DefinitelyTyped,aciccarello/DefinitelyTyped,magny/DefinitelyTyped,jimthedev/DefinitelyTyped,mhegazy/DefinitelyTyped,newclear/DefinitelyTyped,shlomiassaf/DefinitelyTyped,nfriend/DefinitelyTyped,philippstucki/DefinitelyTyped,scriby/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,Zzzen/DefinitelyTyped,gandjustas/DefinitelyTyped,daptiv/DefinitelyTyped,xStrom/DefinitelyTyped,reppners/DefinitelyTyped,minodisk/DefinitelyTyped,abbasmhd/DefinitelyTyped,EnableSoftware/DefinitelyTyped,sclausen/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,sledorze/DefinitelyTyped,pocesar/DefinitelyTyped,schmuli/DefinitelyTyped,mcrawshaw/DefinitelyTyped,progre/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,one-pieces/DefinitelyTyped,chrismbarr/DefinitelyTyped,donnut/DefinitelyTyped,Penryn/DefinitelyTyped,borisyankov/DefinitelyTyped,alvarorahul/DefinitelyTyped,magny/DefinitelyTyped,scriby/DefinitelyTyped,psnider/DefinitelyTyped,arusakov/DefinitelyTyped,pwelter34/DefinitelyTyped,sledorze/DefinitelyTyped,nycdotnet/DefinitelyTyped,alvarorahul/DefinitelyTyped,chrootsu/DefinitelyTyped,florentpoujol/DefinitelyTyped,nainslie/DefinitelyTyped,paulmorphy/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,hellopao/DefinitelyTyped,frogcjn/DefinitelyTyped,amanmahajan7/DefinitelyTyped,nainslie/DefinitelyTyped,Litee/DefinitelyTyped,Zzzen/DefinitelyTyped,mareek/DefinitelyTyped,georgemarshall/DefinitelyTyped,Dashlane/DefinitelyTyped,YousefED/DefinitelyTyped,pocesar/DefinitelyTyped,newclear/DefinitelyTyped,stephenjelfs/DefinitelyTyped,hellopao/DefinitelyTyped,HPFOD/DefinitelyTyped,psnider/DefinitelyTyped,rolandzwaga/DefinitelyTyped,alexdresko/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,use-strict/DefinitelyTyped,amir-arad/DefinitelyTyped,paulmorphy/DefinitelyTyped,chrootsu/DefinitelyTyped,stacktracejs/DefinitelyTyped,markogresak/DefinitelyTyped,damianog/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,raijinsetsu/DefinitelyTyped,Litee/DefinitelyTyped,Pro/DefinitelyTyped,HPFOD/DefinitelyTyped,OpenMaths/DefinitelyTyped,Dashlane/DefinitelyTyped,smrq/DefinitelyTyped,ashwinr/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,alexdresko/DefinitelyTyped,minodisk/DefinitelyTyped,chbrown/DefinitelyTyped,isman-usoh/DefinitelyTyped,jimthedev/DefinitelyTyped,emanuelhp/DefinitelyTyped,yuit/DefinitelyTyped,Pro/DefinitelyTyped,isman-usoh/DefinitelyTyped,jimthedev/DefinitelyTyped,borisyankov/DefinitelyTyped,benishouga/DefinitelyTyped,tan9/DefinitelyTyped,rcchen/DefinitelyTyped,gcastre/DefinitelyTyped,abner/DefinitelyTyped,abbasmhd/DefinitelyTyped,OpenMaths/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,syuilo/DefinitelyTyped,dsebastien/DefinitelyTyped,sclausen/DefinitelyTyped,AgentME/DefinitelyTyped,nobuoka/DefinitelyTyped,nobuoka/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,damianog/DefinitelyTyped,mattblang/DefinitelyTyped,emanuelhp/DefinitelyTyped,xStrom/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,mareek/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,georgemarshall/DefinitelyTyped,amanmahajan7/DefinitelyTyped,arma-gast/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,benishouga/DefinitelyTyped,rcchen/DefinitelyTyped,danfma/DefinitelyTyped,nycdotnet/DefinitelyTyped,ashwinr/DefinitelyTyped,greglo/DefinitelyTyped,raijinsetsu/DefinitelyTyped,aciccarello/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,axelcostaspena/DefinitelyTyped,schmuli/DefinitelyTyped,AgentME/DefinitelyTyped,reppners/DefinitelyTyped,mcliment/DefinitelyTyped,donnut/DefinitelyTyped,subash-a/DefinitelyTyped,AgentME/DefinitelyTyped,QuatroCode/DefinitelyTyped,trystanclarke/DefinitelyTyped,benishouga/DefinitelyTyped,arusakov/DefinitelyTyped,EnableSoftware/DefinitelyTyped,aciccarello/DefinitelyTyped,yuit/DefinitelyTyped,stephenjelfs/DefinitelyTyped,chrismbarr/DefinitelyTyped,schmuli/DefinitelyTyped | ---
+++
@@ -1,19 +1,29 @@
/// <reference path="./redux-logger.d.ts" />
-import createLogger from 'redux-logger';
+import * as createLogger from 'redux-logger';
import { applyMiddleware, createStore } from 'redux'
let logger = createLogger();
let loggerWithOpts = createLogger({
+ level: 'error',
+ duration: true,
+ timestamp: true,
+ colors: {
+ title: (action) => '#000000',
+ prevState: (prevState) => '#000000',
+ action: (action) => '#000000',
+ nextState: (nextState) => '#000000',
+ error: (error, prevState) => '#000000'
+ },
+ logger: console,
+ logErrors: true,
+ collapsed: true,
+ predicate: (getState, action) => true,
+ stateTransformer: state => state,
actionTransformer: actn => actn,
- collapsed: true,
- duration: true,
- level: 'error',
- logger: console,
- predicate: (getState, action) => true,
- timestamp: true,
- stateTransformer: state => state
+ errorTransformer: err => err
+
});
let createStoreWithMiddleware = applyMiddleware( |
685074456648ecea6c0f9f3a92948fc006e18f63 | webpack/redux/__tests__/refresh_logs_tests.ts | webpack/redux/__tests__/refresh_logs_tests.ts | const mockGet = jest.fn(() => {
return Promise.resolve({ data: [mockLog.body] });
});
jest.mock("axios", () => ({ default: { get: mockGet } }));
import { refreshLogs } from "../refresh_logs";
import axios from "axios";
import { API } from "../../api";
import { resourceReady } from "../../sync/actions";
import { fakeLog } from "../../__test_support__/fake_state/resources";
const mockLog = fakeLog();
describe("refreshLogs", () => {
it("dispatches the appropriate action", async () => {
const dispatch = jest.fn();
API.setBaseUrl("localhost");
await refreshLogs(dispatch);
expect(axios.get).toHaveBeenCalled();
const action = resourceReady("Log", mockLog);
expect(dispatch).toHaveBeenCalledWith(action);
});
});
| const mockGet = jest.fn(() => {
return Promise.resolve({ data: [mockLog.body] });
});
jest.mock("axios", () => ({ default: { get: mockGet } }));
import { refreshLogs } from "../refresh_logs";
import axios from "axios";
import { API } from "../../api";
import { SyncResponse } from "../../sync/actions";
import { fakeLog } from "../../__test_support__/fake_state/resources";
import { TaggedLog } from "farmbot";
import { Actions } from "../../constants";
const mockLog = fakeLog();
describe("refreshLogs", () => {
it("dispatches the appropriate action", async () => {
const dispatch = jest.fn();
API.setBaseUrl("localhost");
await refreshLogs(dispatch);
expect(axios.get).toHaveBeenCalled();
const lastCall: SyncResponse<TaggedLog> = dispatch.mock.calls[0][0];
expect(lastCall).toBeTruthy();
expect(lastCall.type).toBe(Actions.RESOURCE_READY);
expect(lastCall.payload.body[0].body).toEqual(mockLog.body);
});
});
| Update log tests to account for reducer-assigned UUIDs | Update log tests to account for reducer-assigned UUIDs
| TypeScript | mit | FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app | ---
+++
@@ -5,8 +5,10 @@
import { refreshLogs } from "../refresh_logs";
import axios from "axios";
import { API } from "../../api";
-import { resourceReady } from "../../sync/actions";
+import { SyncResponse } from "../../sync/actions";
import { fakeLog } from "../../__test_support__/fake_state/resources";
+import { TaggedLog } from "farmbot";
+import { Actions } from "../../constants";
const mockLog = fakeLog();
@@ -16,7 +18,9 @@
API.setBaseUrl("localhost");
await refreshLogs(dispatch);
expect(axios.get).toHaveBeenCalled();
- const action = resourceReady("Log", mockLog);
- expect(dispatch).toHaveBeenCalledWith(action);
+ const lastCall: SyncResponse<TaggedLog> = dispatch.mock.calls[0][0];
+ expect(lastCall).toBeTruthy();
+ expect(lastCall.type).toBe(Actions.RESOURCE_READY);
+ expect(lastCall.payload.body[0].body).toEqual(mockLog.body);
});
}); |
466700e0829df64dbb854874336311e3552fc355 | src/js/components/CloseButton.tsx | src/js/components/CloseButton.tsx | import React from 'react'
export default props => {
const { onClick, disabled } = props
return (
<button
{...{
onClick,
disabled
}}
className='inline-flex items-center justify-center w-8 h-8 p-4 m-2 text-red-200 bg-transparent rounded-full hover:text-red-500 hover:bg-red-100 focus:outline-none focus:shadow-outline active:bg-red-300 active:text-red-700'
>
x
</button>
)
}
| import React from 'react'
export default props => {
const { onClick, disabled } = props
return (
<button
{...{
onClick,
disabled
}}
className='inline-flex items-center justify-center w-8 h-8 p-4 m-2 text-xl text-red-200 bg-transparent rounded-full hover:text-red-500 hover:bg-red-100 focus:outline-none focus:shadow-outline active:bg-red-300 active:text-red-700'
>
x
</button>
)
}
| Make close button X larger | Make close button X larger
| TypeScript | mit | xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2 | ---
+++
@@ -8,7 +8,7 @@
onClick,
disabled
}}
- className='inline-flex items-center justify-center w-8 h-8 p-4 m-2 text-red-200 bg-transparent rounded-full hover:text-red-500 hover:bg-red-100 focus:outline-none focus:shadow-outline active:bg-red-300 active:text-red-700'
+ className='inline-flex items-center justify-center w-8 h-8 p-4 m-2 text-xl text-red-200 bg-transparent rounded-full hover:text-red-500 hover:bg-red-100 focus:outline-none focus:shadow-outline active:bg-red-300 active:text-red-700'
>
x
</button> |
f53d0036edff12d57f355a051b524b6c3ebc5021 | tests/src/ui/data-grid.spec.ts | tests/src/ui/data-grid.spec.ts | /// <reference path="../../../typings/globals/jasmine/index.d.ts" />
import {
Component,
ViewChildren,
QueryList
} from '@angular/core';
import {
TestBed
} from '@angular/core/testing';
import {
DxDataGridModule,
DxDataGridComponent
} from '../../../dist';
@Component({
selector: 'test-container-component',
template: ''
})
class TestContainerComponent {
dataSource = [{
string: 'String',
date: new Date(),
dateString: '1995/01/15',
boolean: true,
number: 10
}];
columns = [
{ dataField: 'string' },
{ dataField: 'date' },
{ dataField: 'dateString', dataType: 'date' },
{ dataField: 'boolean' },
{ dataField: 'number' }
];
@ViewChildren(DxDataGridComponent) innerWidgets: QueryList<DxDataGridComponent>;
}
describe('DxDataGrid', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{
declarations: [TestContainerComponent],
imports: [DxDataGridModule]
});
});
// spec
it('should not fall into infinite loop', (done) => {
TestBed.overrideComponent(TestContainerComponent, {
set: {
template: '<dx-data-grid [columns]="columns" [dataSource]="dataSource"></dx-data-grid>'
}
});
let fixture = TestBed.createComponent(TestContainerComponent);
fixture.detectChanges();
setTimeout(() => {
fixture.detectChanges();
done();
}, 100);
});
});
| /// <reference path="../../../typings/globals/jasmine/index.d.ts" />
import {
Component,
ViewChildren,
QueryList
} from '@angular/core';
import {
TestBed
} from '@angular/core/testing';
import {
DxDataGridModule,
DxDataGridComponent
} from '../../../dist';
@Component({
selector: 'test-container-component',
template: ''
})
class TestContainerComponent {
dataSource = [{
string: 'String',
date: new Date(),
dateString: '1995/01/15',
boolean: true,
number: 10
}];
columns = [
{ dataField: 'string' },
{ dataField: 'date' },
{ dataField: 'dateString', dataType: 'date' },
{ dataField: 'boolean' },
{ dataField: 'number' }
];
@ViewChildren(DxDataGridComponent) innerWidgets: QueryList<DxDataGridComponent>;
}
describe('DxDataGrid', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{
declarations: [TestContainerComponent],
imports: [DxDataGridModule]
});
});
// spec
it('should not fall into infinite loop', (done) => {
TestBed.overrideComponent(TestContainerComponent, {
set: {
template: '<dx-data-grid [columns]="columns" [dataSource]="dataSource"></dx-data-grid>'
}
});
let fixture = TestBed.createComponent(TestContainerComponent);
fixture.detectChanges();
setTimeout(() => {
fixture.detectChanges();
done();
}, 0);
});
});
| Reduce timeout time in test to 0 | Reduce timeout time in test to 0
| TypeScript | mit | DevExpress/devextreme-angular,DevExpress/devextreme-angular,DevExpress/devextreme-angular | ---
+++
@@ -63,6 +63,6 @@
fixture.detectChanges();
done();
- }, 100);
+ }, 0);
});
}); |
ac630ff69b2c5b83771f881beda99538519c407b | src/test/index.ts | src/test/index.ts | //
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
import * as testRunner from "vscode/lib/testrunner";
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner; | /**
* PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
*
* This file is providing the test runner to use when running extension tests.
* By default the test runner in use is Mocha based.
*
* You can provide your own test runner if you want to override it by exporting
* a function run(testRoot: string, clb: (error:Error) => void) that the extension
* host can call to run the tests. The test runner is expected to use console.log
* to report the results back to the caller. When the tests are finished, return
* a possible error to the callback or null if none.
*/
import * as testRunner from "vscode/lib/testrunner";
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: "tdd", // The TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // Colored output from test results
});
module.exports = testRunner; | Adjust the test-file according to tslint | Adjust the test-file according to tslint
| TypeScript | mit | manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter | ---
+++
@@ -1,22 +1,23 @@
-//
-// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
-//
-// This file is providing the test runner to use when running extension tests.
-// By default the test runner in use is Mocha based.
-//
-// You can provide your own test runner if you want to override it by exporting
-// a function run(testRoot: string, clb: (error:Error) => void) that the extension
-// host can call to run the tests. The test runner is expected to use console.log
-// to report the results back to the caller. When the tests are finished, return
-// a possible error to the callback or null if none.
+/**
+ * PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
+ *
+ * This file is providing the test runner to use when running extension tests.
+ * By default the test runner in use is Mocha based.
+ *
+ * You can provide your own test runner if you want to override it by exporting
+ * a function run(testRoot: string, clb: (error:Error) => void) that the extension
+ * host can call to run the tests. The test runner is expected to use console.log
+ * to report the results back to the caller. When the tests are finished, return
+ * a possible error to the callback or null if none.
+ */
import * as testRunner from "vscode/lib/testrunner";
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
- ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
- useColors: true // colored output from test results
+ ui: "tdd", // The TDD UI is being used in extension.test.ts (suite, test, etc.)
+ useColors: true // Colored output from test results
});
module.exports = testRunner; |
327924ca0cbfede69d31e247149c53510ed28c6e | src/index.ts | src/index.ts | import { Client, TextChannel, Message } from 'discord.js';
import { getCharacters } from './characters';
import QuoteManager from './quoteManager';
const client = new Client();
let quoteManager: QuoteManager;
client.on('ready', () => {
quoteManager = new QuoteManager();
console.log('Ready!');
});
client.on('message', (msg: Message) => {
if (msg.author.bot || !quoteManager) return;
if (msg.content.startsWith('!cuiller-commands')) {
const chars = getCharacters();
msg.channel.send(`\`${chars.map(char => `!${char}`)}\``)
return;
}
if (msg.content.startsWith('!')) {
const quote = quoteManager.getRandomQuote(msg.content.slice(1));
if (quote) msg.channel.send(quote);
}
});
console.log("Starting");
client.login('MzU2MDgzNDI0NDMzNTM3MDI0.DJWOFQ.CGcTApLhCyT0gzHYMGIPLPvu1Kk'); | import { Client, TextChannel, Message } from 'discord.js';
import { getCharacters } from './characters';
import QuoteManager from './quoteManager';
const client = new Client();
let quoteManager: QuoteManager;
const helpCommand = '!cuiller-commands';
client.on('ready', () => {
quoteManager = new QuoteManager();
client.user.setGame(helpCommand);
console.log('Ready!');
});
client.on('message', (msg: Message) => {
if (msg.author.bot || !quoteManager) return;
if (msg.content.startsWith(helpCommand)) {
const chars = getCharacters();
msg.channel.send(`\`${chars.map(char => `!${char}`)}\``)
return;
}
if (msg.content.startsWith('!')) {
const quote = quoteManager.getRandomQuote(msg.content.slice(1));
if (quote) msg.channel.send(quote);
}
});
console.log("Starting");
client.login('MzU2MDgzNDI0NDMzNTM3MDI0.DJWOFQ.CGcTApLhCyT0gzHYMGIPLPvu1Kk'); | Set game status as the help command | Set game status as the help command
| TypeScript | mit | Lockeid/CuillerBot | ---
+++
@@ -5,15 +5,18 @@
let quoteManager: QuoteManager;
+const helpCommand = '!cuiller-commands';
+
client.on('ready', () => {
quoteManager = new QuoteManager();
+ client.user.setGame(helpCommand);
console.log('Ready!');
});
client.on('message', (msg: Message) => {
if (msg.author.bot || !quoteManager) return;
- if (msg.content.startsWith('!cuiller-commands')) {
+ if (msg.content.startsWith(helpCommand)) {
const chars = getCharacters();
msg.channel.send(`\`${chars.map(char => `!${char}`)}\``)
return; |
3b4477bf919002351585f343e5e07c7ddcce9c79 | applications/drive/src/app/components/FileBrowser/hooks/useFileBrowserCheckbox.ts | applications/drive/src/app/components/FileBrowser/hooks/useFileBrowserCheckbox.ts | import { useCallback } from 'react';
import { useSelection } from '../state/useSelection';
export const useFileBrowserCheckbox = (id: string) => {
const selectionControls = useSelection();
const isSelected = Boolean(selectionControls?.isSelected(id));
const handleCheckboxChange = useCallback((e) => {
const el = document.activeElement ?? e.currentTarget;
if (isSelected && 'blur' in el) {
(el as any).blur();
}
}, []);
const handleCheckboxClick = useCallback((e) => {
if (!e.shiftKey) {
selectionControls?.toggleSelectItem(id);
}
}, []);
const handleCheckboxWrapperClick = useCallback((e) => {
e.stopPropagation();
// Wrapper handles shift key, because FF has issues: https://bugzilla.mozilla.org/show_bug.cgi?id=559506
if (e.shiftKey) {
selectionControls?.toggleRange?.(id);
}
}, []);
return {
handleCheckboxChange,
handleCheckboxClick,
handleCheckboxWrapperClick,
};
};
| import { useCallback } from 'react';
import { useSelection } from '../state/useSelection';
export const useFileBrowserCheckbox = (id: string) => {
const selectionControls = useSelection();
const isSelected = Boolean(selectionControls?.isSelected(id));
const handleCheckboxChange = useCallback((e) => {
const el = document.activeElement ?? e.currentTarget;
if (isSelected && 'blur' in el) {
(el as any).blur();
}
}, []);
const handleCheckboxClick = useCallback(
(e) => {
if (!e.shiftKey) {
selectionControls?.toggleSelectItem(id);
}
},
[selectionControls?.toggleSelectItem]
);
const handleCheckboxWrapperClick = useCallback(
(e) => {
e.stopPropagation();
// Wrapper handles shift key, because FF has issues: https://bugzilla.mozilla.org/show_bug.cgi?id=559506
if (e.shiftKey) {
selectionControls?.toggleRange?.(id);
}
},
[selectionControls?.toggleRange]
);
return {
handleCheckboxChange,
handleCheckboxClick,
handleCheckboxWrapperClick,
};
};
| Fix shift selection on checkbox | Fix shift selection on checkbox
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,4 +1,5 @@
import { useCallback } from 'react';
+
import { useSelection } from '../state/useSelection';
export const useFileBrowserCheckbox = (id: string) => {
@@ -12,19 +13,25 @@
}
}, []);
- const handleCheckboxClick = useCallback((e) => {
- if (!e.shiftKey) {
- selectionControls?.toggleSelectItem(id);
- }
- }, []);
+ const handleCheckboxClick = useCallback(
+ (e) => {
+ if (!e.shiftKey) {
+ selectionControls?.toggleSelectItem(id);
+ }
+ },
+ [selectionControls?.toggleSelectItem]
+ );
- const handleCheckboxWrapperClick = useCallback((e) => {
- e.stopPropagation();
- // Wrapper handles shift key, because FF has issues: https://bugzilla.mozilla.org/show_bug.cgi?id=559506
- if (e.shiftKey) {
- selectionControls?.toggleRange?.(id);
- }
- }, []);
+ const handleCheckboxWrapperClick = useCallback(
+ (e) => {
+ e.stopPropagation();
+ // Wrapper handles shift key, because FF has issues: https://bugzilla.mozilla.org/show_bug.cgi?id=559506
+ if (e.shiftKey) {
+ selectionControls?.toggleRange?.(id);
+ }
+ },
+ [selectionControls?.toggleRange]
+ );
return {
handleCheckboxChange, |
0acb6649bb9d7f18f55c6a0061e813abc0adc79d | server/test/routes.test.ts | server/test/routes.test.ts | import { Application } from 'express';
import * as request from 'supertest';
import { createServer } from '../src/server';
describe('routes', () => {
let app: Application;
before('create app', async () => {
app = createServer();
});
describe('GET /*', () => {
// Let the Angular app show 404's
it('should respond with HTML', async () => {
const randomRoutes = ['/', '/table', '/foo'];
for (const route of randomRoutes) {
await request(app)
.get(route)
.expect(200)
.expect('Content-Type', /html/);
}
});
});
});
| import { Application } from 'express';
import * as request from 'supertest';
import { createServer } from '../src/server';
describe('routes', () => {
let app: Application;
before('create app', async () => {
app = createServer();
});
describe('GET /*', () => {
// Let the Angular app show 404's
it('should respond with HTML', async () => {
const randomRoutes = ['/', '/table', '/foo'];
for (const route of randomRoutes) {
await request(app)
.get(route)
.expect(200)
.expect('Content-Type', /html/);
}
});
it('should respond with 404 when the Accept header is not for HTML', () => {
return request(app)
.get('/foo')
.accept('foo/bar')
.expect(404)
.expect('Content-Type', /text/);
});
});
});
| Test non-HTML requests to /* | Test non-HTML requests to /*
| TypeScript | mit | mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium | ---
+++
@@ -21,5 +21,13 @@
.expect('Content-Type', /html/);
}
});
+
+ it('should respond with 404 when the Accept header is not for HTML', () => {
+ return request(app)
+ .get('/foo')
+ .accept('foo/bar')
+ .expect(404)
+ .expect('Content-Type', /text/);
+ });
});
}); |
c61266439468e140de5fb50d2c211c8ca4ae4263 | src/main.tsx | src/main.tsx | import * as React from "react";
import * as ReactDOM from "react-dom";
import * as injectTapEventPlugin from "react-tap-event-plugin";
import MenuBar from "./components/menu/MenuBar";
import SimpleContent from "./components/SimpleContent";
import TopPage from "./components/top/TopPage";
import EventPage from "./components/event/EventPage";
import StagePage from "./components/stage/StagePage";
import SearchPage from "./components/search/SearchPage";
import MapPage from "./components/map/MapPage";
import { Router, Route, hashHistory, IndexRoute } from "react-router";
injectTapEventPlugin();
interface Text {
content: string;
}
class TestElement extends React.Component<Text, {}> {
render() {
return (
<div className="test">
<MenuBar appName="Shibaura Fes Navi" />
{this.props.children || <TopPage/>}
</div>
);
}
}
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={TestElement}>
<IndexRoute component={TopPage}/>
<Route path="/event" component={EventPage}/>
<Route path="/stage" component={StagePage}/>
<Route path="/search" component={SearchPage}/>
<Route path="/map" component={MapPage}/>
</Route>
</Router>
), document.getElementById("app")); | import * as React from "react";
import * as ReactDOM from "react-dom";
import * as injectTapEventPlugin from "react-tap-event-plugin";
import MenuBar from "./components/menu/MenuBar";
import SimpleContent from "./components/SimpleContent";
import TopPage from "./components/top/TopPage";
import EventPage from "./components/event/EventPage";
import StagePage from "./components/stage/StagePage";
import SearchPage from "./components/search/SearchPage";
import MapPage from "./components/map/MapPage";
import MapEventList from "./components/map/MapEventList";
import { Router, Route, hashHistory, IndexRoute } from "react-router";
injectTapEventPlugin();
interface Text {
content: string;
}
class TestElement extends React.Component<Text, {}> {
render() {
return (
<div className="test">
<MenuBar appName="Shibaura Fes Navi" />
{this.props.children || <TopPage />}
</div>
);
}
}
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={TestElement}>
<IndexRoute component={TopPage} />
<Route path="/event" component={EventPage} />
<Route path="/stage" component={StagePage} />
<Route path="/search" component={SearchPage} />
<Route path="/map" component={MapPage} />
<Route path="/building/:building/:room_or_stall" component={MapEventList} />
</Route>
</Router>
), document.getElementById("app")); | Add React-router path for MapEventList Componet | Add React-router path for MapEventList Componet
| TypeScript | mit | SIT-DigiCre/ShibaurasaiApp,SIT-DigiCre/ShibaurasaiApp,SIT-DigiCre/ShibaurasaiApp | ---
+++
@@ -8,6 +8,7 @@
import StagePage from "./components/stage/StagePage";
import SearchPage from "./components/search/SearchPage";
import MapPage from "./components/map/MapPage";
+import MapEventList from "./components/map/MapEventList";
import { Router, Route, hashHistory, IndexRoute } from "react-router";
injectTapEventPlugin();
@@ -21,7 +22,7 @@
return (
<div className="test">
<MenuBar appName="Shibaura Fes Navi" />
- {this.props.children || <TopPage/>}
+ {this.props.children || <TopPage />}
</div>
);
}
@@ -30,11 +31,12 @@
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={TestElement}>
- <IndexRoute component={TopPage}/>
- <Route path="/event" component={EventPage}/>
- <Route path="/stage" component={StagePage}/>
- <Route path="/search" component={SearchPage}/>
- <Route path="/map" component={MapPage}/>
- </Route>
+ <IndexRoute component={TopPage} />
+ <Route path="/event" component={EventPage} />
+ <Route path="/stage" component={StagePage} />
+ <Route path="/search" component={SearchPage} />
+ <Route path="/map" component={MapPage} />
+ <Route path="/building/:building/:room_or_stall" component={MapEventList} />
+ </Route>
</Router>
), document.getElementById("app")); |
7fbeaf1ad4bf164e1018acfa4e1759026c700116 | packages/@sanity/desk-tool/src/panes/documentPane/documentHistory/history/tracer.ts | packages/@sanity/desk-tool/src/panes/documentPane/documentHistory/history/tracer.ts | import {Doc, RemoteMutationWithVersion, TransactionLogEvent} from './types'
export type TraceEvent =
| {
type: 'initial'
publishedId: string
draft: Doc | null
published: Doc | null
}
| {type: 'addRemoteMutation'; event: RemoteMutationWithVersion}
| {type: 'addTranslogEntry'; event: TransactionLogEvent}
| {type: 'didReachEarliestEntry'}
| {type: 'updateChunks'}
| import {Doc, RemoteMutationWithVersion, TransactionLogEvent} from './types'
import {Timeline} from './timeline'
export type TraceEvent =
| {
type: 'initial'
publishedId: string
draft: Doc | null
published: Doc | null
}
| {type: 'addRemoteMutation'; event: RemoteMutationWithVersion}
| {type: 'addTranslogEntry'; event: TransactionLogEvent}
| {type: 'didReachEarliestEntry'}
| {type: 'updateChunks'}
export function replay(events: TraceEvent[]): Timeline {
const fst = events[0]
if (fst?.type !== 'initial') throw new Error('no initial event')
const timeline = new Timeline({
publishedId: fst.publishedId,
draft: fst.draft,
published: fst.published
})
console.log('Replaying')
console.log({events})
for (let i = 1; i < events.length; i++) {
const event = events[i]
switch (event.type) {
case 'initial':
throw new Error('unexpected initial event')
case 'addRemoteMutation':
timeline.addRemoteMutation(event.event)
break
case 'addTranslogEntry':
timeline.addTranslogEntry(event.event)
break
case 'didReachEarliestEntry':
timeline.didReachEarliestEntry()
break
case 'updateChunks':
timeline.updateChunks()
break
}
}
return timeline
}
| Add helper function for replaying a timeline trace | [desk-tool] Add helper function for replaying a timeline trace
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,4 +1,5 @@
import {Doc, RemoteMutationWithVersion, TransactionLogEvent} from './types'
+import {Timeline} from './timeline'
export type TraceEvent =
| {
@@ -11,3 +12,40 @@
| {type: 'addTranslogEntry'; event: TransactionLogEvent}
| {type: 'didReachEarliestEntry'}
| {type: 'updateChunks'}
+
+export function replay(events: TraceEvent[]): Timeline {
+ const fst = events[0]
+ if (fst?.type !== 'initial') throw new Error('no initial event')
+
+ const timeline = new Timeline({
+ publishedId: fst.publishedId,
+ draft: fst.draft,
+ published: fst.published
+ })
+
+ console.log('Replaying')
+ console.log({events})
+
+ for (let i = 1; i < events.length; i++) {
+ const event = events[i]
+
+ switch (event.type) {
+ case 'initial':
+ throw new Error('unexpected initial event')
+ case 'addRemoteMutation':
+ timeline.addRemoteMutation(event.event)
+ break
+ case 'addTranslogEntry':
+ timeline.addTranslogEntry(event.event)
+ break
+ case 'didReachEarliestEntry':
+ timeline.didReachEarliestEntry()
+ break
+ case 'updateChunks':
+ timeline.updateChunks()
+ break
+ }
+ }
+
+ return timeline
+} |
26dd668516fea18564dd975055e18ec921c9b267 | ui/test/logs/reducers/logs.test.ts | ui/test/logs/reducers/logs.test.ts | import reducer, {defaultState} from 'src/logs/reducers'
import {setTimeWindow} from 'src/logs/actions'
describe('Logs.Reducers', () => {
it('can set a time window', () => {
const expected = {
timeOption: 'now',
windowOption: '1h',
upper: null,
lower: 'now() - 1h',
seconds: 3600,
}
const actual = reducer(defaultState, setTimeWindow(expected))
expect(actual.timeWindow).toBe(expected)
})
})
| import reducer, {defaultState} from 'src/logs/reducers'
import {setTimeWindow, setTimeMarker, setTimeBounds} from 'src/logs/actions'
describe('Logs.Reducers', () => {
it('can set a time window', () => {
const actionPayload = {
windowOption: '10m',
seconds: 600,
}
const expected = {
timeOption: 'now',
windowOption: '10m',
upper: null,
lower: 'now() - 1m',
seconds: 600,
}
const actual = reducer(defaultState, setTimeWindow(actionPayload))
expect(actual.timeRange).toEqual(expected)
})
it('can set a time marker', () => {
const actionPayload = {
timeOption: '2018-07-10T22:22:21.769Z',
}
const expected = {
timeOption: '2018-07-10T22:22:21.769Z',
windowOption: '1m',
upper: null,
lower: 'now() - 1m',
seconds: 60,
}
const actual = reducer(defaultState, setTimeMarker(actionPayload))
expect(actual.timeRange).toEqual(expected)
})
it('can set the time bounds', () => {
const payload = {
upper: '2018-07-10T22:20:21.769Z',
lower: '2018-07-10T22:22:21.769Z',
}
const expected = {
timeOption: 'now',
windowOption: '1m',
upper: '2018-07-10T22:20:21.769Z',
lower: '2018-07-10T22:22:21.769Z',
seconds: 60,
}
const actual = reducer(defaultState, setTimeBounds(payload))
expect(actual.timeRange).toEqual(expected)
})
})
| Add Tests for new time range reducers | Add Tests for new time range reducers
Co-authored-by: Alex Paxton <[email protected]>
Co-authored-by: Daniel Campbell <[email protected]>
| TypeScript | mit | li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,li-ang/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb | ---
+++
@@ -1,17 +1,57 @@
import reducer, {defaultState} from 'src/logs/reducers'
-import {setTimeWindow} from 'src/logs/actions'
+import {setTimeWindow, setTimeMarker, setTimeBounds} from 'src/logs/actions'
describe('Logs.Reducers', () => {
it('can set a time window', () => {
+ const actionPayload = {
+ windowOption: '10m',
+ seconds: 600,
+ }
+
const expected = {
timeOption: 'now',
- windowOption: '1h',
+ windowOption: '10m',
upper: null,
- lower: 'now() - 1h',
- seconds: 3600,
+ lower: 'now() - 1m',
+ seconds: 600,
}
- const actual = reducer(defaultState, setTimeWindow(expected))
- expect(actual.timeWindow).toBe(expected)
+ const actual = reducer(defaultState, setTimeWindow(actionPayload))
+ expect(actual.timeRange).toEqual(expected)
+ })
+
+ it('can set a time marker', () => {
+ const actionPayload = {
+ timeOption: '2018-07-10T22:22:21.769Z',
+ }
+
+ const expected = {
+ timeOption: '2018-07-10T22:22:21.769Z',
+ windowOption: '1m',
+ upper: null,
+ lower: 'now() - 1m',
+ seconds: 60,
+ }
+
+ const actual = reducer(defaultState, setTimeMarker(actionPayload))
+ expect(actual.timeRange).toEqual(expected)
+ })
+
+ it('can set the time bounds', () => {
+ const payload = {
+ upper: '2018-07-10T22:20:21.769Z',
+ lower: '2018-07-10T22:22:21.769Z',
+ }
+
+ const expected = {
+ timeOption: 'now',
+ windowOption: '1m',
+ upper: '2018-07-10T22:20:21.769Z',
+ lower: '2018-07-10T22:22:21.769Z',
+ seconds: 60,
+ }
+
+ const actual = reducer(defaultState, setTimeBounds(payload))
+ expect(actual.timeRange).toEqual(expected)
})
}) |
6691c2c6baa498cfa7ab685ac06fbee97dd39e89 | test/support.ts | test/support.ts | import { fromObservable, Model, notify } from '../src/lib/model';
import { Updatable } from '../src/lib/updatable';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
let chai = require("chai");
let chaiAsPromised = require("chai-as-promised");
chai.should();
chai.use(chaiAsPromised);
@notify('foo', 'bar')
export class TestClass extends Model {
someSubject: Subject<number>;
foo: Number;
bar: Number;
baz: Number;
updatableFoo: Updatable<number>;
@fromObservable derived: number;
@fromObservable subjectDerived: number;
get explodingProperty(): TestClass {
throw new Error('Kaplowie');
}
constructor() {
super();
this.updatableFoo = new Updatable(() => Observable.of(6));
this.someSubject = new Subject();
Observable.of(42).toProperty(this, 'derived');
this.someSubject
.map((x) => x * 10)
.startWith(0)
.toProperty(this, 'subjectDerived');
}
}
export const {expect, assert} = chai; | import * as path from 'path';
import { fromObservable, Model, notify } from '../src/lib/model';
import { Updatable } from '../src/lib/updatable';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
let chai = require("chai");
let chaiAsPromised = require("chai-as-promised");
chai.should();
chai.use(chaiAsPromised);
@notify('foo', 'bar')
export class TestClass extends Model {
someSubject: Subject<number>;
foo: Number;
bar: Number;
baz: Number;
updatableFoo: Updatable<number>;
@fromObservable derived: number;
@fromObservable subjectDerived: number;
get explodingProperty(): TestClass {
throw new Error('Kaplowie');
}
constructor() {
super();
this.updatableFoo = new Updatable(() => Observable.of(6));
this.someSubject = new Subject();
Observable.of(42).toProperty(this, 'derived');
this.someSubject
.map((x) => x * 10)
.startWith(0)
.toProperty(this, 'subjectDerived');
}
}
before(() => {
// NB: We do this so that coverage is more accurate
require('../src/slack-app');
});
after(() => {
if (!('__coverage__' in window)) return;
const { Reporter, Collector } = require('istanbul');
const coll = new Collector();
coll.add(window.__coverage__);
const reporter = new Reporter(null, path.join(__dirname, '..', 'coverage'));
reporter.addAll(['text-summary', 'lcovonly']);
return new Promise((res) => {
reporter.write(coll, true, res);
});
});
export const {expect, assert} = chai; | Write out the coverage report after the test run | Write out the coverage report after the test run
| TypeScript | bsd-3-clause | paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline | ---
+++
@@ -1,3 +1,4 @@
+import * as path from 'path';
import { fromObservable, Model, notify } from '../src/lib/model';
import { Updatable } from '../src/lib/updatable';
import { Observable } from 'rxjs/Observable';
@@ -8,7 +9,6 @@
chai.should();
chai.use(chaiAsPromised);
-
@notify('foo', 'bar')
export class TestClass extends Model {
@@ -37,4 +37,24 @@
}
}
+before(() => {
+ // NB: We do this so that coverage is more accurate
+ require('../src/slack-app');
+});
+
+after(() => {
+ if (!('__coverage__' in window)) return;
+ const { Reporter, Collector } = require('istanbul');
+
+ const coll = new Collector();
+ coll.add(window.__coverage__);
+
+ const reporter = new Reporter(null, path.join(__dirname, '..', 'coverage'));
+ reporter.addAll(['text-summary', 'lcovonly']);
+
+ return new Promise((res) => {
+ reporter.write(coll, true, res);
+ });
+});
+
export const {expect, assert} = chai; |
0a0dd67bd69c0d8b759e264429412c65773373f0 | src/components/Checkbox/Checkbox.tsx | src/components/Checkbox/Checkbox.tsx | import * as React from "react";
import { FilterConsumer } from "../context/filter";
import { Container, HiddenInput, NativeInput } from "./styled";
export interface CheckboxProps {
name: string;
all?: boolean;
CheckboxRenderer?: React.ComponentType<CheckboxRendererProps>;
}
export interface CheckboxRendererProps {
isChecked: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {
public render() {
const { name, all, CheckboxRenderer = NativeCheckbox } = this.props;
return (
<FilterConsumer>
{({ selected, options, set }) => {
const isSelected = all
? selected.length === 0
: selected.includes(name);
return (
<Container
isSelected={isSelected}
onClick={
all
? () => {
Object.keys(options).forEach(k => set(k, false));
}
: this.onClick(name, isSelected, set)
}
>
<HiddenInput type="checkbox" value={name} checked={isSelected} />
<CheckboxRenderer isChecked={isSelected} />
</Container>
);
}}
</FilterConsumer>
);
}
private onClick = (
name: string,
isSelected: boolean,
set: (name: string, value: boolean) => void
) => () => set(name, !isSelected);
}
const NativeCheckbox: React.SFC<CheckboxRendererProps> = ({ isChecked }) => (
<NativeInput type="checkbox" checked={isChecked} />
);
| import * as React from "react";
import { FilterConsumer } from "../context/filter";
import { Container, HiddenInput, NativeInput } from "./styled";
export interface CheckboxProps {
name: string;
all?: boolean;
CheckboxRenderer?: React.ComponentType<CheckboxRendererProps>;
}
export interface CheckboxRendererProps {
isChecked: boolean;
}
export class Checkbox extends React.Component<CheckboxProps> {
public render() {
const { name, all, CheckboxRenderer = NativeCheckbox } = this.props;
return (
<FilterConsumer>
{({ selected, options, set }) => {
const isSelected = all
? selected.length === 0
: selected.includes(name);
return (
<Container
isSelected={isSelected}
onClick={
all
? () => {
Object.keys(options).forEach(k => set(k, false));
}
: this.onClick(name, isSelected, set)
}
>
<HiddenInput
readOnly={true}
type="checkbox"
value={name}
checked={isSelected}
/>
<CheckboxRenderer isChecked={isSelected} />
</Container>
);
}}
</FilterConsumer>
);
}
private onClick = (
name: string,
isSelected: boolean,
set: (name: string, value: boolean) => void
) => () => set(name, !isSelected);
}
const NativeCheckbox: React.SFC<CheckboxRendererProps> = ({ isChecked }) => (
<NativeInput type="checkbox" readOnly={true} checked={isChecked} />
);
| Add readonly prop to the checkbox input | Add readonly prop to the checkbox input
| TypeScript | mit | sajari/sajari-sdk-react,sajari/sajari-sdk-react | ---
+++
@@ -33,7 +33,12 @@
: this.onClick(name, isSelected, set)
}
>
- <HiddenInput type="checkbox" value={name} checked={isSelected} />
+ <HiddenInput
+ readOnly={true}
+ type="checkbox"
+ value={name}
+ checked={isSelected}
+ />
<CheckboxRenderer isChecked={isSelected} />
</Container>
);
@@ -50,5 +55,5 @@
}
const NativeCheckbox: React.SFC<CheckboxRendererProps> = ({ isChecked }) => (
- <NativeInput type="checkbox" checked={isChecked} />
+ <NativeInput type="checkbox" readOnly={true} checked={isChecked} />
); |
4cf61e4273534a9f3254e3121e75f8be4cf3de5d | console/src/app/common/HttpUtils.ts | console/src/app/common/HttpUtils.ts | export class HttpUtils {
// NOTE: Checks if string matches an IP by pattern.
public static isIpAddressValid(ipAddress: string): boolean {
let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
return ipValidationRegex.test(ipAddress);
}
public static shouldPerformMongooseRunRequest(mongooseAddress: string): boolean {
// NOTE: Temporarily checking only IP address.
let isIpValid: boolean = HttpUtils.isIpAddressValid(mongooseAddress);
let isIpPointsToLocalhost: boolean = mongooseAddress.includes("localhost");
return ((isIpValid) || (isIpPointsToLocalhost));
}
å
} | export class HttpUtils {
public static readonly PORT_NUMBER_UPPER_BOUND: number = 65535;
public static readonly LOCALHOST_KEYWORD: string = "localhost";
// NOTE: Checks if string matches an IP by pattern.
public static isIpAddressValid(ipAddress: string): boolean {
const localhostKeyword: string = HttpUtils.LOCALHOST_KEYWORD;
const hasLocalhostKeyword: boolean = ipAddress.includes(localhostKeyword);
if (!hasLocalhostKeyword) {
let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
return ipValidationRegex.test(ipAddress);
}
const emptyString = "";
const portNumberAndKeywordDelimiter = ":";
const remaningAddressWithoutKeywords = ipAddress.replace(localhostKeyword + portNumberAndKeywordDelimiter, emptyString);
const maximumAmountOfDigitsInPort = 5;
if (remaningAddressWithoutKeywords.length < maximumAmountOfDigitsInPort) {
return false;
}
const portNumber = Number(remaningAddressWithoutKeywords);
return (isNaN(portNumber) && (portNumber <= HttpUtils.PORT_NUMBER_UPPER_BOUND));
}
public static shouldPerformMongooseRunRequest(mongooseAddress: string): boolean {
// NOTE: Temporarily checking only IP address.
let isIpValid: boolean = HttpUtils.isIpAddressValid(mongooseAddress);
let isIpPointsToLocalhost: boolean = mongooseAddress.includes("localhost");
return ((isIpValid) || (isIpPointsToLocalhost));
}
å
} | Update ip validation function @ Http utils. | Update ip validation function @ Http utils.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -1,9 +1,29 @@
export class HttpUtils {
+
+ public static readonly PORT_NUMBER_UPPER_BOUND: number = 65535;
+ public static readonly LOCALHOST_KEYWORD: string = "localhost";
// NOTE: Checks if string matches an IP by pattern.
public static isIpAddressValid(ipAddress: string): boolean {
- let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
- return ipValidationRegex.test(ipAddress);
+ const localhostKeyword: string = HttpUtils.LOCALHOST_KEYWORD;
+ const hasLocalhostKeyword: boolean = ipAddress.includes(localhostKeyword);
+ if (!hasLocalhostKeyword) {
+ let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
+ return ipValidationRegex.test(ipAddress);
+ }
+ const emptyString = "";
+ const portNumberAndKeywordDelimiter = ":";
+ const remaningAddressWithoutKeywords = ipAddress.replace(localhostKeyword + portNumberAndKeywordDelimiter, emptyString);
+
+ const maximumAmountOfDigitsInPort = 5;
+ if (remaningAddressWithoutKeywords.length < maximumAmountOfDigitsInPort) {
+ return false;
+ }
+
+ const portNumber = Number(remaningAddressWithoutKeywords);
+
+ return (isNaN(portNumber) && (portNumber <= HttpUtils.PORT_NUMBER_UPPER_BOUND));
+
}
public static shouldPerformMongooseRunRequest(mongooseAddress: string): boolean {
@@ -12,5 +32,5 @@
let isIpPointsToLocalhost: boolean = mongooseAddress.includes("localhost");
return ((isIpValid) || (isIpPointsToLocalhost));
}
-å
+ å
} |
57aae1f7556284176ffe0dd1c0e7cbdfbd212f3e | src/Microsoft.AspNetCore.SpaTemplates/content/Aurelia-CSharp/ClientApp/app/components/app/app.ts | src/Microsoft.AspNetCore.SpaTemplates/content/Aurelia-CSharp/ClientApp/app/components/app/app.ts | import { Aurelia, PLATFORM } from 'aurelia-framework';
import { Router, RouterConfiguration } from 'aurelia-router';
export class App {
router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
config.title = 'Aurelia';
config.map([{
route: [ '', 'home' ],
name: 'home',
settings: { icon: 'home' },
moduleId: PLATFORM.moduleName('../home/home'),
nav: true,
title: 'Home'
}, {
route: 'counter',
name: 'counter',
settings: { icon: 'education' },
moduleId: PLATFORM.moduleName('../counter/counter'),
nav: true,
title: 'Counter'
}, {
route: 'fetch-data',
name: 'fetchdata',
settings: { icon: 'th-list' },
moduleId: PLATFORM.moduleName('../fetchdata/fetchdata'),
nav: true,
title: 'Fetch data'
}]);
this.router = router;
}
}
| import { Aurelia, PLATFORM } from 'aurelia-framework';
import { Router, RouterConfiguration } from 'aurelia-router';
export class App {
router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
config.title = 'AureliaSpa';
config.map([{
route: [ '', 'home' ],
name: 'home',
settings: { icon: 'home' },
moduleId: PLATFORM.moduleName('../home/home'),
nav: true,
title: 'Home'
}, {
route: 'counter',
name: 'counter',
settings: { icon: 'education' },
moduleId: PLATFORM.moduleName('../counter/counter'),
nav: true,
title: 'Counter'
}, {
route: 'fetch-data',
name: 'fetchdata',
settings: { icon: 'th-list' },
moduleId: PLATFORM.moduleName('../fetchdata/fetchdata'),
nav: true,
title: 'Fetch data'
}]);
this.router = router;
}
}
| Fix failing test for Aurelia template | Fix failing test for Aurelia template
| TypeScript | apache-2.0 | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | ---
+++
@@ -5,7 +5,7 @@
router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
- config.title = 'Aurelia';
+ config.title = 'AureliaSpa';
config.map([{
route: [ '', 'home' ],
name: 'home', |
c710fc7eb3e5d3d405b8c6f1be29ab01a22fa312 | src/v2/components/TopBar/components/AdvancedPrimarySearch/components/AdvancedSearchReturnLabel/index.tsx | src/v2/components/TopBar/components/AdvancedPrimarySearch/components/AdvancedSearchReturnLabel/index.tsx | import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { mixin as boxMixin } from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
const Container = styled(Link).attrs({
mr: 5,
py: 1,
px: 2,
})`
${boxMixin}
display: flex;
align-items: center;
justify-content: center;
background-color: ${p => p.theme.colors.background};
border-radius: ${p => p.theme.radii.regular};
`
const Label = styled(Text).attrs({
color: 'gray.medium',
})`
display: inline;
&:hover {
color: ${p => p.theme.colors.gray.bold};
}
`
interface AdvancedSearchReturnLabelProps {
label?: string
url?: string
}
export const AdvancedSearchReturnLabel: React.FC<AdvancedSearchReturnLabelProps> = ({
label = 'See all results',
url,
}) => {
return (
<Container to={url}>
<Label f={0} mr={4}>
⮐{' '}
</Label>
<Label f={1}>{label}</Label>
</Container>
)
}
export default AdvancedSearchReturnLabel
| import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { mixin as boxMixin } from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
const Label = styled(Text).attrs({
color: 'gray.medium',
})`
display: inline;
`
const Container = styled(Link).attrs({
mr: 5,
py: 1,
px: 2,
})`
${boxMixin}
display: flex;
align-items: center;
justify-content: center;
background-color: ${p => p.theme.colors.background};
border-radius: ${p => p.theme.radii.regular};
&:hover ${Label} {
color: ${p => p.theme.colors.gray.bold};
}
`
interface AdvancedSearchReturnLabelProps {
label?: string
url?: string
}
export const AdvancedSearchReturnLabel: React.FC<AdvancedSearchReturnLabelProps> = ({
label = 'See all results',
url,
}) => {
return (
<Container to={url}>
<Label f={0} mr={4}>
⮐{' '}
</Label>
<Label f={1}>{label}</Label>
</Container>
)
}
export default AdvancedSearchReturnLabel
| Fix hover state for return label (closes ARE-466) | Fix hover state for return label (closes ARE-466)
| TypeScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -4,6 +4,12 @@
import { mixin as boxMixin } from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
+
+const Label = styled(Text).attrs({
+ color: 'gray.medium',
+})`
+ display: inline;
+`
const Container = styled(Link).attrs({
mr: 5,
@@ -16,14 +22,8 @@
justify-content: center;
background-color: ${p => p.theme.colors.background};
border-radius: ${p => p.theme.radii.regular};
-`
-const Label = styled(Text).attrs({
- color: 'gray.medium',
-})`
- display: inline;
-
- &:hover {
+ &:hover ${Label} {
color: ${p => p.theme.colors.gray.bold};
}
` |
9bf3ae8f7ff7a2dd17673bc0855426fecb57b407 | src/object/index.ts | src/object/index.ts | // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
export function extend<T, U>(t: T, u: U): T & U;
export function extend<T, U, V>(t: T, u: U, v: V): T & U & V;
export function extend<T, U, V, W>(t: T, u: U, v: V, w: W): T & U & V & W;
export function extend(...args: any[]): any {
let res: any = {};
Object.assign(res, ...args);
return res;
}
| // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
export function extend<T, U>(t: T, u: U): T & U;
export function extend<T, U, V>(t: T, u: U, v: V): T & U & V;
export function extend<T, U, V, W>(t: T, u: U, v: V, w: W): T & U & V & W;
export function extend(...args: any[]): any {
let res: any = {};
Object.assign(res, ...args);
return res;
}
export function maybeNull<T, U>(t: T | null, func: (t: T) => U): U | null {
if (t === null) {
return null;
}
return func(t);
}
export function maybeUndefined<T, U>(t: T | undefined, func: (t: T) => U): U | undefined {
if (t === undefined) {
return undefined;
}
return func(t);
}
export function maybeNund<T, U>(t: T | null | undefined, func: (t: T) => U): U | null | undefined {
if (t === null) {
return null;
}
else if (t === undefined) {
return undefined;
}
return func(t);
}
| Add simple helpers for dealing w/ null/undefined | Add simple helpers for dealing w/ null/undefined
| TypeScript | mit | joeduffy/nodets | ---
+++
@@ -11,3 +11,27 @@
return res;
}
+export function maybeNull<T, U>(t: T | null, func: (t: T) => U): U | null {
+ if (t === null) {
+ return null;
+ }
+ return func(t);
+}
+
+export function maybeUndefined<T, U>(t: T | undefined, func: (t: T) => U): U | undefined {
+ if (t === undefined) {
+ return undefined;
+ }
+ return func(t);
+}
+
+export function maybeNund<T, U>(t: T | null | undefined, func: (t: T) => U): U | null | undefined {
+ if (t === null) {
+ return null;
+ }
+ else if (t === undefined) {
+ return undefined;
+ }
+ return func(t);
+}
+ |
dec7761c438336e248b59d3843ce69cd961a33a8 | src/index.ts | src/index.ts | import { Application } from 'typedoc/dist/lib/application';
import { ParameterType } from 'typedoc/dist/lib/utils/options/declaration';
import { MarkdownPlugin } from './plugin';
module.exports = (PluginHost: Application) => {
const app = PluginHost.owner;
/**
* Expose additional options for consumption.
*/
app.options.addDeclaration({
component: 'markdown',
help: 'Markdown Plugin: Suppress file sources from output.',
name: 'mdHideSources',
type: ParameterType.Boolean,
});
app.options.addDeclaration({
component: 'markdown',
defaultValue: 'github',
help: 'Markdown Plugin: (github|bitbucket|gitbook) Specifies the markdown rendering engine.',
name: 'mdEngine',
type: ParameterType.String,
});
app.options.addDeclaration({
component: 'markdown',
defaultValue: 'github',
help: 'Markdown Plugin: Deprectated - use --mdEngine.',
name: 'mdFlavour',
type: ParameterType.String,
});
app.options.addDeclaration({
component: 'markdown',
help: 'The repository to use for source files (ignored unless markdownFlavour is set)',
name: 'mdSourceRepo',
type: ParameterType.String,
});
/**
* Add the plugin to the converter instance
*/
app.converter.addComponent('markdown', MarkdownPlugin);
};
| import { Application } from 'typedoc/dist/lib/application';
import { ParameterType } from 'typedoc/dist/lib/utils/options/declaration';
import { MarkdownPlugin } from './plugin';
module.exports = (PluginHost: Application) => {
const app = PluginHost.owner;
if (app.converter.hasComponent('markdown')) {
return;
}
/**
* Expose additional options for consumption.
*/
app.options.addDeclaration({
component: 'markdown',
help: 'Markdown Plugin: Suppress file sources from output.',
name: 'mdHideSources',
type: ParameterType.Boolean,
});
app.options.addDeclaration({
component: 'markdown',
defaultValue: 'github',
help: 'Markdown Plugin: (github|bitbucket|gitbook) Specifies the markdown rendering engine.',
name: 'mdEngine',
type: ParameterType.String,
});
app.options.addDeclaration({
component: 'markdown',
defaultValue: 'github',
help: 'Markdown Plugin: Deprectated - use --mdEngine.',
name: 'mdFlavour',
type: ParameterType.String,
});
app.options.addDeclaration({
component: 'markdown',
help: 'The repository to use for source files (ignored unless markdownFlavour is set)',
name: 'mdSourceRepo',
type: ParameterType.String,
});
/**
* Add the plugin to the converter instance
*/
app.converter.addComponent('markdown', MarkdownPlugin);
};
| Check if plugin is already loaded before adding components | Check if plugin is already loaded before adding components
| TypeScript | mit | tgreyuk/typedoc-plugin-markdown,tgreyuk/typedoc-plugin-markdown | ---
+++
@@ -5,6 +5,10 @@
module.exports = (PluginHost: Application) => {
const app = PluginHost.owner;
+
+ if (app.converter.hasComponent('markdown')) {
+ return;
+ }
/**
* Expose additional options for consumption. |
cf15d34bc47ea7a7b4e553ebb749e76e91bf36b7 | js-md5/index.d.ts | js-md5/index.d.ts | // Type definitions for js-md5 v0.4.2
// Project: https://github.com/emn178/js-md5
// Definitions by: Michael McCarthy <https://github.com/mwmccarthy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/
declare namespace md5 {
type message = string | any[] | Uint8Array | ArrayBuffer;
interface Md5 {
array: () => number[];
arrayBuffer: () => ArrayBuffer;
buffer: () => ArrayBuffer;
digest: () => number[];
finalize: () => void;
hex: () => string;
toString: () => string;
update: (message: message) => Md5;
}
interface md5 {
(message: message): string;
hex: (message: message) => string;
array: (message: message) => number[];
digest: (message: message) => number[];
arrayBuffer: (message: message) => ArrayBuffer;
buffer: (message: message) => ArrayBuffer;
create: () => Md5;
update: (message: message) => Md5;
}
}
declare const md5: md5.md5;
export = md5;
| // Type definitions for js-md5 v0.4.2
// Project: https://github.com/emn178/js-md5
// Definitions by: Michael McCarthy <https://github.com/mwmccarthy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/
declare namespace md5 {
type message = string | any[] | Uint8Array | ArrayBuffer;
interface Md5 {
array: () => number[];
arrayBuffer: () => ArrayBuffer;
buffer: () => ArrayBuffer;
digest: () => number[];
finalize: () => void;
hex: () => string;
toString: () => string;
update: (message: message) => Md5;
}
interface md5 {
(message: message): string;
hex: (message: message) => string;
array: (message: message) => number[];
digest: (message: message) => number[];
arrayBuffer: (message: message) => ArrayBuffer;
buffer: (message: message) => ArrayBuffer;
create: () => Md5;
update: (message: message) => Md5;
}
}
declare const md5: md5.md5;
export = md5;
| Replace stray tab with spaces | Replace stray tab with spaces
| TypeScript | mit | AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,borisyankov/DefinitelyTyped,benishouga/DefinitelyTyped,amir-arad/DefinitelyTyped,AgentME/DefinitelyTyped,smrq/DefinitelyTyped,jimthedev/DefinitelyTyped,markogresak/DefinitelyTyped,QuatroCode/DefinitelyTyped,YousefED/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,arusakov/DefinitelyTyped,isman-usoh/DefinitelyTyped,jimthedev/DefinitelyTyped,zuzusik/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,johan-gorter/DefinitelyTyped,benliddicott/DefinitelyTyped,ashwinr/DefinitelyTyped,QuatroCode/DefinitelyTyped,mcrawshaw/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,nycdotnet/DefinitelyTyped,YousefED/DefinitelyTyped,benishouga/DefinitelyTyped,chrootsu/DefinitelyTyped,arusakov/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,progre/DefinitelyTyped,minodisk/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,magny/DefinitelyTyped,ashwinr/DefinitelyTyped,mcliment/DefinitelyTyped,progre/DefinitelyTyped,mcrawshaw/DefinitelyTyped,minodisk/DefinitelyTyped,borisyankov/DefinitelyTyped,johan-gorter/DefinitelyTyped,abbasmhd/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,abbasmhd/DefinitelyTyped,isman-usoh/DefinitelyTyped,alexdresko/DefinitelyTyped,alexdresko/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,jimthedev/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,smrq/DefinitelyTyped,nycdotnet/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,zuzusik/DefinitelyTyped,rolandzwaga/DefinitelyTyped,one-pieces/DefinitelyTyped | ---
+++
@@ -22,7 +22,7 @@
hex: (message: message) => string;
array: (message: message) => number[];
digest: (message: message) => number[];
- arrayBuffer: (message: message) => ArrayBuffer;
+ arrayBuffer: (message: message) => ArrayBuffer;
buffer: (message: message) => ArrayBuffer;
create: () => Md5;
update: (message: message) => Md5; |
0a30fd0e40144d1a98fe15c94d792eab0d58695a | jSlider/Options.ts | jSlider/Options.ts | module jSlider {
export class Options {
private options:Object = {
"delay": 4000,
"duration": 200,
"effect": jSlider.Effect.SLIDE,
"button": {
"next": null,
"prev": null,
"stop": null,
"start": null
},
"on": {
"slide": [],
"next": [],
"prev": [],
"start": [],
"stop": []
}
};
constructor(options:Object = {}) {
var option:string;
for (option in this.options) {
if (!this.options.hasOwnProperty(option)) continue;
this.options[option] = options[option] || this.options[option];
}
//Change event listeners to [function(){}] if function(){}
var eventListeners = this.options['on'];
var key:string;
for (key in eventListeners) {
if (!eventListeners.hasOwnProperty(key)) continue;
if (typeof eventListeners[key] === 'function') {
this.options['on'][key] = Array(eventListeners[key]);
}
}
}
/**
* Get an option
* @param optionName
* @returns {string}
*/
public get(optionName:string):any {
return this.options[optionName];
}
}
} | module jSlider {
export class Options {
private options:Object = {
"delay": 4000,
"duration": 200,
"effect": jSlider.Effect.SLIDE,
"button": {
"next": null,
"prev": null,
"stop": null,
"start": null
},
"on": {
"slide": [],
"next": [],
"prev": [],
"start": [],
"stop": []
}
};
constructor(options:Object = {}) {
jQuery.extend(true, this.options, options);
console.log(this.options['on']);
//Change event listeners to [function(){}] if function(){}
var eventListeners = this.options['on'];
var key:string;
for (key in eventListeners) {
if (!eventListeners.hasOwnProperty(key)) continue;
if (typeof eventListeners[key] === 'function') {
this.options['on'][key] = Array(eventListeners[key]);
}
}
}
/**
* Get an option
* @param optionName
* @returns {string}
*/
public get(optionName:string):any {
return this.options[optionName];
}
}
} | Fix second level options. options like on->someOption and button->option did not work as the loop was just asking if, for example "on" is set in the user defined option array. and even though the user might not have spesified a, for example "next" event, but has spesified the "slide" event. The entire "on" will be replaced by the user spesified one, and this array does not contain the proper default, causing in, amongst other things a "property does not exist" error when trying to trigger events. | Fix second level options.
options like on->someOption and button->option
did not work as the loop was just asking if, for example
"on" is set in the user defined option array.
and even though the user might not have spesified a, for example
"next" event, but has spesified the "slide" event. The entire
"on" will be replaced by the user spesified one, and this array
does not contain the proper default, causing in, amongst other things
a "property does not exist" error when trying to trigger events.
| TypeScript | lgpl-2.1 | sigurdsvela/JSlider | ---
+++
@@ -20,11 +20,8 @@
};
constructor(options:Object = {}) {
- var option:string;
- for (option in this.options) {
- if (!this.options.hasOwnProperty(option)) continue;
- this.options[option] = options[option] || this.options[option];
- }
+ jQuery.extend(true, this.options, options);
+ console.log(this.options['on']);
//Change event listeners to [function(){}] if function(){}
var eventListeners = this.options['on']; |
cd81e24cea5ded7f178174a1f40631e566ebef5e | src/components/Room.ts | src/components/Room.ts | import PheromoneNetwork from './PheromoneNetwork'
// --- Properties ---
Object.defineProperty(Room.prototype, 'pheromoneNetwork', {
configurable: true,
get(this: Room) {
if (this._pheromoneNetwork === undefined && this.memory.pheromoneNetwork !== undefined) {
this._pheromoneNetwork = PheromoneNetwork.deserialize(this.memory.pheromoneNetwork)
}
if (this._pheromoneNetwork === undefined) {
this._pheromoneNetwork = new PheromoneNetwork(this)
}
if (this.memory.pheromoneNetwork === undefined) {
this.memory.pheromoneNetwork = this._pheromoneNetwork.serialize()
}
return this._pheromoneNetwork
}
})
// --- Methods ---
Room.prototype.run = function(this: Room) {
this.pheromoneNetwork.dissipate()
}
Room.prototype.draw = function(this: Room) {
this.pheromoneNetwork.draw('home', '#47AFFF')
this.pheromoneNetwork.draw('energy', '#FFE87B')
}
| import PheromoneNetwork from './PheromoneNetwork'
// --- Properties ---
Object.defineProperty(Room.prototype, 'pheromoneNetwork', {
configurable: true,
get(this: Room) {
if (this._pheromoneNetwork === undefined && this.memory.pheromoneNetwork !== undefined) {
this._pheromoneNetwork = PheromoneNetwork.deserialize(this.memory.pheromoneNetwork)
}
if (this._pheromoneNetwork === undefined) {
this._pheromoneNetwork = new PheromoneNetwork(this)
}
if (this.memory.pheromoneNetwork === undefined) {
this.memory.pheromoneNetwork = this._pheromoneNetwork.serialize()
}
return this._pheromoneNetwork
}
})
// --- Methods ---
Room.prototype.run = function(this: Room) {
if (Game.time % 2 === 0) {
this.pheromoneNetwork.dissipate()
}
}
Room.prototype.draw = function(this: Room) {
this.pheromoneNetwork.draw('home', '#47AFFF')
this.pheromoneNetwork.draw('energy', '#FFE87B')
}
| Reduce dissipation rate to 1 per 2 ticks | Reduce dissipation rate to 1 per 2 ticks
| TypeScript | unlicense | tinnvec/aints,tinnvec/aints | ---
+++
@@ -21,7 +21,9 @@
// --- Methods ---
Room.prototype.run = function(this: Room) {
- this.pheromoneNetwork.dissipate()
+ if (Game.time % 2 === 0) {
+ this.pheromoneNetwork.dissipate()
+ }
}
Room.prototype.draw = function(this: Room) { |
65c79a775feb264d08ca6fce6fbba5ae1822cf63 | packages/examples/src/generateUI.ts | packages/examples/src/generateUI.ts | import { registerExamples } from './register';
import { data as personData, } from './person';
export const schema = undefined;
export const uischema = undefined;
export const data = personData;
registerExamples([
{
name: 'generate-ui',
label: 'Generate UI Schema',
data,
schema,
uiSchema: uischema
}
]);
| import { registerExamples } from './register';
import {data as personData, personCoreSchema } from './person';
export const schema = personCoreSchema;
export const uischema = undefined;
export const data = personData;
registerExamples([
{
name: 'generate-ui',
label: 'Generate UI Schema',
data,
schema,
uiSchema: uischema
}
]);
| Set person core schema to be used as schema in generate UI example | Set person core schema to be used as schema in generate UI example
| TypeScript | mit | qb-project/jsonforms,qb-project/jsonforms,qb-project/jsonforms | ---
+++
@@ -1,7 +1,7 @@
import { registerExamples } from './register';
-import { data as personData, } from './person';
+import {data as personData, personCoreSchema } from './person';
-export const schema = undefined;
+export const schema = personCoreSchema;
export const uischema = undefined;
export const data = personData;
|
5f35907f7f985724078564f0f084cb95c655b5e9 | packages/components/hooks/useLoad.ts | packages/components/hooks/useLoad.ts | import { useEffect } from 'react';
import { useRouteMatch } from 'react-router';
import { load } from 'proton-shared/lib/api/core/load';
import useApi from './useApi';
const useLoad = () => {
const api = useApi();
/*
* The "path" property on React Router's "match" object contains the
* path pattern that was used to match the current pathname.
*
* It therefore contains the names of any dynamic parameters rather
* than their values.
*
* This is an important distinction for three reasons:
* - it makes it possible to tell which segments of the pathname are parameters (":")
* - this path looks the same indifferent of how the parameters are populated
* - it allows us to send the load request without leaking any potentially sensitive data
*/
const { path } = useRouteMatch();
useEffect(() => {
api({ ...load(path), silent: true });
}, []);
};
export default useLoad;
| import { useEffect } from 'react';
import { useRouteMatch } from 'react-router';
import { load } from 'proton-shared/lib/api/core/load';
import useApi from './useApi';
const useLoad = () => {
const api = useApi();
/*
* The "path" property on React Router's "match" object contains the
* path pattern that was used to match the current pathname.
*
* It therefore contains the names of any dynamic parameters rather
* than their values.
*
* This is an important distinction for three reasons:
* - it makes it possible to tell which segments of the pathname are parameters (":")
* - this path looks the same indifferent of how the parameters are populated
* - it allows us to send the load request without leaking any potentially sensitive data
*/
const { path } = useRouteMatch();
useEffect(() => {
api({ ...load(path), silence: true });
}, []);
};
export default useLoad;
| Fix incorrect name for silence api config | Fix incorrect name for silence api config
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -22,7 +22,7 @@
const { path } = useRouteMatch();
useEffect(() => {
- api({ ...load(path), silent: true });
+ api({ ...load(path), silence: true });
}, []);
};
|
8264f3aa18be424ca9f137b9b8398bd6eec169e2 | src/types/Types.ts | src/types/Types.ts | /**
* @public
*/
export type Node = {
nodeType: number;
};
/**
* @public
*/
export type Attr = Node & {
localName: string;
name: string;
namespaceURI: string;
nodeName: string;
prefix: string;
value: string;
};
/**
* @public
*/
export type CharacterData = Node & { data: string };
/**
* @public
*/
export type CDATASection = CharacterData;
/**
* @public
*/
export type Comment = CharacterData;
/**
* @public
*/
export type Document = Node & {
implementation: {
createDocument(namespaceURI: null, qualifiedNameStr: null, documentType: null): Document;
};
createAttributeNS(namespaceURI: string, name: string): Attr;
createCDATASection(contents: string): CDATASection;
createComment(data: string): Comment;
createElementNS(namespaceURI: string, qualifiedName: string): Element;
createProcessingInstruction(target: string, data: string): ProcessingInstruction;
createTextNode(data: string): Text;
};
/**
* @public
*/
export type Element = Node & {
localName: string;
namespaceURI: string;
nodeName: string;
prefix: string;
};
/**
* @public
*/
export type ProcessingInstruction = CharacterData & {
nodeName: string;
target: string;
};
/**
* @public
*/
export type Text = CharacterData;
| /**
* @public
*/
export type Node = {
nodeType: number;
};
/**
* @public
*/
export type Attr = Node & {
localName: string;
name: string;
namespaceURI: string | null;
nodeName: string;
prefix: string | null;
value: string;
};
/**
* @public
*/
export type CharacterData = Node & { data: string };
/**
* @public
*/
export type CDATASection = CharacterData;
/**
* @public
*/
export type Comment = CharacterData;
/**
* @public
*/
export type Document = Node & {
implementation: {
createDocument(namespaceURI: null, qualifiedNameStr: null, documentType: null): Document;
};
createAttributeNS(namespaceURI: string, name: string): Attr;
createCDATASection(contents: string): CDATASection;
createComment(data: string): Comment;
createElementNS(namespaceURI: string, qualifiedName: string): Element;
createProcessingInstruction(target: string, data: string): ProcessingInstruction;
createTextNode(data: string): Text;
};
/**
* @public
*/
export type Element = Node & {
localName: string;
namespaceURI: string | null;
nodeName: string;
prefix: string | null;
};
/**
* @public
*/
export type ProcessingInstruction = CharacterData & {
nodeName: string;
target: string;
};
/**
* @public
*/
export type Text = CharacterData;
| Make the prefix/namespaceURI of Element/Attr nullable | Make the prefix/namespaceURI of Element/Attr nullable
This makes the typings more in-line with lib.dom | TypeScript | mit | FontoXML/fontoxpath,FontoXML/fontoxpath,FontoXML/fontoxpath | ---
+++
@@ -11,9 +11,9 @@
export type Attr = Node & {
localName: string;
name: string;
- namespaceURI: string;
+ namespaceURI: string | null;
nodeName: string;
- prefix: string;
+ prefix: string | null;
value: string;
};
@@ -52,9 +52,9 @@
*/
export type Element = Node & {
localName: string;
- namespaceURI: string;
+ namespaceURI: string | null;
nodeName: string;
- prefix: string;
+ prefix: string | null;
};
/** |
cd9dac9f854da13c50885713b94aadaaab4502c0 | typings/tests/component-type-test.tsx | typings/tests/component-type-test.tsx | import styled from "../..";
declare const A: React.ComponentClass;
declare const B: React.StatelessComponent;
declare const C: React.ComponentClass | React.StatelessComponent;
styled(A); // succeeds
styled(B); // succeeds
styled(C); // used to fail; see issue trail linked below
// https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247
// https://github.com/mui-org/material-ui/issues/9838
// https://github.com/styled-components/styled-components/pull/1420
// https://github.com/styled-components/styled-components/pull/1427
| import styled from "../..";
declare const A: React.ComponentClass;
declare const B: React.StatelessComponent;
declare const C: React.ComponentClass | React.StatelessComponent;
styled(A); // succeeds
styled(B); // succeeds
styled(C); // used to fail; see issue trail linked below
// https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247
// https://github.com/mui-org/material-ui/issues/9838
// https://github.com/styled-components/styled-components/pull/1420
// https://github.com/Microsoft/TypeScript/issues/21175
// https://github.com/styled-components/styled-components/pull/1427
| Add link to the TypeScript bug report | Add link to the TypeScript bug report
| TypeScript | mit | css-components/styled-components,styled-components/styled-components,JamieDixon/styled-components,JamieDixon/styled-components,JamieDixon/styled-components,styled-components/styled-components,styled-components/styled-components | ---
+++
@@ -11,4 +11,5 @@
// https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247
// https://github.com/mui-org/material-ui/issues/9838
// https://github.com/styled-components/styled-components/pull/1420
+// https://github.com/Microsoft/TypeScript/issues/21175
// https://github.com/styled-components/styled-components/pull/1427 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.