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
3016c9f71c3165f53b5b6d9ec90a39b16c033893
src/Styleguide/Components/ArtistBio.tsx
src/Styleguide/Components/ArtistBio.tsx
import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { Responsive } from "Utils/Responsive" import { ReadMore } from "./ReadMore" import { ArtistBio_bio } from "__generated__/ArtistBio_bio.graphql" interface Props { bio: ArtistBio_bio onReadMoreClicked?: () => void } export class ArtistBio extends React.Component<Props> { render() { const blurb = ( <div dangerouslySetInnerHTML={{ __html: this.props.bio.biography_blurb.text, }} /> ) return ( <Responsive> {({ xs }) => { if (xs) { return ( <ReadMore onReadMoreClicked={this.props.onReadMoreClicked}> {blurb} </ReadMore> ) } else { return ( <ReadMore onReadMoreClicked={this.props.onReadMoreClicked} maxLineCount={7} > {blurb} </ReadMore> ) } }} </Responsive> ) } } export const ArtistBioFragmentContainer = createFragmentContainer( ArtistBio, graphql` fragment ArtistBio_bio on Artist { biography_blurb(format: HTML, partner_bio: true) { text credit } } ` )
import { Serif } from "@artsy/palette" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { Responsive } from "Utils/Responsive" import { ReadMore } from "./ReadMore" import { ArtistBio_bio } from "__generated__/ArtistBio_bio.graphql" interface Props { bio: ArtistBio_bio onReadMoreClicked?: () => void } export class ArtistBio extends React.Component<Props> { render() { const blurb = ( <div dangerouslySetInnerHTML={{ __html: this.props.bio.biography_blurb.text, }} /> ) return ( <Responsive> {({ xs }) => { if (xs) { return ( <ReadMore onReadMoreClicked={this.props.onReadMoreClicked}> <Serif size="3">{blurb}</Serif> </ReadMore> ) } else { return ( <ReadMore onReadMoreClicked={this.props.onReadMoreClicked} maxLineCount={7} > <Serif size="3">{blurb}</Serif> </ReadMore> ) } }} </Responsive> ) } } export const ArtistBioFragmentContainer = createFragmentContainer( ArtistBio, graphql` fragment ArtistBio_bio on Artist { biography_blurb(format: HTML, partner_bio: true) { text credit } } ` )
Make sure to wrap bio html with typography
Make sure to wrap bio html with typography
TypeScript
mit
xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force
--- +++ @@ -1,3 +1,4 @@ +import { Serif } from "@artsy/palette" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { Responsive } from "Utils/Responsive" @@ -26,7 +27,7 @@ if (xs) { return ( <ReadMore onReadMoreClicked={this.props.onReadMoreClicked}> - {blurb} + <Serif size="3">{blurb}</Serif> </ReadMore> ) } else { @@ -35,7 +36,7 @@ onReadMoreClicked={this.props.onReadMoreClicked} maxLineCount={7} > - {blurb} + <Serif size="3">{blurb}</Serif> </ReadMore> ) }
849b8f22999ee734201122f919b5bdb2dd7135a9
src/sync/ArrayEnumerable.ts
src/sync/ArrayEnumerable.ts
import { IEnumerable } from "../types" /* eslint-disable @typescript-eslint/naming-convention */ /** * Array backed Enumerable */ export class ArrayEnumerable<TSource> extends Array<TSource> { } /** * Workaround * @private */ export interface ArrayEnumerable<TSource> extends IEnumerable<TSource> { reverse(): ArrayEnumerable<TSource> concat(items: IEnumerable<TSource>): IEnumerable<TSource> concat(...items: readonly TSource[]): ArrayEnumerable<TSource> // eslint-disable-next-line @typescript-eslint/array-type concat(...items: Array<TSource | ReadonlyArray<TSource>>): ArrayEnumerable<TSource> }
import { IEnumerable } from "../types" /* eslint-disable @typescript-eslint/naming-convention */ /** * Array backed Enumerable */ export class ArrayEnumerable<TSource> extends Array<TSource> { } /** * Workaround * @private */ export interface ArrayEnumerable<TSource> extends IEnumerable<TSource> { reverse(): ArrayEnumerable<TSource> concat(items: IEnumerable<TSource>): IEnumerable<TSource> concat(...items: ConcatArray<TSource>[]): ArrayEnumerable<TSource> concat(...items: (TSource | ConcatArray<TSource>)[]): ArrayEnumerable<TSource> }
Change Contact Definition for Array Enumerable
Change Contact Definition for Array Enumerable
TypeScript
mit
arogozine/LinqToTypeScript,arogozine/LinqToTypeScript
--- +++ @@ -16,7 +16,6 @@ export interface ArrayEnumerable<TSource> extends IEnumerable<TSource> { reverse(): ArrayEnumerable<TSource> concat(items: IEnumerable<TSource>): IEnumerable<TSource> - concat(...items: readonly TSource[]): ArrayEnumerable<TSource> - // eslint-disable-next-line @typescript-eslint/array-type - concat(...items: Array<TSource | ReadonlyArray<TSource>>): ArrayEnumerable<TSource> + concat(...items: ConcatArray<TSource>[]): ArrayEnumerable<TSource> + concat(...items: (TSource | ConcatArray<TSource>)[]): ArrayEnumerable<TSource> }
d61c30dc437eba05c0d1e0f7d4bf9a6c47c01af5
packages/schematics/src/scam/index.ts
packages/schematics/src/scam/index.ts
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema } from '@schematics/angular/module/schema'; export function scam(options: Schema): Rule { return chain([ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', { ...options, export: true, module: options.name }), ]); }
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; export inter export function scam(options: NgComponentOptions): Rule { return chain([ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', { ...options, export: true, module: options.name }), ]); }
Merge module and component as default behavior.
@wishtack/schematics:scam: Merge module and component as default behavior.
TypeScript
mit
wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids
--- +++ @@ -1,7 +1,10 @@ import { chain, externalSchematic, Rule } from '@angular-devkit/schematics'; -import { Schema } from '@schematics/angular/module/schema'; +import { Schema as NgComponentOptions } from '@schematics/angular/component/schema'; -export function scam(options: Schema): Rule { +export inter + +export function scam(options: NgComponentOptions): Rule { + return chain([ externalSchematic('@schematics/angular', 'module', options), externalSchematic('@schematics/angular', 'component', {
9d635ad519452544c38ca54a9ceb0bb4996255e7
webpack/plugins/index.ts
webpack/plugins/index.ts
const StringReplacePlugin = require('string-replace-webpack-plugin'); import constant from './const'; import minify from './minify'; import banner from './banner'; const env = process.env.NODE_ENV; const isProduction = env === 'production'; export default version => { const plugins = [ constant(), new StringReplacePlugin() ]; if (isProduction) { plugins.push(minify()); } plugins.push(banner(version)); return plugins; };
const StringReplacePlugin = require('string-replace-webpack-plugin'); import constant from './const'; import minify from './minify'; import banner from './banner'; const env = process.env.NODE_ENV; const isProduction = env === 'production'; export default version => { const plugins = [ constant(), new StringReplacePlugin() ]; /* if (isProduction) { plugins.push(minify()); } */ plugins.push(banner(version)); return plugins; };
Disable minification temporaly (Fuck Webkit)
Disable minification temporaly (Fuck Webkit)
TypeScript
mit
syuilo/Misskey,armchair-philosophy/misskey,Tosuke/misskey,ha-dai/Misskey,syuilo/Misskey,Tosuke/misskey,Tosuke/misskey,Tosuke/misskey,armchair-philosophy/misskey,armchair-philosophy/misskey,Tosuke/misskey,armchair-philosophy/misskey,ha-dai/Misskey
--- +++ @@ -12,11 +12,11 @@ constant(), new StringReplacePlugin() ]; - +/* if (isProduction) { plugins.push(minify()); } - +*/ plugins.push(banner(version)); return plugins;
bc4af11da5c68049974441e4679eeda5a150922e
src/app/classes/indent/indenter.spec.ts
src/app/classes/indent/indenter.spec.ts
import { Indenter } from './indenter'; describe('Indenter', () => { describe('using tabs', () => { let indenter = new Indenter(); describe("on single line", () => { it("should indent", () => { expect(indenter.indent('text')).toEqual('\ttext'); }); }); describe("on multiple lines", () => { it("should indent", () => { expect(indenter.indent('firstLine\nSecondLine')).toEqual('\tfirstLine\n\tSecondLine'); }); }); }); describe('using spaces', () => { let indenter = new Indenter(' '); describe("on single line", () => { it("should indent", () => { expect(indenter.indent('text')).toEqual(' text'); }); }); describe("on multiple lines", () => { it("should indent", () => { expect(indenter.indent('firstLine\nSecondLine')).toEqual(' firstLine\n SecondLine'); }); }); }); });
import { Indenter } from './indenter'; describe('Indenter', () => { describe('using tabs', () => { let indenter = new Indenter(); describe("on single line", () => { it("should indent", () => { expect(indenter.indent('text')).toEqual('\ttext'); }); }); describe("on multiple lines", () => { it("should indent", () => { expect(indenter.indent('firstLine\nSecondLine')).toEqual('\tfirstLine\n\tSecondLine'); }); }); }); describe('using spaces', () => { let indenter = new Indenter(' '); describe("on single line", () => { it("should indent", () => { expect(indenter.indent('text')).toEqual(' text'); }); }); describe("on multiple lines", () => { it("should indent", () => { expect(indenter.indent('firstLine\nSecondLine')).toEqual(' firstLine\n SecondLine'); }); }); }); it("should indent java method correctly", () => { let method = "@Override" + "\n" + "public BuildSingleFieldSample firstField(String firstField) {" + "\n" + "\tthis.firstField = firstField;" + "\n" + "\treturn this;" + "\n" + "}"; let indentedMethod = "\t@Override" + "\n\t" + "public BuildSingleFieldSample firstField(String firstField) {" + "\n\t" + "\tthis.firstField = firstField;" + "\n\t" + "\treturn this;" + "\n\t" + "}"; expect(new Indenter().indent(method)).toEqual(indentedMethod); }); });
Add more elaborate indent use case
Add more elaborate indent use case
TypeScript
mit
bvkatwijk/code-tools,bvkatwijk/code-tools,bvkatwijk/code-tools
--- +++ @@ -45,4 +45,20 @@ }); + it("should indent java method correctly", () => { + let method = + "@Override" + + "\n" + "public BuildSingleFieldSample firstField(String firstField) {" + + "\n" + "\tthis.firstField = firstField;" + + "\n" + "\treturn this;" + + "\n" + "}"; + let indentedMethod = + "\t@Override" + + "\n\t" + "public BuildSingleFieldSample firstField(String firstField) {" + + "\n\t" + "\tthis.firstField = firstField;" + + "\n\t" + "\treturn this;" + + "\n\t" + "}"; + expect(new Indenter().indent(method)).toEqual(indentedMethod); + }); + });
31c90141a60cbc10258e420b19d62b583067d0d9
tests/hoist-errors/Hello.ts
tests/hoist-errors/Hello.ts
interface FooInterface { foo: string, bar: number, //This interface should be stripped and the line numbers should still fit. } export const foo = () => { console.log('foo'); }; jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); export class Hello { constructor() { const greeting = ` this is a multiline greeting `; this.unexcuted(() => { }); throw new Error('Hello error!'); } public unexcuted(action: () => void = () => { }): void { if (action) { action(); } else { console.log('unexcuted'); } } } jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path'); jest.mock('path');
interface FooInterface { foo: string, bar: number, //This interface should be stripped and the line numbers should still fit. } export const foo = () => { console.log('foo'); }; export class Hello { constructor() { const greeting = ` this is a multiline greeting `; this.unexcuted(() => { }); throw new Error('Hello error!'); } public unexcuted(action: () => void = () => { }): void { if (action) { action(); } else { console.log('unexcuted'); } } }
Remove the mock calls from the test application file
Remove the mock calls from the test application file
TypeScript
mit
kulshekhar/ts-jest,kulshekhar/ts-jest
--- +++ @@ -1,19 +1,11 @@ interface FooInterface { - foo: string, - bar: number, //This interface should be stripped and the line numbers should still fit. + foo: string, + bar: number, //This interface should be stripped and the line numbers should still fit. } export const foo = () => { - console.log('foo'); + console.log('foo'); }; - - -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); export class Hello { constructor() { @@ -38,14 +30,3 @@ } } } - - -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path'); -jest.mock('path');
c84c794b0d7b1fc12ac193083b2c77753df9a52a
src/client/PreloadState.ts
src/client/PreloadState.ts
module Roomiverse { export class PreloadState extends Phaser.State { group : Phaser.Group preload() { this.group = this.add.group() this.group.alpha = 0 this.add.tween(this.group).to({ alpha: 1 }, 1000, Phaser.Easing.Linear.None, true) var bar = this.add.sprite(this.world.centerX - 400, this.world.centerY + 60, 'bar1', 0, this.group) this.load.setPreloadSprite(bar) this.load.audio('serenity', 'audio/serenity.ogg', true) var text = this.add.text(this.world.centerX, this.world.centerY, 'Loading', undefined, this.group) text.anchor.setTo(0.5, 0.5) text.font = 'Iceland' text.fontSize = 60 text.fill = '#acf' } create() { var tween = this.add.tween(this.group).to({ alpha: 0 }, 1000, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => this.game.state.start('Room')) } } }
module Roomiverse { export class PreloadState extends Phaser.State { group : Phaser.Group preload() { this.group = this.add.group() this.group.alpha = 0 this.add.tween(this.group).to({ alpha: 1 }, 1000, Phaser.Easing.Linear.None, true) var bar = this.add.sprite(this.world.centerX - 400, this.world.centerY + 60, 'bar', 0, this.group) this.load.setPreloadSprite(bar) this.load.audio('serenity', 'audio/serenity.ogg', true) var text = this.add.text(this.world.centerX, this.world.centerY, 'Loading', undefined, this.group) text.anchor.setTo(0.5, 0.5) text.font = 'Iceland' text.fontSize = 60 text.fill = '#acf' } create() { var tween = this.add.tween(this.group).to({ alpha: 0 }, 1000, Phaser.Easing.Linear.None, true) tween.onComplete.add(() => this.game.state.start('Room')) } } }
Fix copy paste error with bar1 vs bar
Fix copy paste error with bar1 vs bar
TypeScript
apache-2.0
shockkolate/roomiverse,shockkolate/roomiverse,shockkolate/roomiverse
--- +++ @@ -7,7 +7,7 @@ this.group.alpha = 0 this.add.tween(this.group).to({ alpha: 1 }, 1000, Phaser.Easing.Linear.None, true) - var bar = this.add.sprite(this.world.centerX - 400, this.world.centerY + 60, 'bar1', 0, this.group) + var bar = this.add.sprite(this.world.centerX - 400, this.world.centerY + 60, 'bar', 0, this.group) this.load.setPreloadSprite(bar) this.load.audio('serenity', 'audio/serenity.ogg', true)
255a54458e025aa3085199236110f5443d7b470c
server/bootstrap/broadcast.ts
server/bootstrap/broadcast.ts
const bonjour = require("bonjour")(); export default function(port = 443, httpOnly) { bonjour.publish({ name: `Thorium-${require("os").hostname()}`, type: "thorium-http", port: port, txt: {https: !httpOnly}, }); }
const bonjour = require("bonjour")(); export default function(port = 443, httpOnly) { bonjour.publish({ name: `Thorium-${require("os").hostname()}`, type: "thorium-http", port: port, txt: {https: String(process.env.NODE_ENV === "production" && !httpOnly)}, }); }
Fix the DNS txt record.
Fix the DNS txt record.
TypeScript
apache-2.0
Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium
--- +++ @@ -5,6 +5,6 @@ name: `Thorium-${require("os").hostname()}`, type: "thorium-http", port: port, - txt: {https: !httpOnly}, + txt: {https: String(process.env.NODE_ENV === "production" && !httpOnly)}, }); }
2f06735fe021a52b4150f96cce58df077479a396
app/src/ui/diff/selection/range-selection-strategy.ts
app/src/ui/diff/selection/range-selection-strategy.ts
import { DiffSelection } from '../../../models/diff' import { ISelectionStrategy } from './selection-strategy' import { DiffLineGutter } from '../diff-line-gutter' import { range } from '../../../lib/range' /** apply hunk selection to the current diff */ export class RangeSelection implements ISelectionStrategy { private readonly _start: number private readonly _end: number private readonly _desiredSelection: boolean private readonly _snapshot: DiffSelection public constructor( start: number, end: number, desiredSelection: boolean, snapshot: DiffSelection ) { this._start = start this._end = end this._desiredSelection = desiredSelection this._snapshot = snapshot } public update(index: number) { // no-op } public paint(elements: Map<number, DiffLineGutter>) { range(this._start, this._end).forEach(row => { const element = elements.get(row) if (!element) { // if the element has not been rendered, it's not visible to the user return } if (!element.isIncluded()) { return } const selected = this._desiredSelection element.setSelected(selected) }) } public done(): DiffSelection { const length = this._end - this._start + 1 const newSelection = this._snapshot.withRangeSelection( this._start, length, this._desiredSelection ) return newSelection } }
import { DiffSelection } from '../../../models/diff' import { ISelectionStrategy } from './selection-strategy' import { DiffLineGutter } from '../diff-line-gutter' import { range } from '../../../lib/range' /** apply hunk selection to the current diff */ export class RangeSelection implements ISelectionStrategy { private readonly _start: number private readonly _end: number private readonly _desiredSelection: boolean private readonly _snapshot: DiffSelection public constructor( start: number, end: number, desiredSelection: boolean, snapshot: DiffSelection ) { this._start = start this._end = end this._desiredSelection = desiredSelection this._snapshot = snapshot } public update(index: number) { // no-op } public paint(elements: Map<number, DiffLineGutter>) { range(this._start, this._end + 1).forEach(row => { const element = elements.get(row) if (!element) { // if the element has not been rendered, it's not visible to the user return } if (!element.isIncluded()) { return } const selected = this._desiredSelection element.setSelected(selected) }) } public done(): DiffSelection { const length = this._end - this._start + 1 const newSelection = this._snapshot.withRangeSelection( this._start, length, this._desiredSelection ) return newSelection } }
Fix off by one, include all lines in range
Fix off by one, include all lines in range
TypeScript
mit
j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,desktop/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop
--- +++ @@ -27,7 +27,7 @@ } public paint(elements: Map<number, DiffLineGutter>) { - range(this._start, this._end).forEach(row => { + range(this._start, this._end + 1).forEach(row => { const element = elements.get(row) if (!element) {
50cb66150a0bddd0f00e9dd1c8c865e4df77a192
node_modules/dimensions/extensions.ts
node_modules/dimensions/extensions.ts
import {LogOptions} from "dimensions/configloader"; import Extension from "dimensions/extension"; import ListenServer from "dimensions/listenserver"; import Logger from "dimensions/logger"; import {requireNoCache} from "dimensions/utils"; import * as glob from "glob"; import * as path from "path"; class Extensions { public static folder: string = "./extensions"; public static loadExtensions(extensionsList: Extension[], listenServers: { [name: string]: ListenServer }, options: LogOptions, logging: Logger) { glob.sync(`${this.folder}/**/index.js`).forEach((file) => { const extension: Extension = new (requireNoCache(path.resolve(file), require).default)(); extensionsList[extension.name] = extension; if (typeof extension.setListenServers === "function") { extension.setListenServers(listenServers); } if (options.extensionLoad) { if (options.outputToConsole) { console.log(`\u001b[36m[Extension] ${extension.name} ${extension.version} loaded.\u001b[37m`); } logging.appendLine(`[Extension] ${extension.name} ${extension.version} loaded.`); } }); } } export default Extensions;
import {LogOptions} from "dimensions/configloader"; import Extension from "dimensions/extension"; import ListenServer from "dimensions/listenserver"; import Logger from "dimensions/logger"; import {requireNoCache} from "dimensions/utils"; import * as glob from "glob"; import * as path from "path"; class Extensions { public static folder: string = "./extensions"; public static loadExtensions(extensionsList: Extension[], listenServers: { [name: string]: ListenServer }, options: LogOptions, logging: Logger) { try { glob.sync(`${this.folder}/**/index.js`).forEach((file) => { const extension: Extension = new (requireNoCache(path.resolve(file), require).default)(); extensionsList[extension.name] = extension; if (typeof extension.setListenServers === "function") { extension.setListenServers(listenServers); } if (options.extensionLoad) { if (options.outputToConsole) { console.log(`\u001b[36m[Extension] ${extension.name} ${extension.version} loaded.\u001b[37m`); } logging.appendLine(`[Extension] ${extension.name} ${extension.version} loaded.`); } }); } catch(e) { if (options.outputToConsole) { console.log("Failed to load extensions. Error: "); console.log(e); } logging.appendLine(`Failed to load extensions. Error: `); logging.appendLine(e); } } } export default Extensions;
Add error handling for extension loading
Add error handling for extension loading
TypeScript
mit
popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions
--- +++ @@ -10,21 +10,31 @@ public static folder: string = "./extensions"; public static loadExtensions(extensionsList: Extension[], listenServers: { [name: string]: ListenServer }, options: LogOptions, logging: Logger) { - glob.sync(`${this.folder}/**/index.js`).forEach((file) => { - const extension: Extension = new (requireNoCache(path.resolve(file), require).default)(); - extensionsList[extension.name] = extension; - if (typeof extension.setListenServers === "function") { - extension.setListenServers(listenServers); - } - - if (options.extensionLoad) { - if (options.outputToConsole) { - console.log(`\u001b[36m[Extension] ${extension.name} ${extension.version} loaded.\u001b[37m`); + try { + glob.sync(`${this.folder}/**/index.js`).forEach((file) => { + const extension: Extension = new (requireNoCache(path.resolve(file), require).default)(); + extensionsList[extension.name] = extension; + if (typeof extension.setListenServers === "function") { + extension.setListenServers(listenServers); } - logging.appendLine(`[Extension] ${extension.name} ${extension.version} loaded.`); + if (options.extensionLoad) { + if (options.outputToConsole) { + console.log(`\u001b[36m[Extension] ${extension.name} ${extension.version} loaded.\u001b[37m`); + } + + logging.appendLine(`[Extension] ${extension.name} ${extension.version} loaded.`); + } + }); + } catch(e) { + if (options.outputToConsole) { + console.log("Failed to load extensions. Error: "); + console.log(e); } - }); + + logging.appendLine(`Failed to load extensions. Error: `); + logging.appendLine(e); + } } }
d5d530e6cd3466f7207cefd40cd03c40a134f42d
app/src/lib/open-shell.ts
app/src/lib/open-shell.ts
import { spawn } from 'child_process' import { platform } from 'os' class Command { public name: string public args: string[] } /** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */ export function openShell(fullPath: string, shell?: string) { const currentPlatform = platform() const command = new Command switch (currentPlatform) { case 'darwin': { command.name = 'open' command.args = [ '-a', shell || 'Terminal', fullPath ] break } case 'win32': { command.name = 'start' command.args = [ '/D', '"%cd%"', shell || 'cmd', fullPath ] break } } return spawn(command.name, command.args) }
import { spawn } from 'child_process' import { platform } from 'os' class Command { public name: string public args: string[] } /** Opens a shell setting the working directory to fullpath. If a shell is not specified, OS defaults are used. */ export function openShell(fullPath: string, shell?: string) { const currentPlatform = platform() const command = new Command switch (currentPlatform) { case 'darwin': { command.name = 'open' command.args = [ '-a', shell || 'Terminal', fullPath ] break } case 'win32': { command.name = 'cmd.exe' command.args = [ '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ] break } } const process = spawn(command.name, command.args) process.stdout.on('data', (data) => { console.log(`stdout: ${data}`) }) process.stderr.on('data', (data) => { console.log(`stderr: ${data}`) }) process.on('close', (code) => { console.log(`process exited with code ${code}`) }) }
Add even-handlers to aid in debugging
Add even-handlers to aid in debugging
TypeScript
mit
shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,gengjiawen/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,kactus-io/kactus,j-f1/forked-desktop,BugTesterTest/desktops,artivilla/desktop,desktop/desktop,desktop/desktop,desktop/desktop,hjobrien/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,BugTesterTest/desktops,hjobrien/desktop,gengjiawen/desktop,hjobrien/desktop,gengjiawen/desktop,say25/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop
--- +++ @@ -18,11 +18,23 @@ break } case 'win32': { - command.name = 'start' - command.args = [ '/D', '"%cd%"', shell || 'cmd', fullPath ] + command.name = 'cmd.exe' + command.args = [ '/D', `"${fullPath}"` , 'title', 'GitHub Desktop' ] break } } - return spawn(command.name, command.args) + const process = spawn(command.name, command.args) + + process.stdout.on('data', (data) => { + console.log(`stdout: ${data}`) + }) + + process.stderr.on('data', (data) => { + console.log(`stderr: ${data}`) + }) + + process.on('close', (code) => { + console.log(`process exited with code ${code}`) + }) }
2d5f4a84231d1dfc0a3dfbb591d04edfae97806b
app/land/land.service.ts
app/land/land.service.ts
import {Injectable} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; import {CardService} from '../card/card.service'; import {Land} from './land'; @Injectable() export class LandService { constructor(private cardService: CardService) {} public getLands(): Observable<Land[]> { return this.cardService.getCards() .map((lands: Land[]) => { return _.filter(lands, (land: Land) => { return _.includes(land.types, 'Land'); }); }); } public getLandsWithMostColorIdentities(): Observable<Land[]> { return this.getLands() .map((lands: Land[]) => { return _.sortByOrder(lands, (land: Land) => { return _.size(land.colorIdentity); }, 'desc'); }) .map((lands: Land[]) => { return _.slice(lands, 0, 10); }); } }
import {Injectable} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; import {Card} from '../card/card'; import {CardService} from '../card/card.service'; import {Land} from './land'; @Injectable() export class LandService { constructor(private cardService: CardService) {} public getLands(): Observable<Land[]> { return this.cardService.getCards() .map((cards: Card[]) => { return _.filter(cards, (card: Card) => { return _.includes(card.types, 'Land'); }); }); } public getLandsWithMostColorIdentities(): Observable<Land[]> { return this.getLands() .map((lands: Land[]) => { return _.sortByOrder(lands, (land: Land) => { return _.size(land.colorIdentity); }, 'desc'); }) .map((lands: Land[]) => { return _.slice(lands, 0, 10); }); } }
Use type Card in getLands mapping
Use type Card in getLands mapping
TypeScript
mit
christianhg/magicalc,christianhg/magicalc,christianhg/magicalc
--- +++ @@ -1,6 +1,7 @@ import {Injectable} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; +import {Card} from '../card/card'; import {CardService} from '../card/card.service'; import {Land} from './land'; @@ -11,9 +12,9 @@ public getLands(): Observable<Land[]> { return this.cardService.getCards() - .map((lands: Land[]) => { - return _.filter(lands, (land: Land) => { - return _.includes(land.types, 'Land'); + .map((cards: Card[]) => { + return _.filter(cards, (card: Card) => { + return _.includes(card.types, 'Land'); }); }); }
bc8b65d3e89fd569dbd670ffef27d2ce8d6f499e
angular/src/app/sort/sort.component.ts
angular/src/app/sort/sort.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core"; import { I18nService } from "../i18n.service"; import { SortOrder } from "./sort-order"; @Component({ selector: "app-sort", templateUrl: "./sort.component.html", }) export class SortComponent implements OnInit { constructor(private readonly i18nService: I18nService) { } @Input() initialSortOrder: SortOrder; @Input() set isDistanceEnabled(isDistanceEnabled: boolean) { this._isDistanceEnabled = isDistanceEnabled; if (!isDistanceEnabled && this.sortOrder !== "name") { this.sortOrder = "name"; this.sortOrderChange.emit("name"); } } get isDistanceEnabled(): boolean { return this._isDistanceEnabled; } private _isDistanceEnabled: boolean; @Output() readonly sortOrderChange = new EventEmitter<SortOrder>(); readonly i18n = this.i18nService.getI18n(); sortOrder: SortOrder; ngOnInit() { this.sortOrder = this.initialSortOrder; } }
import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core"; import { I18nService } from "../i18n.service"; import { SortOrder } from "./sort-order"; @Component({ selector: "app-sort", templateUrl: "./sort.component.html", }) export class SortComponent implements OnInit { constructor(private readonly i18nService: I18nService) { } @Input() initialSortOrder: SortOrder; @Input() set isDistanceEnabled(isDistanceEnabled: boolean) { this._isDistanceEnabled = isDistanceEnabled; if (isDistanceEnabled && this.sortOrder !== "distance") { this.sortOrder = "distance"; this.sortOrderChange.emit("distance"); } else if (!isDistanceEnabled && this.sortOrder !== "name") { this.sortOrder = "name"; this.sortOrderChange.emit("name"); } } get isDistanceEnabled(): boolean { return this._isDistanceEnabled; } private _isDistanceEnabled: boolean; @Output() readonly sortOrderChange = new EventEmitter<SortOrder>(); readonly i18n = this.i18nService.getI18n(); sortOrder: SortOrder; ngOnInit() { this.sortOrder = this.initialSortOrder; } }
Switch to sort order "distance" automatically when geolocation is turned on
Switch to sort order "distance" automatically when geolocation is turned on
TypeScript
unknown
Berlin-Vegan/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map,smeir/berlin-vegan-map,smeir/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map,smeir/berlin-vegan-map,Berlin-Vegan/berlin-vegan-map
--- +++ @@ -15,7 +15,10 @@ @Input() set isDistanceEnabled(isDistanceEnabled: boolean) { this._isDistanceEnabled = isDistanceEnabled; - if (!isDistanceEnabled && this.sortOrder !== "name") { + if (isDistanceEnabled && this.sortOrder !== "distance") { + this.sortOrder = "distance"; + this.sortOrderChange.emit("distance"); + } else if (!isDistanceEnabled && this.sortOrder !== "name") { this.sortOrder = "name"; this.sortOrderChange.emit("name"); }
adc5c92fba38472ef152668dcb707c3984774b8f
app/src/ui/delete-branch/index.tsx
app/src/ui/delete-branch/index.tsx
import * as React from 'react' import { Dispatcher } from '../../lib/dispatcher' import { Repository } from '../../models/repository' import { Branch } from '../../models/branch' import { Button } from '../lib/button' import { ButtonGroup } from '../lib/button-group' import { Dialog, DialogContent, DialogFooter } from '../dialog' interface IDeleteBranchProps { readonly dispatcher: Dispatcher readonly repository: Repository readonly branch: Branch readonly onDismissed: () => void } export class DeleteBranch extends React.Component<IDeleteBranchProps, {}> { public render() { return ( <Dialog id="delete-branch" title={__DARWIN__ ? 'Delete Branch' : 'Delete branch'} type="warning" onDismissed={this.props.onDismissed} > <DialogContent> <p> Delete branch "{this.props.branch.name}"? </p> <p>This cannot be undone.</p> </DialogContent> <DialogFooter> <ButtonGroup destructive={true}> <Button type="submit">Cancel</Button> <Button onClick={this.deleteBranch}>Delete</Button> </ButtonGroup> </DialogFooter> </Dialog> ) } private deleteBranch = () => { this.props.dispatcher.deleteBranch(this.props.repository, this.props.branch, false) this.props.dispatcher.closePopup() } }
import * as React from 'react' import { Dispatcher } from '../../lib/dispatcher' import { Repository } from '../../models/repository' import { Branch } from '../../models/branch' import { Button } from '../lib/button' import { ButtonGroup } from '../lib/button-group' import { Dialog, DialogContent, DialogFooter } from '../dialog' interface IDeleteBranchProps { readonly dispatcher: Dispatcher readonly repository: Repository readonly branch: Branch readonly onDismissed: () => void } interface IDeleteBranchState { readonly includeRemoteBranch: boolean } export class DeleteBranch extends React.Component< IDeleteBranchProps, IDeleteBranchState > { public constructor(props: IDeleteBranchProps) { super(props) this.state = { includeRemoteBranch: false, } } public render() { return ( <Dialog id="delete-branch" title={__DARWIN__ ? 'Delete Branch' : 'Delete branch'} type="warning" onDismissed={this.props.onDismissed} > <DialogContent> <p> Delete branch "{this.props.branch.name}"? </p> <p>This cannot be undone.</p> </DialogContent> <DialogFooter> <ButtonGroup destructive={true}> <Button type="submit">Cancel</Button> <Button onClick={this.deleteBranch}>Delete</Button> </ButtonGroup> </DialogFooter> </Dialog> ) } private deleteBranch = () => { this.props.dispatcher.deleteBranch(this.props.repository, this.props.branch, false) this.props.dispatcher.closePopup() } }
Add state for including remote in delete
Add state for including remote in delete
TypeScript
mit
say25/desktop,kactus-io/kactus,hjobrien/desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,gengjiawen/desktop,desktop/desktop,say25/desktop,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,hjobrien/desktop,say25/desktop,gengjiawen/desktop,shiftkey/desktop,shiftkey/desktop,hjobrien/desktop,j-f1/forked-desktop,artivilla/desktop,hjobrien/desktop,gengjiawen/desktop
--- +++ @@ -14,7 +14,22 @@ readonly onDismissed: () => void } -export class DeleteBranch extends React.Component<IDeleteBranchProps, {}> { +interface IDeleteBranchState { + readonly includeRemoteBranch: boolean +} + +export class DeleteBranch extends React.Component< + IDeleteBranchProps, + IDeleteBranchState +> { + public constructor(props: IDeleteBranchProps) { + super(props) + + this.state = { + includeRemoteBranch: false, + } + } + public render() { return ( <Dialog
8df5f4a72b105f9e5b4a4376a2ae09c3755d83d8
src/app/services/classify.service.ts
src/app/services/classify.service.ts
import { Injectable } from '@angular/core'; import { Restangular } from 'ngx-restangular'; import { environment } from '../../environments/environment'; @Injectable() export class ClassifyService { constructor(private restangular:Restangular) { } classify(datasetId:string){ let classifyEndpoint = "service/datasets"; let restObj = this.restangular.oneUrl('classify', environment.servicesUrl + classifyEndpoint, datasetId); return restObj.customPOST(null, "classify", null, {}); } }
import { Injectable } from '@angular/core'; import { Restangular } from 'ngx-restangular'; import { environment } from '../../environments/environment'; @Injectable() export class ClassifyService { constructor(private restangular:Restangular) { } classify(datasetId:string){ let classifyEndpoint = "service/datasets/" + datasetId; let restObj = this.restangular.oneUrl('classify', environment.servicesUrl + classifyEndpoint); return restObj.customPOST(null, "classify", null, {}); } }
Fix classify endpoint with new url calls
Fix classify endpoint with new url calls
TypeScript
mit
hres/cfg-classification-webapp,hres/cfg-classification-webapp,hres/cfg-classification-webapp
--- +++ @@ -8,9 +8,9 @@ constructor(private restangular:Restangular) { } classify(datasetId:string){ - let classifyEndpoint = "service/datasets"; + let classifyEndpoint = "service/datasets/" + datasetId; - let restObj = this.restangular.oneUrl('classify', environment.servicesUrl + classifyEndpoint, datasetId); + let restObj = this.restangular.oneUrl('classify', environment.servicesUrl + classifyEndpoint); return restObj.customPOST(null, "classify", null, {}); }
4364d83df83ac9e51f245e67d50d03094c628d27
src/vibrate.android.ts
src/vibrate.android.ts
import { Common } from './vibrate.common'; import * as app from 'tns-core-modules/application'; export class Vibrate extends Common { constructor() { super(); this.service = app.android.context.getSystemService(android.content.Context.VIBRATOR_SERVICE); } hasVibrator(): boolean { return this.service.hasVibrator(); } vibrate(param: number | number[] = 300, repeat: number = -1) { if (this.hasVibrator()) { if (typeof param === "number") { this.service.vibrate(param); } else { let pattern = Array.create('long', param.length); pattern.forEach((element, index) => { pattern[index] = element; }); this.service.vibrate(pattern, repeat); } } } cancel() { this.service.cancel(); } }
import { Common } from './vibrate.common'; import * as app from 'tns-core-modules/application'; export class Vibrate extends Common { constructor() { super(); this.service = app.android.context.getSystemService(android.content.Context.VIBRATOR_SERVICE); } hasVibrator(): boolean { return this.service.hasVibrator(); } vibrate(param: number | number[] = 300, repeat: number = -1) { if (this.hasVibrator()) { if (typeof param === "number") { this.service.vibrate(param); } else { // Define array pattern length const patternLength = param.length; // Create the pattern array let pattern = Array.create('long', patternLength); // Assign the pattern values param.forEach((value, index) => { pattern[index] = value; }); // Vibrate pattern this.service.vibrate(pattern, repeat); } } } cancel() { this.service.cancel(); } }
Fix the vibration pattern on Android
Fix the vibration pattern on Android
TypeScript
mit
anarchicknight/nativescript-vibrate,bazzite/nativescript-vibrate,bazzite/nativescript-vibrate,bazzite/nativescript-vibrate
--- +++ @@ -17,9 +17,16 @@ if (typeof param === "number") { this.service.vibrate(param); } else { - let pattern = Array.create('long', param.length); - pattern.forEach((element, index) => { pattern[index] = element; }); + // Define array pattern length + const patternLength = param.length; + // Create the pattern array + let pattern = Array.create('long', patternLength); + + // Assign the pattern values + param.forEach((value, index) => { pattern[index] = value; }); + + // Vibrate pattern this.service.vibrate(pattern, repeat); } }
07e7f744c274edb3e426c35fbc687d5fe54f978e
src/test/typescript.ts
src/test/typescript.ts
import assert = require('assert'); import {Sequelize, Model, DataTypes} from 'sequelize'; import {Options, Attribute} from '../index'; import * as sinon from 'sinon'; // Just a dummy const sequelize: Sequelize = Object.create(Sequelize.prototype); describe('TypeScript', () => { it('should call Model.init with correct attributes and options', () => { const stub = sinon.stub(Model, 'init'); try { @Options({sequelize}) class User extends Model { @Attribute(DataTypes.STRING) public username: string; } assert(stub.calledOnce); const [[attributes, options]] = stub.args; assert.equal(typeof attributes, 'object'); assert.equal(attributes.username, DataTypes.STRING); assert.equal(typeof options, 'object'); assert.equal(options.sequelize, sequelize); } finally { stub.restore(); } }); });
import assert = require('assert'); import {Sequelize, Model, DataTypes} from 'sequelize'; import {Options, Attribute} from '../index'; import * as sinon from 'sinon'; // Just a dummy const sequelize: Sequelize = Object.create(Sequelize.prototype); describe('TypeScript', () => { it('should call Model.init with correct attributes and options', () => { const stub = sinon.stub(Model, 'init'); try { @Options({sequelize}) class User extends Model { @Attribute(DataTypes.STRING) public username: string; @Attribute() public street: string; @Attribute() public loginCount: number; @Attribute() public lastLogin: Date; @Attribute() public passwordHash: Buffer; } assert(stub.calledOnce); const [[attributes, options]] = stub.args; assert.equal(typeof attributes, 'object'); assert.equal(attributes.username, DataTypes.STRING); assert.equal(attributes.street, DataTypes.STRING); assert.equal(attributes.loginCount, DataTypes.INTEGER); assert.equal(attributes.lastLogin, DataTypes.DATE); assert.equal(attributes.passwordHash, DataTypes.BLOB); assert.equal(typeof options, 'object'); assert.equal(options.sequelize, sequelize); } finally { stub.restore(); } }); });
Add tests for type inference
Add tests for type inference
TypeScript
isc
felixfbecker/sequelize-decorators,felixfbecker/sequelize-decorators
--- +++ @@ -20,6 +20,18 @@ @Attribute(DataTypes.STRING) public username: string; + + @Attribute() + public street: string; + + @Attribute() + public loginCount: number; + + @Attribute() + public lastLogin: Date; + + @Attribute() + public passwordHash: Buffer; } assert(stub.calledOnce); @@ -28,6 +40,10 @@ assert.equal(typeof attributes, 'object'); assert.equal(attributes.username, DataTypes.STRING); + assert.equal(attributes.street, DataTypes.STRING); + assert.equal(attributes.loginCount, DataTypes.INTEGER); + assert.equal(attributes.lastLogin, DataTypes.DATE); + assert.equal(attributes.passwordHash, DataTypes.BLOB); assert.equal(typeof options, 'object'); assert.equal(options.sequelize, sequelize);
e0f49a763ef0d560ee0f410d11c9d440df32be20
src/app/error/error.component.spec.ts
src/app/error/error.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { TitleService } from '../shared/title.service'; import { MockTitleService } from '../shared/mocks/mock-title.service'; import { PageHeroComponent } from '../shared/page-hero/page-hero.component'; import { ErrorComponent } from './error.component'; describe('ErrorComponent', () => { const mockTitleService = new MockTitleService(); let component: ErrorComponent; let fixture: ComponentFixture<ErrorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PageHeroComponent, ErrorComponent ], providers: [ { provide: TitleService, useValue: mockTitleService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ErrorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create and show 404 text', () => { expect(component).toBeTruthy(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.basic-card > h2').textContent) .toContain('You’re looking a little lost there.'); }); it('should reset title', () => { expect(mockTitleService.mockTitle).toBe(''); }); });
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { TitleService } from '../shared/title.service'; import { MockTitleService } from '../shared/mocks/mock-title.service'; import { PageHeroComponent } from '../shared/page-hero/page-hero.component'; import { ErrorComponent } from './error.component'; describe('ErrorComponent', () => { const mockTitleService = new MockTitleService(); let component: ErrorComponent; let fixture: ComponentFixture<ErrorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ PageHeroComponent, ErrorComponent ], providers: [ { provide: TitleService, useValue: mockTitleService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(ErrorComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create and show 404 text', () => { expect(component).toBeTruthy(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.basic-card > h2').textContent) .toContain('You’re looking a little lost there.'); }); it('should reset title', () => { expect(mockTitleService.mockTitle).toBe(''); }); });
Add router testing module to Error Component tests
Add router testing module to Error Component tests Router links have been added to the error component and thuus the testing module is required.
TypeScript
apache-2.0
jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog
--- +++ @@ -1,4 +1,5 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; import { TitleService } from '../shared/title.service'; import { MockTitleService } from '../shared/mocks/mock-title.service'; @@ -14,6 +15,7 @@ beforeEach(async(() => { TestBed.configureTestingModule({ + imports: [ RouterTestingModule ], declarations: [ PageHeroComponent, ErrorComponent
9a8def7198336365590bf1a6b3c13b88b782c203
src/Parsing/Inline/GetInlineNodes.ts
src/Parsing/Inline/GetInlineNodes.ts
import { InlineSyntaxNode } from '../../SyntaxNodes/InlineSyntaxNode' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { TextConsumer } from '../TextConsumer' import { last } from '../CollectionHelpers' enum TokenMeaning { Text, EmphasisStart, EmphasisEnd } class Token { constructor(public meaning: TokenMeaning, public index: number, public value: string) { } } export function getInlineNodes(text: string): InlineSyntaxNode[] { return [new PlainTextNode(text)] } function tokenize(text: string): Token[] { const consumer = new TextConsumer(text) const tokens: Token[] = [] while (!consumer.done()) { const index = consumer.lengthConsumed() tokens.push(new Token(TokenMeaning.Text, index, consumer.escapedCurrentChar())) consumer.moveNext() } return withMergedConsecutiveTextTokens(tokens) } function withMergedConsecutiveTextTokens(tokens: Token[]): Token[] { return tokens.reduce((cleaned, current) => { const lastToken = last(cleaned) if (lastToken && (lastToken.meaning === TokenMeaning.Text) && (current.meaning === TokenMeaning.Text)) { lastToken.value += current.value return cleaned } return cleaned.concat([current]) }, []) } function parse(tokens: Token[]): InlineSyntaxNode[] { const nodes: InlineSyntaxNode[] = [] return nodes }
import { InlineSyntaxNode } from '../../SyntaxNodes/InlineSyntaxNode' import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode' import { TextConsumer } from '../TextConsumer' import { last } from '../CollectionHelpers' enum TokenMeaning { Text, EmphasisStart, EmphasisEnd } class Token { constructor(public meaning: TokenMeaning, public index: number, public value: string) { } } export function getInlineNodes(text: string): InlineSyntaxNode[] { return parse(tokenize(text)) } function tokenize(text: string): Token[] { const consumer = new TextConsumer(text) const tokens: Token[] = [] while (!consumer.done()) { const index = consumer.lengthConsumed() tokens.push(new Token(TokenMeaning.Text, index, consumer.escapedCurrentChar())) consumer.moveNext() } return withMergedConsecutiveTextTokens(tokens) } function withMergedConsecutiveTextTokens(tokens: Token[]): Token[] { return tokens.reduce((cleaned, current) => { const lastToken = last(cleaned) if (lastToken && (lastToken.meaning === TokenMeaning.Text) && (current.meaning === TokenMeaning.Text)) { lastToken.value += current.value return cleaned } return cleaned.concat([current]) }, []) } function parse(tokens: Token[]): InlineSyntaxNode[] { const nodes: InlineSyntaxNode[] = [] for (const token of tokens) { switch (token.meaning) { case TokenMeaning.Text: nodes.push(new PlainTextNode(token.value)) continue default: throw new Error('Unexpected token type') } } return nodes }
Use tokenizer; pass backslash tests
Use tokenizer; pass backslash tests
TypeScript
mit
start/up,start/up
--- +++ @@ -6,7 +6,7 @@ enum TokenMeaning { Text, EmphasisStart, - EmphasisEnd + EmphasisEnd } @@ -16,41 +16,52 @@ export function getInlineNodes(text: string): InlineSyntaxNode[] { - return [new PlainTextNode(text)] + return parse(tokenize(text)) } function tokenize(text: string): Token[] { const consumer = new TextConsumer(text) const tokens: Token[] = [] - + while (!consumer.done()) { const index = consumer.lengthConsumed() - + tokens.push(new Token(TokenMeaning.Text, index, consumer.escapedCurrentChar())) - + consumer.moveNext() } - + return withMergedConsecutiveTextTokens(tokens) } function withMergedConsecutiveTextTokens(tokens: Token[]): Token[] { return tokens.reduce((cleaned, current) => { - const lastToken = last(cleaned) - - if (lastToken && (lastToken.meaning === TokenMeaning.Text) && (current.meaning === TokenMeaning.Text)) { - lastToken.value += current.value - return cleaned - } - - return cleaned.concat([current]) - }, []) + const lastToken = last(cleaned) + + if (lastToken && (lastToken.meaning === TokenMeaning.Text) && (current.meaning === TokenMeaning.Text)) { + lastToken.value += current.value + return cleaned + } + + return cleaned.concat([current]) + }, []) } function parse(tokens: Token[]): InlineSyntaxNode[] { const nodes: InlineSyntaxNode[] = [] - + + for (const token of tokens) { + switch (token.meaning) { + case TokenMeaning.Text: + nodes.push(new PlainTextNode(token.value)) + continue + + default: + throw new Error('Unexpected token type') + } + } + return nodes }
9d6cedaba79e70186a08b5722a3c6db999504b98
src/app/todos/todos.component.spec.ts
src/app/todos/todos.component.spec.ts
import { TodosComponent } from './todos.component'; import { TestBed, ComponentFixture, async } from "@angular/core/testing"; describe('TodosComponent', function () { let component: TodosComponent; let fixture: ComponentFixture<TodosComponent>; beforeEach(async() => { TestBed.configureTestingModule({ declarations: [ TodosComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(TodosComponent); component = fixture.componentInstance; }); it('should create component', () => expect(component).toBeDefined()); });
import { TodosComponent } from './todos.component'; import { TodosInputComponent } from './input/todos-input.component'; import { TestBed, ComponentFixture, async } from "@angular/core/testing"; describe('TodosComponent', function () { let component: TodosComponent; let fixture: ComponentFixture<TodosComponent>; beforeEach(async() => { TestBed.configureTestingModule({ declarations: [ TodosComponent, TodosInputComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(TodosComponent); component = fixture.componentInstance; }); it('should create component', () => expect(component).toBeDefined()); });
Add TodosInputComponent to TestBend declarations
Add TodosInputComponent to TestBend declarations
TypeScript
mit
pawelec/todo-list,pawelec/todo-list,pawelec/todo-list,pawelec/todo-list
--- +++ @@ -1,4 +1,5 @@ import { TodosComponent } from './todos.component'; +import { TodosInputComponent } from './input/todos-input.component'; import { TestBed, ComponentFixture, async } from "@angular/core/testing"; @@ -8,7 +9,7 @@ beforeEach(async() => { TestBed.configureTestingModule({ - declarations: [ TodosComponent ] + declarations: [ TodosComponent, TodosInputComponent ] }) .compileComponents(); });
e0d470d1f4e0b87e529232b2666c92e7b02336ee
src/app/icon/iconmap.ts
src/app/icon/iconmap.ts
export const IconMap: any = { 'in progress' : ['pficon', 'pficon-resources-almost-full'], 'new' : ['fa', 'fa-arrow-down'], 'resolved' : ['pficon', 'pficon-resources-full'], 'open' : ['fa', 'fa-fire'], 'closed' : ['fa', 'fa-remove'], 'system.userstory' : ['fa', 'fa-bookmark'], 'system.valueproposition' : ['fa', 'fa-gift'], 'system.fundamental' : ['fa', 'fa-bank'], 'system.experience' : ['fa', 'fa-map'], 'system.feature' : ['fa', 'fa-mouse-pointer'], 'system.bug' : ['fa', 'fa-bug'], 'system.planneritem' : ['fa', 'fa-paint-brush'], 'default' : ['fa', 'fa-crosshairs'] // Never remove this line };
export const IconMap: any = { 'in progress' : ['pficon', 'pficon-resources-almost-full'], 'new' : ['fa', 'fa-arrow-down'], 'resolved' : ['pficon', 'pficon-resources-full'], 'open' : ['fa', 'fa-fire'], 'closed' : ['fa', 'fa-remove'], 'userstory' : ['fa', 'fa-bookmark'], 'valueproposition' : ['fa', 'fa-gift'], 'fundamental' : ['fa', 'fa-bank'], 'experience' : ['fa', 'fa-map'], 'feature' : ['fa', 'fa-mouse-pointer'], 'bug' : ['fa', 'fa-bug'], 'planneritem' : ['fa', 'fa-paint-brush'], 'default' : ['fa', 'fa-crosshairs'] // Never remove this line };
Update icon map to reflect the correct work item type icons
Update icon map to reflect the correct work item type icons
TypeScript
apache-2.0
fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui
--- +++ @@ -1,15 +1,15 @@ export const IconMap: any = { - 'in progress' : ['pficon', 'pficon-resources-almost-full'], - 'new' : ['fa', 'fa-arrow-down'], - 'resolved' : ['pficon', 'pficon-resources-full'], - 'open' : ['fa', 'fa-fire'], - 'closed' : ['fa', 'fa-remove'], - 'system.userstory' : ['fa', 'fa-bookmark'], - 'system.valueproposition' : ['fa', 'fa-gift'], - 'system.fundamental' : ['fa', 'fa-bank'], - 'system.experience' : ['fa', 'fa-map'], - 'system.feature' : ['fa', 'fa-mouse-pointer'], - 'system.bug' : ['fa', 'fa-bug'], - 'system.planneritem' : ['fa', 'fa-paint-brush'], - 'default' : ['fa', 'fa-crosshairs'] // Never remove this line + 'in progress' : ['pficon', 'pficon-resources-almost-full'], + 'new' : ['fa', 'fa-arrow-down'], + 'resolved' : ['pficon', 'pficon-resources-full'], + 'open' : ['fa', 'fa-fire'], + 'closed' : ['fa', 'fa-remove'], + 'userstory' : ['fa', 'fa-bookmark'], + 'valueproposition' : ['fa', 'fa-gift'], + 'fundamental' : ['fa', 'fa-bank'], + 'experience' : ['fa', 'fa-map'], + 'feature' : ['fa', 'fa-mouse-pointer'], + 'bug' : ['fa', 'fa-bug'], + 'planneritem' : ['fa', 'fa-paint-brush'], + 'default' : ['fa', 'fa-crosshairs'] // Never remove this line };
3185e27c795569effa4d6f2bf0e71b04a0d3284c
app/src/crash/index.tsx
app/src/crash/index.tsx
const startTime = Date.now() import * as React from 'react' import * as ReactDOM from 'react-dom' import { CrashApp } from './crash-app' if (!process.env.TEST_ENV) { /* This is the magic trigger for webpack to go compile * our sass into css and inject it into the DOM. */ require('./styles/crash.scss') } const container = document.createElement('div') container.id = 'desktop-crash-container' document.body.appendChild(container) ReactDOM.render(<CrashApp startTime={startTime} />, container)
const startTime = Date.now() import * as React from 'react' import * as ReactDOM from 'react-dom' import { CrashApp } from './crash-app' if (!process.env.TEST_ENV) { /* This is the magic trigger for webpack to go compile * our sass into css and inject it into the DOM. */ require('./styles/crash.scss') } document.body.classList.add(`platform-${process.platform}`) const container = document.createElement('div') container.id = 'desktop-crash-container' document.body.appendChild(container) ReactDOM.render(<CrashApp startTime={startTime} />, container)
Set the platform class for styles
Set the platform class for styles
TypeScript
mit
artivilla/desktop,say25/desktop,desktop/desktop,say25/desktop,hjobrien/desktop,artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,hjobrien/desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,kactus-io/kactus,hjobrien/desktop,gengjiawen/desktop
--- +++ @@ -11,6 +11,8 @@ require('./styles/crash.scss') } +document.body.classList.add(`platform-${process.platform}`) + const container = document.createElement('div') container.id = 'desktop-crash-container' document.body.appendChild(container)
23b0b1a7732caed69706301149b7019a5389389a
test/driver/CollectionLoader.spec.ts
test/driver/CollectionLoader.spec.ts
import CollectionLoader from '../../src/driver/CollectionLoader'; describe('Error Handling', () => { const loader = new CollectionLoader(); it('throws an error if module is not found', async () => { await expect(() => loader.get('1qaz')).rejects.toThrowError(/^Cannot find module '1qaz' from '.*'/); }); it('rejects invalid game module', async () => { await expect(() => loader.get('jest')).rejects.toThrowError('jest is not a valid game pack.'); }); });
import fs from 'fs'; import CollectionLoader from '../../src/driver/CollectionLoader'; describe('Normal Case', () => { let readFile: jest.SpyInstance<Promise<string | Buffer>>; beforeAll(() => { readFile = jest.spyOn(fs.promises, 'readFile').mockResolvedValueOnce(JSON.stringify({ dependencies: { '@karuta/sanguosha-pack': '^1.0.0', }, })); }); const loader = new CollectionLoader(); it('loads a valid module', async () => { const col = await loader.get('jest'); expect(col).toBeTruthy(); }); it('caches loaded modules', async () => { const col = await loader.get('jest'); expect(col).toBeTruthy(); }); afterAll(() => { readFile.mockRestore(); }); }); describe('Error Handling', () => { const loader = new CollectionLoader(); it('throws an error if module is not found', async () => { await expect(() => loader.get('1qaz')).rejects.toThrowError(/^Cannot find module '1qaz' from '.*'/); }); it('rejects invalid game module', async () => { await expect(() => loader.get('jest')).rejects.toThrowError('jest is not a valid game pack.'); }); });
Test normal cases of CollectionLoader
Test normal cases of CollectionLoader
TypeScript
agpl-3.0
takashiro/sanguosha-server,takashiro/sanguosha-server
--- +++ @@ -1,4 +1,34 @@ +import fs from 'fs'; + import CollectionLoader from '../../src/driver/CollectionLoader'; + +describe('Normal Case', () => { + let readFile: jest.SpyInstance<Promise<string | Buffer>>; + + beforeAll(() => { + readFile = jest.spyOn(fs.promises, 'readFile').mockResolvedValueOnce(JSON.stringify({ + dependencies: { + '@karuta/sanguosha-pack': '^1.0.0', + }, + })); + }); + + const loader = new CollectionLoader(); + + it('loads a valid module', async () => { + const col = await loader.get('jest'); + expect(col).toBeTruthy(); + }); + + it('caches loaded modules', async () => { + const col = await loader.get('jest'); + expect(col).toBeTruthy(); + }); + + afterAll(() => { + readFile.mockRestore(); + }); +}); describe('Error Handling', () => { const loader = new CollectionLoader();
53e3c3ee6876ac67d10c3c4ce9ec01b6ad523bcb
src/app/redux/modules/counter/index.test.ts
src/app/redux/modules/counter/index.test.ts
import { expect } from 'chai'; import * as counter from './'; import { ICounter, ICounterAction } from '../../../models/counter'; /** Module */ describe('Counter Module', () => { /** Actions */ describe('Actions', () => { describe('Increment', () => { it('has the correct type', () => { const action: ICounterAction = counter.increment(); expect(action.type).to.equal(counter.INCREMENT); }); }); describe('Decrement', () => { it('has the correct type', () => { const action: ICounterAction = counter.decrement(); expect(action.type).to.equal(counter.DECREMENT); }); }); }); /** Reducer */ describe('Reducer', () => { let state: ICounter = { count: 10 }; it('handles action of type INCREMENT', () => { const action: ICounterAction = { type: counter.INCREMENT }; expect(counter.counterReducer(state, action)).to.be.eql({ count: state.count + 1 }); }); it('handles action of type DECREMENT', () => { const action: ICounterAction = { type: counter.DECREMENT }; expect(counter.counterReducer(state, action)).to.be.eql({ count: state.count - 1 }); }); it('handles actions with unknown type', function() { expect(counter.counterReducer(state, { type: '' })).to.be.eql({ count: state.count }); }); }); });
import { expect } from 'chai'; import * as counter from './'; import { ICounter, ICounterAction } from '../../../models/counter'; /** Module */ describe('Counter Module', () => { /** Actions */ describe('Actions', () => { describe('Increment', () => { it('has the correct type', () => { const action: ICounterAction = counter.increment(); expect(action.type).to.equal(counter.INCREMENT); }); }); describe('Decrement', () => { it('has the correct type', () => { const action: ICounterAction = counter.decrement(); expect(action.type).to.equal(counter.DECREMENT); }); }); }); /** Reducer */ describe('Reducer', () => { let state: ICounter = { count: 10 }; it('handles action of type INCREMENT', () => { const action: ICounterAction = { type: counter.INCREMENT }; expect(counter.counterReducer(state, action)).to.be.eql({ count: state.count + 1 }); }); it('handles action of type DECREMENT', () => { const action: ICounterAction = { type: counter.DECREMENT }; expect(counter.counterReducer(state, action)).to.be.eql({ count: state.count - 1 }); }); it('handles actions with unknown type', () => { expect(counter.counterReducer(state, { type: '' })).to.be.eql({ count: state.count }); }); }); });
Replace "function ()" with "() =>"
Replace "function ()" with "() =>"
TypeScript
mit
devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine,devonzuegel/aldine
--- +++ @@ -37,7 +37,7 @@ expect(counter.counterReducer(state, action)).to.be.eql({ count: state.count - 1 }); }); - it('handles actions with unknown type', function() { + it('handles actions with unknown type', () => { expect(counter.counterReducer(state, { type: '' })).to.be.eql({ count: state.count }); });
7cbfbf8a80d9ad3d9ad88ad54ce151048f7bda96
frontend/javascript/snippets/search.ts
frontend/javascript/snippets/search.ts
function applyToForm(searchForm: HTMLFormElement) { function submitForm() { searchForm.submit(); } const inputs = searchForm.querySelectorAll('select, input[type="date"]'); let i; for (i = 0; i < inputs.length; i += 1) { const selectInput = inputs[i]; selectInput.addEventListener("change", submitForm); } function dropdownSubmit(input: HTMLInputElement) { return function(this: HTMLElement, e: Event) { e.preventDefault(); input.value = this.dataset.value || ""; searchForm.submit(); }; } const dropdowns = searchForm.querySelectorAll(".dropdown"); for (i = 0; i < dropdowns.length; i += 1) { const dropdown = dropdowns[i]; const input = dropdown.querySelector("input") as HTMLInputElement; const dropdownLinks = dropdown.querySelectorAll(".dropdown-menu a"); Array.from(dropdownLinks).forEach((dropdownLink) => { dropdownLink.addEventListener("click", dropdownSubmit(input)); }); } } let domSearchForm = document.querySelector(".search-form") as HTMLFormElement; if (domSearchForm !== null) { applyToForm(domSearchForm); }
function applyToForm(searchForm: HTMLFormElement) { function submitForm() { searchForm.submit(); } const inputs = searchForm.querySelectorAll('select'); let i; for (i = 0; i < inputs.length; i += 1) { const selectInput = inputs[i]; selectInput.addEventListener("change", submitForm); } function dropdownSubmit(input: HTMLInputElement) { return function(this: HTMLElement, e: Event) { e.preventDefault(); input.value = this.dataset.value || ""; searchForm.submit(); }; } const dropdowns = searchForm.querySelectorAll(".dropdown"); for (i = 0; i < dropdowns.length; i += 1) { const dropdown = dropdowns[i]; const input = dropdown.querySelector("input") as HTMLInputElement; const dropdownLinks = dropdown.querySelectorAll(".dropdown-menu a"); Array.from(dropdownLinks).forEach((dropdownLink) => { dropdownLink.addEventListener("click", dropdownSubmit(input)); }); } } let domSearchForm = document.querySelector(".search-form") as HTMLFormElement; if (domSearchForm !== null) { applyToForm(domSearchForm); }
Remove date input from auto-submit on change
Remove date input from auto-submit on change
TypeScript
mit
fin/froide,fin/froide,fin/froide,fin/froide
--- +++ @@ -2,7 +2,7 @@ function submitForm() { searchForm.submit(); } - const inputs = searchForm.querySelectorAll('select, input[type="date"]'); + const inputs = searchForm.querySelectorAll('select'); let i; for (i = 0; i < inputs.length; i += 1) { const selectInput = inputs[i];
2e46ef9480bfd77296c06c1851d5eb46560b7b6b
packages/authentication/src/user-model.service.ts
packages/authentication/src/user-model.service.ts
import { DefaultIdAndTimeStamps, Sequelize, SequelizeConnectionService, SequelizeModelService } from '@foal/sequelize'; export interface BaseUser { isAdmin: boolean; } export abstract class UserModelService<User, CreatingUser = User, IIdAndTimeStamps extends { id: any; } = DefaultIdAndTimeStamps, IdType = number> extends SequelizeModelService<User, CreatingUser, IIdAndTimeStamps, IdType> { constructor(schema: object, connection: SequelizeConnectionService, private parsers: ((data: CreatingUser) => void)[] = []) { super('users', { ...schema, isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false } }, connection); } public createOne(data: CreatingUser): Promise<User & IIdAndTimeStamps> { this.parsers.forEach(parser => parser(data)); return super.createOne(data); } public createMany(records: CreatingUser[]): Promise<(User & IIdAndTimeStamps)[]> { for (const record of records) { this.parsers.forEach(parser => parser(record)); } return super.createMany(records); } }
import { DefaultIdAndTimeStamps, Sequelize, SequelizeConnectionService, SequelizeModelService } from '@foal/sequelize'; export interface BaseUser { isAdmin: boolean; } export abstract class UserModelService<User, CreatingUser = User, IIdAndTimeStamps extends { id: any; } = DefaultIdAndTimeStamps, IdType = number> extends SequelizeModelService<User, CreatingUser, IIdAndTimeStamps, IdType> { constructor(schema: object, connection: SequelizeConnectionService, private parsers: ((data: CreatingUser) => void|Promise<void>)[] = []) { super('users', { ...schema, isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false } }, connection); } public async createOne(data: CreatingUser): Promise<User & IIdAndTimeStamps> { for (const parser of this.parsers) { await parser(data); } return super.createOne(data); } public async createMany(records: CreatingUser[]): Promise<(User & IIdAndTimeStamps)[]> { for (const record of records) { for (const parser of this.parsers) { await parser(record); } } return super.createMany(records); } }
Fix async issue with parsers.
Fix async issue with parsers.
TypeScript
mit
FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal
--- +++ @@ -13,21 +13,25 @@ IIdAndTimeStamps extends { id: any; } = DefaultIdAndTimeStamps, IdType = number> extends SequelizeModelService<User, CreatingUser, IIdAndTimeStamps, IdType> { constructor(schema: object, connection: SequelizeConnectionService, - private parsers: ((data: CreatingUser) => void)[] = []) { + private parsers: ((data: CreatingUser) => void|Promise<void>)[] = []) { super('users', { ...schema, isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false } }, connection); } - public createOne(data: CreatingUser): Promise<User & IIdAndTimeStamps> { - this.parsers.forEach(parser => parser(data)); + public async createOne(data: CreatingUser): Promise<User & IIdAndTimeStamps> { + for (const parser of this.parsers) { + await parser(data); + } return super.createOne(data); } - public createMany(records: CreatingUser[]): Promise<(User & IIdAndTimeStamps)[]> { + public async createMany(records: CreatingUser[]): Promise<(User & IIdAndTimeStamps)[]> { for (const record of records) { - this.parsers.forEach(parser => parser(record)); + for (const parser of this.parsers) { + await parser(record); + } } return super.createMany(records); }
89b4caab0062f6f5ca078515becd11f675b5f3f4
src/v2/Components/__tests__/Footer.jest.tsx
src/v2/Components/__tests__/Footer.jest.tsx
import { MockBoot } from "v2/DevTools/MockBoot" import { mount } from "enzyme" import React from "react" import { Footer, LargeFooter, SmallFooter } from "../Footer" describe("Footer", () => { beforeAll(() => { window.matchMedia = undefined // Immediately set matching media query in Boot }) it("is responsive", () => { const small = mount( <MockBoot breakpoint="xs"> <Footer /> </MockBoot> ) expect(small.find(SmallFooter).length).toEqual(1) const large = mount( <MockBoot breakpoint="lg"> <Footer /> </MockBoot> ) expect(large.find(LargeFooter).length).toEqual(1) }) })
import { MockBoot } from "v2/DevTools/MockBoot" import { mount } from "enzyme" import React from "react" import { Footer, LargeFooter, SmallFooter } from "../Footer" import { DownloadAppBadge } from "v2/Components/DownloadAppBadge" describe("Footer", () => { beforeAll(() => { window.matchMedia = undefined // Immediately set matching media query in Boot }) const getSmallFooterWrapper = () => mount( <MockBoot breakpoint="xs"> <Footer /> </MockBoot> ) const getLargeFooterWrapper = () => mount( <MockBoot breakpoint="lg"> <Footer /> </MockBoot> ) it("is responsive", () => { const small = getSmallFooterWrapper() expect(small.find(SmallFooter).length).toEqual(1) const large = getLargeFooterWrapper() expect(large.find(LargeFooter).length).toEqual(1) }) it("renders prompts to download the app", () => { const small = getSmallFooterWrapper() const large = getLargeFooterWrapper() expect(small.find("DownloadAppBanner").length).toEqual(0) expect(large.find("DownloadAppBanner").length).toEqual(1) expect(small.find(DownloadAppBadge).length).toEqual(1) expect(large.find(DownloadAppBadge).length).toEqual(1) }) })
Add tests for download app components
Add tests for download app components
TypeScript
mit
artsy/force-public,joeyAghion/force,joeyAghion/force,joeyAghion/force,artsy/force,artsy/force,joeyAghion/force,artsy/force,artsy/force-public,artsy/force
--- +++ @@ -2,25 +2,42 @@ import { mount } from "enzyme" import React from "react" import { Footer, LargeFooter, SmallFooter } from "../Footer" +import { DownloadAppBadge } from "v2/Components/DownloadAppBadge" describe("Footer", () => { beforeAll(() => { window.matchMedia = undefined // Immediately set matching media query in Boot }) - it("is responsive", () => { - const small = mount( + const getSmallFooterWrapper = () => + mount( <MockBoot breakpoint="xs"> <Footer /> </MockBoot> ) - expect(small.find(SmallFooter).length).toEqual(1) - const large = mount( + const getLargeFooterWrapper = () => + mount( <MockBoot breakpoint="lg"> <Footer /> </MockBoot> ) + + it("is responsive", () => { + const small = getSmallFooterWrapper() + expect(small.find(SmallFooter).length).toEqual(1) + + const large = getLargeFooterWrapper() expect(large.find(LargeFooter).length).toEqual(1) }) + + it("renders prompts to download the app", () => { + const small = getSmallFooterWrapper() + const large = getLargeFooterWrapper() + + expect(small.find("DownloadAppBanner").length).toEqual(0) + expect(large.find("DownloadAppBanner").length).toEqual(1) + expect(small.find(DownloadAppBadge).length).toEqual(1) + expect(large.find(DownloadAppBadge).length).toEqual(1) + }) })
8cb6dd4a6be85b9d56150f194034f6bfdf2d6be8
lib/typescript/contact.ts
lib/typescript/contact.ts
import { RequestPromise } from 'request-promise' import { Properties } from './contact_property' declare class Contact { get(opts?: {}): RequestPromise getByEmail(email: string): RequestPromise getByEmailBatch(email: string[]): RequestPromise getById(number: string): RequestPromise getByIdBatch(ids: number[]): RequestPromise getByToken(utk: string): RequestPromise update(id: number, data: {}): RequestPromise create(data: {}): RequestPromise createOrUpdateBatch(data: any[]): RequestPromise search(query: string): RequestPromise getRecentlyCreated(opts: {}): RequestPromise getRecentlyModified(opts: {}): RequestPromise createOrUpdate(email: string, data: any[]): RequestPromise delete(id: number): RequestPromise properties: Properties } export { Contact }
import { RequestPromise } from 'request-promise' import { Properties } from './contact_property' declare class Contact { get(opts?: {}): RequestPromise getByEmail(email: string): RequestPromise getByEmailBatch(email: string[]): RequestPromise getById(number: string): RequestPromise getByIdBatch(ids: number[]): RequestPromise getByToken(utk: string): RequestPromise update(id: number, data: {}): RequestPromise create(data: {}): RequestPromise createOrUpdateBatch(data: any[]): RequestPromise search(query: string): RequestPromise getRecentlyCreated(opts: {}): RequestPromise getRecentlyModified(opts: {}): RequestPromise createOrUpdate(email: string, data: {}): RequestPromise delete(id: number): RequestPromise properties: Properties } export { Contact }
Solve isse with createOrUpdate typescript data type -> should be an object and not an array
fix: Solve isse with createOrUpdate typescript data type -> should be an object and not an array
TypeScript
mit
brainflake/node-hubspot,brainflake/node-hubspot
--- +++ @@ -26,7 +26,7 @@ getRecentlyModified(opts: {}): RequestPromise - createOrUpdate(email: string, data: any[]): RequestPromise + createOrUpdate(email: string, data: {}): RequestPromise delete(id: number): RequestPromise
afcb0aaf303f64a8558be312396dea1791133521
src/viewmodel/CanvasFileViewModel.ts
src/viewmodel/CanvasFileViewModel.ts
import Transform from '../lib/geometry/Transform'; import Variable from "../lib/rx/Variable"; import CanvasFile from "../model/CanvasFile"; import User from "../model/User"; import * as Auth from "../Auth"; declare module gapi.drive.share { export var ShareClient: any; } export default class CanvasFileViewModel { id: string; name = new Variable(""); modifiedTime = new Variable(new Date()); constructor(file: CanvasFile) { this.id = file.id; this.update(file); } update(file: CanvasFile) { if (this.id != file.id) { throw new Error("wrong file ID"); } this.name.value = file.name; this.modifiedTime.value = file.modifiedTime; } get file() { return new CanvasFile({ id: this.id, name: this.name.value, modifiedTime: this.modifiedTime.value }); } async rename(name: string) { this.name.value = name; await CanvasFile.rename(this.id, name); } dispose() { } async openShareDialog() { const shareClient = new gapi.drive.share.ShareClient(); shareClient.setOAuthToken(Auth.accessToken); shareClient.setItemIds([this.id]); shareClient.showSettingsDialog(); } }
import Transform from '../lib/geometry/Transform'; import Variable from "../lib/rx/Variable"; import CanvasFile from "../model/CanvasFile"; import User from "../model/User"; import * as Auth from "../Auth"; declare module gapi.drive.share { export var ShareClient: any; } export default class CanvasFileViewModel { id: string; name = new Variable(""); modifiedTime = new Variable(new Date()); constructor(file: CanvasFile) { this.id = file.id; this.update(file); } update(file: CanvasFile) { if (this.id != file.id) { throw new Error("wrong file ID"); } this.name.value = file.name; this.modifiedTime.value = file.modifiedTime; } get file() { return new CanvasFile({ id: this.id, name: this.name.value, modifiedTime: this.modifiedTime.value }); } async rename(name: string) { if (this.name.value != name) { this.name.value = name; await CanvasFile.rename(this.id, name); } } dispose() { } async openShareDialog() { const shareClient = new gapi.drive.share.ShareClient(); shareClient.setOAuthToken(Auth.accessToken); shareClient.setItemIds([this.id]); shareClient.showSettingsDialog(); } }
Send rename request only if needed
Send rename request only if needed
TypeScript
mit
seanchas116/sketch-glass,seanchas116/sketch-glass,seanchas116/sketch-glass
--- +++ @@ -36,8 +36,10 @@ } async rename(name: string) { - this.name.value = name; - await CanvasFile.rename(this.id, name); + if (this.name.value != name) { + this.name.value = name; + await CanvasFile.rename(this.id, name); + } } dispose() {
7130c4dfab01a2b4232224d48a6bbe32d3c774ef
src/lib/finalMetrics.ts
src/lib/finalMetrics.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 {Metric} from '../types.js'; export const finalMetrics: WeakSet<Metric>|Set<Metric> = 'WeakSet' in window ? new WeakSet() : new Set();
/* * 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 {Metric} from '../types.js'; export const finalMetrics: WeakSet<Metric>|Set<Metric> = typeof WeakSet === 'function' ? new WeakSet() : new Set();
Check typeof instead of window attribute
Check typeof instead of window attribute
TypeScript
apache-2.0
GoogleChrome/web-vitals,GoogleChrome/web-vitals
--- +++ @@ -16,6 +16,6 @@ import {Metric} from '../types.js'; -export const finalMetrics: WeakSet<Metric>|Set<Metric> = 'WeakSet' in window +export const finalMetrics: WeakSet<Metric>|Set<Metric> = typeof WeakSet === 'function' ? new WeakSet() : new Set();
d695a94c9e03f99cd089dcd8e35d795541bd68c4
samples/ImplicitFlow/AureliaApp/src/open-id-connect-configuration.ts
samples/ImplicitFlow/AureliaApp/src/open-id-connect-configuration.ts
import environment from "./environment"; import { OpenIdConnectConfiguration } from "aurelia-open-id-connect"; import { UserManagerSettings, WebStorageStateStore } from "oidc-client"; const oidcConfig: OpenIdConnectConfiguration = { loginRedirectModuleId: "home", logoutRedirectModuleId: "home", userManagerSettings: <UserManagerSettings>{ // number of seconds in advance of access token expiry // to raise the access token expiring event accessTokenExpiringNotificationTime: 1, authority: environment.urls.authority, automaticSilentRenew: false, // true, // interval in milliseconds to check the user's session checkSessionInterval: 10000, client_id: "aurelia", filterProtocolClaims: true, loadUserInfo: false, post_logout_redirect_uri: `${environment.urls.host}/signout-oidc`, redirect_uri: `${environment.urls.host}/signin-oidc`, response_type: "id_token token", scope: "openid email roles profile", // number of millisecods to wait for the authorization // server to response to silent renew request silentRequestTimeout: 10000, silent_redirect_uri: `${environment.urls.host}/signin-oidc`, userStore: new WebStorageStateStore({ prefix: "oidc", store: window.localStorage, }), }, }; export default oidcConfig;
import environment from "./environment"; import { OpenIdConnectConfiguration } from "aurelia-open-id-connect"; import { UserManagerSettings, WebStorageStateStore } from "oidc-client"; const oidcConfig: OpenIdConnectConfiguration = { loginRedirectModuleId: "home", logoutRedirectModuleId: "home", userManagerSettings: <UserManagerSettings>{ // number of seconds in advance of access token expiry // to raise the access token expiring event accessTokenExpiringNotificationTime: 3585, authority: environment.urls.authority, automaticSilentRenew: true, // interval in milliseconds to check the user's session checkSessionInterval: 10000, client_id: "aurelia", filterProtocolClaims: true, loadUserInfo: false, post_logout_redirect_uri: `${environment.urls.host}/signout-oidc`, redirect_uri: `${environment.urls.host}/signin-oidc`, response_type: "id_token token", scope: "openid email roles profile", // number of millisecods to wait for the authorization // server to response to silent renew request silentRequestTimeout: 10000, silent_redirect_uri: `${environment.urls.host}/signin-oidc` }, }; export default oidcConfig;
Update the OIDC implicit flow sample settings to avoid using WebStorageStateStore
Update the OIDC implicit flow sample settings to avoid using WebStorageStateStore
TypeScript
apache-2.0
shaunluttin/openiddict-samples,openiddict/openiddict-samples
--- +++ @@ -8,9 +8,9 @@ userManagerSettings: <UserManagerSettings>{ // number of seconds in advance of access token expiry // to raise the access token expiring event - accessTokenExpiringNotificationTime: 1, + accessTokenExpiringNotificationTime: 3585, authority: environment.urls.authority, - automaticSilentRenew: false, // true, + automaticSilentRenew: true, // interval in milliseconds to check the user's session checkSessionInterval: 10000, client_id: "aurelia", @@ -23,11 +23,7 @@ // number of millisecods to wait for the authorization // server to response to silent renew request silentRequestTimeout: 10000, - silent_redirect_uri: `${environment.urls.host}/signin-oidc`, - userStore: new WebStorageStateStore({ - prefix: "oidc", - store: window.localStorage, - }), + silent_redirect_uri: `${environment.urls.host}/signin-oidc` }, };
b8cafd576eb91616ac54b2f9871cca0760815045
src/components/StructureSpawn.ts
src/components/StructureSpawn.ts
// --- Constants --- const CREEP_BODY = [MOVE, WORK, CARRY, MOVE] // --- Methods --- StructureSpawn.prototype.run = function(this: StructureSpawn) { if (this.canCreateCreep(CREEP_BODY) === OK) { this.createCreep(CREEP_BODY) } }
// --- Constants --- const CREEP_BODY = [MOVE, MOVE, WORK, CARRY, MOVE] // --- Methods --- StructureSpawn.prototype.run = function(this: StructureSpawn) { if (this.canCreateCreep(CREEP_BODY) === OK) { this.createCreep(CREEP_BODY) } }
Increase creep body size to use all available energy
Increase creep body size to use all available energy
TypeScript
unlicense
tinnvec/aints,tinnvec/aints
--- +++ @@ -1,6 +1,6 @@ // --- Constants --- -const CREEP_BODY = [MOVE, WORK, CARRY, MOVE] +const CREEP_BODY = [MOVE, MOVE, WORK, CARRY, MOVE] // --- Methods ---
b63c52a79dc04f9ef3305ea22ab22a1e0ccc1b20
src/browser/vcs/vcs.effects.ts
src/browser/vcs/vcs.effects.ts
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { Actions, Effect } from '@ngrx/effects'; import { Action } from '@ngrx/store'; import { of } from 'rxjs'; import { catchError, debounceTime, filter, map, switchMap } from 'rxjs/operators'; import { UpdateFileChangesAction, UpdateFileChangesErrorAction } from './vcs.actions'; import { VcsService } from './vcs.service'; export const VCS_DETECT_CHANGES_THROTTLE_TIME = 250; export const VCS_DETECT_CHANGES_EFFECT_ACTIONS = new InjectionToken<any[]>('VcsDetectChangesEffectActions'); @Injectable() export class VcsEffects { readonly detectChangesEffectActions: any[]; @Effect() detectChanges = this.actions.pipe( filter((action: Action) => this.detectChangesEffectActions.some(type => action.type === type)), debounceTime(VCS_DETECT_CHANGES_THROTTLE_TIME), switchMap(() => this.vcsService.fetchFileChanges()), map(fileChanges => new UpdateFileChangesAction({ fileChanges })), catchError(error => of(new UpdateFileChangesErrorAction(error))), ); constructor( private actions: Actions, private vcsService: VcsService, @Optional() @Inject(VCS_DETECT_CHANGES_EFFECT_ACTIONS) effectActions: any[], ) { this.detectChangesEffectActions = effectActions || []; } }
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core'; import { Actions, Effect } from '@ngrx/effects'; import { Action } from '@ngrx/store'; import { of } from 'rxjs'; import { catchError, debounceTime, filter, map, switchMap } from 'rxjs/operators'; import { UpdateFileChangesAction, UpdateFileChangesErrorAction, VcsActionTypes } from './vcs.actions'; import { VcsService } from './vcs.service'; export const VCS_DETECT_CHANGES_THROTTLE_TIME = 250; export const VCS_DETECT_CHANGES_EFFECT_ACTIONS = new InjectionToken<any[]>('VcsDetectChangesEffectActions'); @Injectable() export class VcsEffects { readonly detectChangesEffectActions: any[]; @Effect() detectChanges = this.actions.pipe( filter((action: Action) => this.detectChangesEffectActions.some(type => action.type === type)), debounceTime(VCS_DETECT_CHANGES_THROTTLE_TIME), switchMap(() => this.vcsService.fetchFileChanges()), map(fileChanges => new UpdateFileChangesAction({ fileChanges })), catchError(error => of(new UpdateFileChangesErrorAction(error))), ); constructor( private actions: Actions, private vcsService: VcsService, @Optional() @Inject(VCS_DETECT_CHANGES_EFFECT_ACTIONS) effectActions: any[], ) { this.detectChangesEffectActions = (effectActions || []).concat([ VcsActionTypes.COMMITTED, ]); } }
Add 'COMMITTED' action as default effect action
Add 'COMMITTED' action as default effect action
TypeScript
mit
seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary
--- +++ @@ -3,7 +3,7 @@ import { Action } from '@ngrx/store'; import { of } from 'rxjs'; import { catchError, debounceTime, filter, map, switchMap } from 'rxjs/operators'; -import { UpdateFileChangesAction, UpdateFileChangesErrorAction } from './vcs.actions'; +import { UpdateFileChangesAction, UpdateFileChangesErrorAction, VcsActionTypes } from './vcs.actions'; import { VcsService } from './vcs.service'; @@ -30,6 +30,8 @@ private vcsService: VcsService, @Optional() @Inject(VCS_DETECT_CHANGES_EFFECT_ACTIONS) effectActions: any[], ) { - this.detectChangesEffectActions = effectActions || []; + this.detectChangesEffectActions = (effectActions || []).concat([ + VcsActionTypes.COMMITTED, + ]); } }
83de424dd9143cd19c2d9322e1857a37264e6e7d
src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx
src/lib/Scenes/ArtistSeries/ArtistSeriesHeader.tsx
import { Flex } from "@artsy/palette" import { ArtistSeriesHeader_artistSeries } from "__generated__/ArtistSeriesHeader_artistSeries.graphql" import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" import React from "react" import { createFragmentContainer, graphql } from "react-relay" interface ArtistSeriesHeaderProps { artistSeries: ArtistSeriesHeader_artistSeries } export const ArtistSeriesHeader: React.SFC<ArtistSeriesHeaderProps> = ({ artistSeries }) => { const url = artistSeries.image?.url! return ( <Flex flexDirection="row" justifyContent="center"> <OpaqueImageView width={180} height={180} imageURL={url} style={{ borderRadius: 2 }} /> </Flex> ) } export const ArtistSeriesHeaderFragmentContainer = createFragmentContainer(ArtistSeriesHeader, { artistSeries: graphql` fragment ArtistSeriesHeader_artistSeries on ArtistSeries { image { url } } `, })
import { Flex } from "@artsy/palette" import { ArtistSeriesHeader_artistSeries } from "__generated__/ArtistSeriesHeader_artistSeries.graphql" import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView" import React from "react" import { createFragmentContainer, graphql } from "react-relay" interface ArtistSeriesHeaderProps { artistSeries: ArtistSeriesHeader_artistSeries } export const ArtistSeriesHeader: React.SFC<ArtistSeriesHeaderProps> = ({ artistSeries }) => { const url = artistSeries.image?.url! return ( <Flex flexDirection="row" justifyContent="center" pt={1}> <OpaqueImageView width={180} height={180} imageURL={url} style={{ borderRadius: 2 }} /> </Flex> ) } export const ArtistSeriesHeaderFragmentContainer = createFragmentContainer(ArtistSeriesHeader, { artistSeries: graphql` fragment ArtistSeriesHeader_artistSeries on ArtistSeries { image { url } } `, })
Fix whitespace above header image
style: Fix whitespace above header image
TypeScript
mit
artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen,artsy/eigen
--- +++ @@ -11,7 +11,7 @@ const url = artistSeries.image?.url! return ( - <Flex flexDirection="row" justifyContent="center"> + <Flex flexDirection="row" justifyContent="center" pt={1}> <OpaqueImageView width={180} height={180} imageURL={url} style={{ borderRadius: 2 }} /> </Flex> )
3e5aeb7ac1b033d1a61b8b51f8e12aacb72e2c35
server/dbconnection.test.ts
server/dbconnection.test.ts
import MongodbMemoryServer from "mongodb-memory-server"; describe("", () => { test("", async (done) => { const mongod = new MongodbMemoryServer(); const name = await mongod.getDbName(); console.log(name); await mongod.stop(); done(); }); });
import MongodbMemoryServer from "mongodb-memory-server"; describe("User Accounts", () => { let mongod: MongodbMemoryServer; beforeAll(async () => { mongod = new MongodbMemoryServer(); const uri = await mongod.getUri(); }); afterAll(async () => { await mongod.stop(); }); test("", async () => { const name = await mongod.getDbName(); console.log(name); }); });
Move db setup to beforeAll and afterAll
Move db setup to beforeAll and afterAll
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -1,11 +1,19 @@ import MongodbMemoryServer from "mongodb-memory-server"; -describe("", () => { - test("", async (done) => { - const mongod = new MongodbMemoryServer(); +describe("User Accounts", () => { + let mongod: MongodbMemoryServer; + + beforeAll(async () => { + mongod = new MongodbMemoryServer(); + const uri = await mongod.getUri(); + }); + + afterAll(async () => { + await mongod.stop(); + }); + + test("", async () => { const name = await mongod.getDbName(); console.log(name); - await mongod.stop(); - done(); }); });
a7915ba895f0fc5bb13d4fb14b55066fa60f775c
src/app/config.ts
src/app/config.ts
import isElectron from './utils/is_electron'; export default { ga: 'UA-41432833-6', add_query_depth_limit: 3, max_windows: 10, default_language: 'en', languages: { en: 'English', fr: 'French' }, query_history_depth: isElectron ? 25 : 7, themes: ['light', 'dark'] };
import isElectron from './utils/is_electron'; export default { ga: 'UA-41432833-6', add_query_depth_limit: 3, max_windows: 10, default_language: 'en', languages: { en: 'English', fr: 'French', es: 'Español' }, query_history_depth: isElectron ? 25 : 7, themes: ['light', 'dark'] };
Add spanish to languages object.
Add spanish to languages object.
TypeScript
mit
imolorhe/altair,imolorhe/altair,imolorhe/altair,imolorhe/altair
--- +++ @@ -5,7 +5,7 @@ add_query_depth_limit: 3, max_windows: 10, default_language: 'en', - languages: { en: 'English', fr: 'French' }, + languages: { en: 'English', fr: 'French', es: 'Español' }, query_history_depth: isElectron ? 25 : 7, themes: ['light', 'dark'] };
db50399b971843e4e22073d2f8c45fbbd3e782d7
packages/nextjs/src/utils/handlers.ts
packages/nextjs/src/utils/handlers.ts
import { captureException, flush, Handlers, withScope } from '@sentry/node'; import { NextApiRequest, NextApiResponse } from 'next'; const { parseRequest } = Handlers; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const withSentry = (handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>) => { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types return async (req: NextApiRequest, res: NextApiResponse) => { try { // TODO: Start Transaction return await handler(req, res); // Call Handler // TODO: Finish Transaction } catch (e) { withScope(scope => { scope.addEventProcessor(event => parseRequest(event, req)); captureException(e); }); await flush(2000); throw e; } }; };
import { captureException, flush, Handlers, withScope } from '@sentry/node'; import { addExceptionMechanism } from '@sentry/utils'; import { NextApiRequest, NextApiResponse } from 'next'; const { parseRequest } = Handlers; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const withSentry = (handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>) => { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types return async (req: NextApiRequest, res: NextApiResponse) => { try { // TODO: Start Transaction return await handler(req, res); // Call Handler // TODO: Finish Transaction } catch (e) { withScope(scope => { scope.addEventProcessor(event => { addExceptionMechanism(event, { handled: false, }); return parseRequest(event, req); }); captureException(e); }); throw e; } finally { await flush(2000); } }; };
Set handled:false for next.js serverless
fix: Set handled:false for next.js serverless
TypeScript
bsd-3-clause
getsentry/raven-js,getsentry/raven-js,getsentry/raven-js,getsentry/raven-js
--- +++ @@ -1,4 +1,5 @@ import { captureException, flush, Handlers, withScope } from '@sentry/node'; +import { addExceptionMechanism } from '@sentry/utils'; import { NextApiRequest, NextApiResponse } from 'next'; const { parseRequest } = Handlers; @@ -13,11 +14,17 @@ // TODO: Finish Transaction } catch (e) { withScope(scope => { - scope.addEventProcessor(event => parseRequest(event, req)); + scope.addEventProcessor(event => { + addExceptionMechanism(event, { + handled: false, + }); + return parseRequest(event, req); + }); captureException(e); }); + throw e; + } finally { await flush(2000); - throw e; } }; };
a1f6150143b32762c7e823c30e6dea1622ab3289
index.d.ts
index.d.ts
import { ChildProcess } from 'child_process'; type argValues = '-cors' | '-dbPath' | '-delayTransientStatuses' | '-help' | '-inMemory' | '-optimizeDbBeforeStartup' | '-port' | '-sharedDb'; export interface InstallerConfig { installPath: string; downloadUrl: string; } export function configureInstaller(config: InstallerConfig): void; export function launch(portNumber: number, dbPath?: string | null, args?: argValues[], verbose?: boolean, detached?: any, javaOpts?: string): Promise<ChildProcess>; export function stop(portNumber: number): void; export function stopChild(child: ChildProcess): void; export function relaunch(portNumber: number, dbPath?:string): void;
import { ChildProcess } from 'child_process'; type argValues = '-cors' | '-dbPath' | '-delayTransientStatuses' | '-help' | '-inMemory' | '-optimizeDbBeforeStartup' | '-port' | '-sharedDb'; export interface InstallerConfig { installPath?: string; downloadUrl?: string; } export function configureInstaller(config: InstallerConfig): void; export function launch(portNumber: number, dbPath?: string | null, args?: argValues[], verbose?: boolean, detached?: any, javaOpts?: string): Promise<ChildProcess>; export function stop(portNumber: number): void; export function stopChild(child: ChildProcess): void; export function relaunch(portNumber: number, dbPath?:string): void;
Mark Config options as optional in TypeScript typings
Mark Config options as optional in TypeScript typings
TypeScript
mit
doapp-ryanp/dynamodb-local
--- +++ @@ -3,8 +3,8 @@ type argValues = '-cors' | '-dbPath' | '-delayTransientStatuses' | '-help' | '-inMemory' | '-optimizeDbBeforeStartup' | '-port' | '-sharedDb'; export interface InstallerConfig { - installPath: string; - downloadUrl: string; + installPath?: string; + downloadUrl?: string; } export function configureInstaller(config: InstallerConfig): void;
1caad3d14b1c5a7e55f46bf445bb1d2f398ba6ae
src/core/feature-flags.ts
src/core/feature-flags.ts
/* Copyright 2019 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import queryString from 'query-string'; export class FeatureFlags { readonly baseline: boolean = false; constructor() { const parsed = queryString.parse(window.location.search); const { baseline } = parsed; if (baseline === 'true') { this.baseline = true; } } } export default new FeatureFlags();
/* Copyright 2019 Google LLC. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import queryString from 'query-string'; import { observable, computed } from 'mobx'; export type Variant = 'a' | 'b'; export class FeatureFlags { @observable readonly variant: Variant = 'a'; @computed get baseline() { return this.variant === 'b'; } constructor() { const parsed = queryString.parse(window.location.search); const { variant } = parsed; if (variant === 'b') { this.variant = variant; } } } export default new FeatureFlags();
Rename baseline query param to variant=b
Rename baseline query param to variant=b
TypeScript
apache-2.0
PAIR-code/cococo,PAIR-code/cococo,PAIR-code/cococo
--- +++ @@ -14,15 +14,22 @@ ==============================================================================*/ import queryString from 'query-string'; +import { observable, computed } from 'mobx'; + +export type Variant = 'a' | 'b'; export class FeatureFlags { - readonly baseline: boolean = false; + @observable readonly variant: Variant = 'a'; + + @computed get baseline() { + return this.variant === 'b'; + } constructor() { const parsed = queryString.parse(window.location.search); - const { baseline } = parsed; - if (baseline === 'true') { - this.baseline = true; + const { variant } = parsed; + if (variant === 'b') { + this.variant = variant; } } }
57ea93dce4b45e2be02ca50f69aa056a6f66c4f0
src/emitter/statements.ts
src/emitter/statements.ts
import { ReturnStatement } from 'typescript'; import { Context } from '../contexts'; import { EmitResult, emit } from './'; export const emitReturnStatement = ({ expression }: ReturnStatement, context: Context): EmitResult => { const emit_result = emit(expression, context); return { ...emit_result, emitted_string: `return ${emit_result.emitted_string};` }; };
import { ReturnStatement, VariableStatement } from 'typescript'; import { Context } from '../contexts'; import { EmitResult, emit } from './'; export const emitReturnStatement = ({ expression }: ReturnStatement, context: Context): EmitResult => { const emit_result = emit(expression, context); return { ...emit_result, emitted_string: `return ${emit_result.emitted_string};` }; }; export const emitVariableStatement = ({ declarationList: { declarations } }: VariableStatement, context: Context): EmitResult => { const emit_result = declarations .reduce<EmitResult>(({ context, emitted_string }, node) => { const result = emit(node, context); result.emitted_string = emitted_string + ';\n ' + result.emitted_string; return result; }, { context, emitted_string: '' }); return { ...emit_result, emitted_string: `${emit_result.emitted_string};` }; };
Add emit for variable statement
Add emit for variable statement
TypeScript
mit
AmnisIO/typewriter,AmnisIO/typewriter,AmnisIO/typewriter
--- +++ @@ -1,4 +1,4 @@ -import { ReturnStatement } from 'typescript'; +import { ReturnStatement, VariableStatement } from 'typescript'; import { Context } from '../contexts'; import { EmitResult, emit } from './'; @@ -9,3 +9,17 @@ emitted_string: `return ${emit_result.emitted_string};` }; }; + +export const emitVariableStatement = ({ declarationList: { declarations } }: VariableStatement, context: Context): EmitResult => { + const emit_result = + declarations + .reduce<EmitResult>(({ context, emitted_string }, node) => { + const result = emit(node, context); + result.emitted_string = emitted_string + ';\n ' + result.emitted_string; + return result; + }, { context, emitted_string: '' }); + return { + ...emit_result, + emitted_string: `${emit_result.emitted_string};` + }; +};
da14b6ac5637e8cfc74fd827df16cf1df79430c4
src/ui/components/AlternatingRows.tsx
src/ui/components/AlternatingRows.tsx
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import Bordered from './Bordered'; import {colors} from './colors'; /** * Displays all children in a bordered, zebra styled vertical layout */ const AlternatingRows: React.FC<{children: React.ReactNode[]}> = ({ children, }) => ( <Bordered style={{flexDirection: 'column'}}> {children.map((child, idx) => ( <div key={idx} style={{ padding: 8, background: idx % 2 === 0 ? colors.light02 : colors.white, }}> {child} </div> ))} </Bordered> ); export default AlternatingRows;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import Bordered from './Bordered'; import {colors} from './colors'; /** * Displays all children in a bordered, zebra styled vertical layout */ const AlternatingRows: React.FC<{ children: React.ReactNode[] | React.ReactNode; }> = ({children}) => ( <Bordered style={{flexDirection: 'column'}}> {(Array.isArray(children) ? children : [children]).map((child, idx) => ( <div key={idx} style={{ padding: 8, background: idx % 2 === 0 ? colors.light02 : colors.white, }}> {child} </div> ))} </Bordered> ); export default AlternatingRows;
Fix App name prefilling, improve markdown layout
Fix App name prefilling, improve markdown layout Summary: Make sure appname is prefilled Slightly improved layout of markdown Reviewed By: jknoxville Differential Revision: D18761477 fbshipit-source-id: 00184a0a4c6d1b5a779c3d3168f587e75e363433
TypeScript
mit
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
--- +++ @@ -15,11 +15,11 @@ /** * Displays all children in a bordered, zebra styled vertical layout */ -const AlternatingRows: React.FC<{children: React.ReactNode[]}> = ({ - children, -}) => ( +const AlternatingRows: React.FC<{ + children: React.ReactNode[] | React.ReactNode; +}> = ({children}) => ( <Bordered style={{flexDirection: 'column'}}> - {children.map((child, idx) => ( + {(Array.isArray(children) ? children : [children]).map((child, idx) => ( <div key={idx} style={{
01f262a375ea89ed14f00c38339bc2b824e81318
problems/additional-pylons/solution.ts
problems/additional-pylons/solution.ts
import {ISolution} from '../solution.interface'; export class Solution implements ISolution<string, string> { units = { "Probe": 1, "Zealot": 2, "Sentry": 2, "Stalker": 2, "HighTemplar": 2, "DarkTemplar": 2, "Immortal": 4, "Colossus": 6, "Archon": 4, "Observer": 1, "WarpPrism": 2, "Phoenix": 2, "MothershipCore": 2, "VoidRay": 4, "Oracle": 3, "Tempest": 4, "Carrier": 6, "Mothership": 8 }; solve(input: string): string { let supply = parseInt(input.split(' ')[0]) * 8; let units = input.split(' ').slice(1); for (let u of units) { supply -= this.units[u]; } return units.join(' '); } }
import {ISolution} from '../solution.interface'; export class Solution implements ISolution<string, string> { units = { "Probe": 1, "Zealot": 2, "Sentry": 2, "Stalker": 2, "HighTemplar": 2, "DarkTemplar": 2, "Immortal": 4, "Colossus": 6, "Archon": 4, "Observer": 1, "WarpPrism": 2, "Phoenix": 2, "MothershipCore": 2, "VoidRay": 4, "Oracle": 3, "Tempest": 4, "Carrier": 6, "Mothership": 8 }; solve(input: string): string { let supply = parseInt(input.split(' ')[0]) * 8; let units = input.split(' ').slice(1); for (let u of units) { supply -= this.units[u]; } if (supply >= 0) { return "true"; } return units.join(' '); } }
Return true if we can make all the units
Return true if we can make all the units
TypeScript
unlicense
Jameskmonger/challenges
--- +++ @@ -30,6 +30,10 @@ supply -= this.units[u]; } + if (supply >= 0) { + return "true"; + } + return units.join(' '); } }
9b7989b0ab6824860327058786b5c32d2c458ab9
types/random-seed/random-seed-tests.ts
types/random-seed/random-seed-tests.ts
import { RandomSeed, create } from "random-seed"; // these generators produce different numbers const rand1: RandomSeed = create(); // method 1 // these generators will produce // the same sequence of numbers const seed = 'My Secret String Value'; const rand2 = create(seed); // API rand1(50); rand1.addEntropy(); rand1.random(); rand1.range(100); rand1.intBetween(0, 10); rand1.floatBetween(0, 1); rand1.seed("new seed");
import { RandomSeed, create } from "random-seed"; // these generators produce different numbers const rand1: RandomSeed = create(); // method 1 // these generators will produce // the same sequence of numbers const seed = 'My Secret String Value'; const rand2 = create(seed); // API rand1(50); rand1.addEntropy(); rand1.random(); rand1.range(100); rand1.intBetween(0, 10); rand1.floatBetween(0, 1); rand1.seed("new seed"); rand2(50); rand2.addEntropy(); rand2.random(); rand2.range(100); rand2.intBetween(0, 10); rand2.floatBetween(0, 1); rand2.seed("new seed");
Add tests for random-seed seeded generator
Add tests for random-seed seeded generator
TypeScript
mit
georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,chrootsu/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,arusakov/DefinitelyTyped,alexdresko/DefinitelyTyped,dsebastien/DefinitelyTyped,arusakov/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,benliddicott/DefinitelyTyped,mcliment/DefinitelyTyped,alexdresko/DefinitelyTyped,rolandzwaga/DefinitelyTyped,georgemarshall/DefinitelyTyped,zuzusik/DefinitelyTyped
--- +++ @@ -16,3 +16,11 @@ rand1.intBetween(0, 10); rand1.floatBetween(0, 1); rand1.seed("new seed"); + +rand2(50); +rand2.addEntropy(); +rand2.random(); +rand2.range(100); +rand2.intBetween(0, 10); +rand2.floatBetween(0, 1); +rand2.seed("new seed");
b1ed6cd8dabb4a8b77f1aa539eab6149e7ec7d83
lib/ui/src/components/sidebar/Heading.tsx
lib/ui/src/components/sidebar/Heading.tsx
import React, { FunctionComponent, ComponentProps } from 'react'; import { styled } from '@storybook/theming'; import { Brand } from './Brand'; import { SidebarMenu, MenuList } from './Menu'; export interface HeadingProps { menuHighlighted?: boolean; menu: MenuList; } const BrandArea = styled.div(({ theme }) => ({ fontSize: theme.typography.size.s2, fontWeight: theme.typography.weight.bold, color: theme.color.defaultText, marginRight: 40, display: 'flex', width: '100%', alignItems: 'center', minHeight: 22, '& > *': { maxWidth: '100%', height: 'auto', width: 'auto', display: 'block', }, })); const HeadingWrapper = styled.div({ display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative', }); export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({ menuHighlighted = false, menu, ...props }) => { return ( <HeadingWrapper {...props}> <BrandArea> <Brand /> </BrandArea> <SidebarMenu menu={menu} isHighlighted={menuHighlighted} /> </HeadingWrapper> ); };
import React, { FunctionComponent, ComponentProps } from 'react'; import { styled } from '@storybook/theming'; import { Brand } from './Brand'; import { SidebarMenu, MenuList } from './Menu'; export interface HeadingProps { menuHighlighted?: boolean; menu: MenuList; } const BrandArea = styled.div(({ theme }) => ({ fontSize: theme.typography.size.s2, fontWeight: theme.typography.weight.bold, color: theme.color.defaultText, marginRight: 40, display: 'flex', width: '100%', alignItems: 'center', minHeight: 22, '& > *': { maxWidth: '100%', height: 'auto', display: 'block', flex: '1 1 auto', }, })); const HeadingWrapper = styled.div({ display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative', }); export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({ menuHighlighted = false, menu, ...props }) => { return ( <HeadingWrapper {...props}> <BrandArea> <Brand /> </BrandArea> <SidebarMenu menu={menu} isHighlighted={menuHighlighted} /> </HeadingWrapper> ); };
Fix display of sidebar logo
UI: Fix display of sidebar logo
TypeScript
mit
storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook
--- +++ @@ -22,8 +22,8 @@ '& > *': { maxWidth: '100%', height: 'auto', - width: 'auto', display: 'block', + flex: '1 1 auto', }, }));
fb001f4c7e908618e5b2fbc3779ca0f668677f77
src/console/components/FindPrompt.tsx
src/console/components/FindPrompt.tsx
import React from "react"; import Input from "./console/Input"; import styled from "styled-components"; import useAutoResize from "../hooks/useAutoResize"; import { useExecFind, useHide } from "../app/hooks"; const ConsoleWrapper = styled.div` border-top: 1px solid gray; `; const FindPrompt: React.FC = () => { const [inputValue, setInputValue] = React.useState(""); const hide = useHide(); const execFind = useExecFind(); const onBlur = () => { hide(); }; useAutoResize(); const doEnter = (e: React.KeyboardEvent<HTMLInputElement>) => { e.stopPropagation(); e.preventDefault(); const value = (e.target as HTMLInputElement).value; execFind(value === "" ? undefined : value); }; const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { switch (e.key) { case "Escape": hide(); break; case "Enter": doEnter(e); break; } }; const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { setInputValue(e.target.value); }; return ( <ConsoleWrapper> <Input prompt={"/"} onBlur={onBlur} onKeyDown={onKeyDown} onChange={onChange} value={inputValue} /> </ConsoleWrapper> ); }; export default FindPrompt;
import React from "react"; import Input from "./console/Input"; import styled from "styled-components"; import useAutoResize from "../hooks/useAutoResize"; import { useExecFind, useHide } from "../app/hooks"; const ConsoleWrapper = styled.div` border-top: 1px solid gray; `; const FindPrompt: React.FC = () => { const [inputValue, setInputValue] = React.useState(""); const hide = useHide(); const execFind = useExecFind(); const onBlur = () => { hide(); }; useAutoResize(); const doEnter = (e: React.KeyboardEvent<HTMLInputElement>) => { e.stopPropagation(); e.preventDefault(); const value = (e.target as HTMLInputElement).value; execFind(value === "" ? undefined : value); hide(); }; const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { switch (e.key) { case "Escape": hide(); break; case "Enter": doEnter(e); break; } }; const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { setInputValue(e.target.value); }; return ( <ConsoleWrapper> <Input prompt={"/"} onBlur={onBlur} onKeyDown={onKeyDown} onChange={onChange} value={inputValue} /> </ConsoleWrapper> ); }; export default FindPrompt;
Hide console to focus main window after find executed
Hide console to focus main window after find executed
TypeScript
mit
ueokande/vim-vixen,ueokande/vim-vixen,ueokande/vim-vixen
--- +++ @@ -25,6 +25,7 @@ const value = (e.target as HTMLInputElement).value; execFind(value === "" ? undefined : value); + hide(); }; const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
772359e0a54377592c8f4e4159cbc39a56978443
packages/stryker-webpack/src/index.ts
packages/stryker-webpack/src/index.ts
import { TranspilerFactory } from 'stryker-api/transpile'; // import { ConfigEditorFactory } from 'stryker-api/config'; import WebpackTranspiler from "./WebpackTranspiler"; // import WebpackConfigEditor from "./WebpackConfigEditor"; TranspilerFactory.instance().register('webpack', WebpackTranspiler); // ConfigEditorFactory.instance().register('webpack', WebpackConfigEditor);
import { TranspilerFactory } from 'stryker-api/transpile'; import WebpackTranspiler from "./WebpackTranspiler"; TranspilerFactory.instance().register('webpack', WebpackTranspiler);
Remove configEditor from the implementation
Refactor(ConfigEditor): Remove configEditor from the implementation
TypeScript
apache-2.0
stryker-mutator/stryker,stryker-mutator/stryker,stryker-mutator/stryker
--- +++ @@ -1,7 +1,4 @@ import { TranspilerFactory } from 'stryker-api/transpile'; -// import { ConfigEditorFactory } from 'stryker-api/config'; import WebpackTranspiler from "./WebpackTranspiler"; -// import WebpackConfigEditor from "./WebpackConfigEditor"; TranspilerFactory.instance().register('webpack', WebpackTranspiler); -// ConfigEditorFactory.instance().register('webpack', WebpackConfigEditor);
4bcb43375571765f93c108752f5ac626a18e6750
packages/components/containers/login/AbuseModal.tsx
packages/components/containers/login/AbuseModal.tsx
import { c } from 'ttag'; import { AlertModal, Button, Href } from '../../components'; interface Props { message?: string; open: boolean; onClose: () => void; } const AbuseModal = ({ message, open, onClose }: Props) => { const contactLink = ( <Href url="https://protonmail.com/abuse" key={1}> {c('Info').t`here`} </Href> ); return ( <AlertModal open={open} title={c('Title').t`Account suspended`} onClose={onClose} buttons={<Button onClick={onClose}>I understand</Button>} > {message || ( <> <div className="mb1">{c('Info') .t`This account has been suspended due to a potential policy violation.`}</div> <div>{c('Info').jt`If you believe this is in error, please contact us ${contactLink}.`}</div> </> )} </AlertModal> ); }; export default AbuseModal;
import { c } from 'ttag'; import { AlertModal, Button, Href } from '../../components'; interface Props { message?: string; open: boolean; onClose: () => void; } const AbuseModal = ({ message, open, onClose }: Props) => { const contactLink = ( <Href url="https://protonmail.com/abuse" key={1}> {c('Info').t`here`} </Href> ); return ( <AlertModal open={open} title={c('Title').t`Account suspended`} onClose={onClose} buttons={<Button onClick={onClose}>{c('Action').t`I understand`}</Button>} > {message || ( <> <div className="mb1">{c('Info') .t`This account has been suspended due to a potential policy violation.`}</div> <div>{c('Info').jt`If you believe this is in error, please contact us ${contactLink}.`}</div> </> )} </AlertModal> ); }; export default AbuseModal;
Fix translation in abuse modal
Fix translation in abuse modal
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -19,7 +19,7 @@ open={open} title={c('Title').t`Account suspended`} onClose={onClose} - buttons={<Button onClick={onClose}>I understand</Button>} + buttons={<Button onClick={onClose}>{c('Action').t`I understand`}</Button>} > {message || ( <>
775778b0036c141a07ccc8794d319b844dc3b182
packages/linter/src/rules/FastGoogleFontsDisplay.ts
packages/linter/src/rules/FastGoogleFontsDisplay.ts
import { Context } from "../index"; import { Rule } from "../rule"; const GOOGLE_FONT_URL_PATTERN = /https?:\/\/fonts.googleapis.com\/css\?(?!(?:[\s\S]+&)?display=(?:swap|fallback|optional)(?:&|$))/i; /** * This test will return an info when font-face definitions with a url * but no fonts are preloaded. * Font definitions with url but an additional font-display setting are ignored. */ export class FastGoogleFontsDisplay extends Rule { run({ $ }: Context) { const fonts = $( "link[rel='stylesheet'][href^='https://fonts.googleapis.com/css']" ); if (!fonts.length) { return this.pass(); } const results = []; fonts.each((i, linkNode) => { const href = $(linkNode).attr("href"); const match = GOOGLE_FONT_URL_PATTERN.exec(href); if (match) { results.push( this.warn( `Use &display=swap|fallback|optional in font stylesheet url: ${href}` ) ); } }); return Promise.all(results); } meta() { return { url: "https://web.dev/font-display/", title: "Use fast font display for Google Fonts", info: "", }; } }
import { Context } from "../index"; import { Rule } from "../rule"; const GOOGLE_FONT_URL_PATTERN = /https?:\/\/fonts.googleapis.com\/css\?(?!(?:[\s\S]+&)?display=(?:swap|fallback|optional)(?:&|$))/i; /** * This test will return an info when font-face definitions with a url * but no fonts are preloaded. * Font definitions with url but an additional font-display setting are ignored. */ export class FastGoogleFontsDisplay extends Rule { run({ $ }: Context) { const fonts = $( "link[rel='stylesheet'][href^='https://fonts.googleapis.com/css']" ); if (!fonts.length) { return this.pass(); } const results = []; fonts.each((i, linkNode) => { const href = $(linkNode).attr("href"); const match = GOOGLE_FONT_URL_PATTERN.exec(href); if (match) { results.push( this.warn( `Use &display=swap|fallback|optional in Google Font stylesheet URL: ${href}` ) ); } }); return Promise.all(results); } meta() { return { url: "https://web.dev/font-display/", title: "Use fast font-display for Google Fonts", info: "", }; } }
Change rule tile and warning text
Change rule tile and warning text
TypeScript
apache-2.0
ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox
--- +++ @@ -23,7 +23,7 @@ if (match) { results.push( this.warn( - `Use &display=swap|fallback|optional in font stylesheet url: ${href}` + `Use &display=swap|fallback|optional in Google Font stylesheet URL: ${href}` ) ); } @@ -33,7 +33,7 @@ meta() { return { url: "https://web.dev/font-display/", - title: "Use fast font display for Google Fonts", + title: "Use fast font-display for Google Fonts", info: "", }; }
7d574f43950d9157152e9ad2f7b127582935c95c
src/pages/story-list.ts
src/pages/story-list.ts
import { RoutableComponentActivate, RoutableComponentDetermineActivationStrategy, Router } from 'aurelia-router'; import { Item } from '../models/item'; import { HackerNewsApi, STORIES_PER_PAGE } from '../services/api'; export abstract class StoryList implements RoutableComponentActivate, RoutableComponentDetermineActivationStrategy { stories: Item[]; currentPage: number; totalPages: number; readonly route: string; protected readonly api: HackerNewsApi; protected readonly router: Router; private allStories: number[] = []; constructor(api: HackerNewsApi, router: Router, route: string) { this.api = api; this.router = router; this.route = route; } determineActivationStrategy(): 'no-change' | 'invoke-lifecycle' | 'replace' { return 'invoke-lifecycle'; } async activate(params: any): Promise<void> { this.allStories = await this.api.fetch(this.route); this.currentPage = params.page ? Number(params.page) : 1; this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE); if (this.currentPage > this.totalPages) { this.router.navigateToRoute(this.route, { page: this.totalPages }); } else { this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage); } } }
import { RoutableComponentActivate, RoutableComponentDetermineActivationStrategy, Router } from 'aurelia-router'; import { Item } from '../models/item'; import { HackerNewsApi, STORIES_PER_PAGE } from '../services/api'; export abstract class StoryList implements RoutableComponentActivate, RoutableComponentDetermineActivationStrategy { stories: Item[]; offset: number; currentPage: number; totalPages: number; readonly route: string; protected readonly api: HackerNewsApi; protected readonly router: Router; private allStories: number[] = []; constructor(api: HackerNewsApi, router: Router, route: string) { this.api = api; this.router = router; this.route = route; } determineActivationStrategy(): 'no-change' | 'invoke-lifecycle' | 'replace' { return 'invoke-lifecycle'; } async activate(params: any): Promise<void> { this.allStories = await this.api.fetch(this.route); this.currentPage = params.page ? Number(params.page) : 1; this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE); if (this.currentPage > this.totalPages) { this.router.navigateToRoute(this.route, { page: this.totalPages }); } else { this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage); } this.offset = STORIES_PER_PAGE * (this.currentPage - 1); } }
Fix item numbers on pages >1
Fix item numbers on pages >1
TypeScript
isc
MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news
--- +++ @@ -11,6 +11,7 @@ export abstract class StoryList implements RoutableComponentActivate, RoutableComponentDetermineActivationStrategy { stories: Item[]; + offset: number; currentPage: number; totalPages: number; readonly route: string; @@ -39,5 +40,7 @@ } else { this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage); } + + this.offset = STORIES_PER_PAGE * (this.currentPage - 1); } }
cdd33efcb197d14ac801236ca95642b7019580ee
test/server/codingChallengeFixesSpec.ts
test/server/codingChallengeFixesSpec.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich & the OWASP Juice Shop contributors. * SPDX-License-Identifier: MIT */ import { retrieveChallengesWithCodeSnippet } from '../../routes/vulnCodeSnippet' import { readFixes } from '../../routes/vulnCodeFixes' import chai = require('chai') const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) describe('codingChallengeFixes', () => { let codingChallenges: string[] before(async () => { codingChallenges = await retrieveChallengesWithCodeSnippet() }) it('should have a correct fix for each coding challenge', async () => { for (const challenge of codingChallenges) { const fixes = readFixes(challenge) expect(fixes.correct, `Coding challenge ${challenge} does not have a correct fix file`).to.be.greaterThan(-1) } }) it('should have a total of three or more fix options for each coding challenge', async () => { for (const challenge of codingChallenges) { const fixes = readFixes(challenge) expect(fixes.fixes.length, `Coding challenge ${challenge} does not have enough fix option files`).to.be.greaterThanOrEqual(3) } }) })
/* * Copyright (c) 2014-2021 Bjoern Kimminich & the OWASP Juice Shop contributors. * SPDX-License-Identifier: MIT */ import { retrieveChallengesWithCodeSnippet } from '../../routes/vulnCodeSnippet' import { readFixes } from '../../routes/vulnCodeFixes' import chai = require('chai') import fs from 'graceful-fs' const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) describe('codingChallengeFixes', () => { let codingChallenges: string[] before(async () => { codingChallenges = await retrieveChallengesWithCodeSnippet() }) it('should have a correct fix for each coding challenge', async () => { for (const challenge of codingChallenges) { const fixes = readFixes(challenge) expect(fixes.correct, `Coding challenge ${challenge} does not have a correct fix file`).to.be.greaterThan(-1) } }) it('should have a total of three or more fix options for each coding challenge', async () => { for (const challenge of codingChallenges) { const fixes = readFixes(challenge) expect(fixes.fixes.length, `Coding challenge ${challenge} does not have enough fix option files`).to.be.greaterThanOrEqual(3) } }) xit('should have an info YAML file for each coding challenge', async () => { // TODO Enable test once all coding challenges have an info file. Then also state it as a mandatory pieced in companion guide. for (const challenge of codingChallenges) { expect(fs.existsSync('./data/static/codefixes/' + challenge + '.info.yml'), `Coding challenge ${challenge} does not have an info YAML file`).to.equal(true) } }) })
Prepare test case to check presence of info YAML files
Prepare test case to check presence of info YAML files
TypeScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -6,6 +6,7 @@ import { retrieveChallengesWithCodeSnippet } from '../../routes/vulnCodeSnippet' import { readFixes } from '../../routes/vulnCodeFixes' import chai = require('chai') +import fs from 'graceful-fs' const sinonChai = require('sinon-chai') const expect = chai.expect chai.use(sinonChai) @@ -29,4 +30,10 @@ expect(fixes.fixes.length, `Coding challenge ${challenge} does not have enough fix option files`).to.be.greaterThanOrEqual(3) } }) + + xit('should have an info YAML file for each coding challenge', async () => { // TODO Enable test once all coding challenges have an info file. Then also state it as a mandatory pieced in companion guide. + for (const challenge of codingChallenges) { + expect(fs.existsSync('./data/static/codefixes/' + challenge + '.info.yml'), `Coding challenge ${challenge} does not have an info YAML file`).to.equal(true) + } + }) })
158749dc07d677e17ea25f17c6cac1218f567508
Mechanism/Structures/Vector2Mutator.ts
Mechanism/Structures/Vector2Mutator.ts
class Vector2Mutator { constructor(private readonly origin: Vector2) { } add(value: Vector2| number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs + rhs); return this; } subtract(value: Vector2): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs - rhs); return this; } multiply(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs * rhs); return this; } divide(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs / rhs); return this; } private apply(value: Vector2 | number, fn: (lhs: number, rhs: number) => number): void { if (value instanceof Vector2) { this.origin.x = fn(this.origin.x, value.x); this.origin.y = fn(this.origin.y, value.y); } else { this.origin.x = fn(this.origin.x, value); this.origin.y = fn(this.origin.y, value); } } }
class Vector2Mutator { constructor(private readonly origin: Vector2) { } add(value: Vector2| number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs + rhs); return this; } subtract(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs - rhs); return this; } multiply(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs * rhs); return this; } divide(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs / rhs); return this; } private apply(value: Vector2 | number, fn: (lhs: number, rhs: number) => number): void { if (value instanceof Vector2) { this.origin.x = fn(this.origin.x, value.x); this.origin.y = fn(this.origin.y, value.y); } else { this.origin.x = fn(this.origin.x, value); this.origin.y = fn(this.origin.y, value); } } }
Add vector2 x number subtraction.
Add vector2 x number subtraction.
TypeScript
apache-2.0
Dia6lo/Mechanism,Dia6lo/Mechanism,Dia6lo/Mechanism
--- +++ @@ -6,7 +6,7 @@ return this; } - subtract(value: Vector2): Vector2Mutator { + subtract(value: Vector2 | number): Vector2Mutator { this.apply(value, (lhs, rhs) => lhs - rhs); return this; }
32d7af21e685e3f86b02028a771e4ca15ee53333
lib/msal-node/src/cache/ITokenCache.ts
lib/msal-node/src/cache/ITokenCache.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AccountInfo } from "@azure/msal-common"; export interface ITokenCache { getAllAccounts(): Promise<AccountInfo[]>; getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>; getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>; removeAccount(account: AccountInfo): Promise<void>; } export const stubbedTokenCache: ITokenCache = { getAllAccounts: () => { return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); }, getAccountByHomeId: () => { return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); }, getAccountByLocalId: () => { return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); }, removeAccount: () => { return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); }, };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AccountInfo } from "@azure/msal-common"; export interface ITokenCache { getAllAccounts(): Promise<AccountInfo[]>; getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>; getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>; removeAccount(account: AccountInfo): Promise<void>; }
Remove node errors - no longer needed
Remove node errors - no longer needed
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -4,25 +4,9 @@ */ import { AccountInfo } from "@azure/msal-common"; - export interface ITokenCache { getAllAccounts(): Promise<AccountInfo[]>; getAccountByHomeId(homeAccountId: string): Promise<AccountInfo | null>; getAccountByLocalId(localAccountId: string): Promise<AccountInfo | null>; removeAccount(account: AccountInfo): Promise<void>; } - -export const stubbedTokenCache: ITokenCache = { - getAllAccounts: () => { - return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); - }, - getAccountByHomeId: () => { - return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); - }, - getAccountByLocalId: () => { - return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); - }, - removeAccount: () => { - return Promise.reject(NodeConfigurationAuthError.createStubTokenCacheCalledError()); - }, -};
7236a3b69951a5c4622c0f8ec071137008b628ce
packages/shared/lib/interfaces/utils.ts
packages/shared/lib/interfaces/utils.ts
export type SimpleMap<T> = { [key: string]: T | undefined };
export type SimpleMap<T> = { [key: string]: T | undefined }; export type LoadingMap = { [key: string]: boolean | undefined };
Move LoadingMap type to proton-shared
Move LoadingMap type to proton-shared
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1 +1,3 @@ export type SimpleMap<T> = { [key: string]: T | undefined }; + +export type LoadingMap = { [key: string]: boolean | undefined };
8cfbbf3dae280769d176f21e061784424a8bc008
applications/mail/src/app/components/sidebar/EmptyFolders.tsx
applications/mail/src/app/components/sidebar/EmptyFolders.tsx
import React from 'react'; import { c } from 'ttag'; import { SidebarListItem, SidebarListItemButton, SidebarListItemContentIcon, SidebarListItemContent, LabelModal, useModals, } from 'react-components'; import { randomIntFromInterval } from 'proton-shared/lib/helpers/function'; import { LABEL_COLORS, ROOT_FOLDER, LABEL_TYPE } from 'proton-shared/lib/constants'; import { Folder } from 'proton-shared/lib/interfaces/Folder'; interface Props { onFocus: () => void; } const EmptyFolders = ({ onFocus }: Props) => { const { createModal } = useModals(); const handleClick = () => { const newLabel: Pick<Folder, 'Name' | 'Color' | 'ParentID' | 'Type'> = { Name: '', Color: LABEL_COLORS[randomIntFromInterval(0, LABEL_COLORS.length - 1)], ParentID: ROOT_FOLDER, Type: LABEL_TYPE.MESSAGE_FOLDER, }; createModal(<LabelModal label={newLabel} />); }; return ( <SidebarListItem> <SidebarListItemButton onFocus={onFocus} data-shortcut-target="add-folder" onClick={handleClick}> <SidebarListItemContent right={<SidebarListItemContentIcon name="plus" color="white" />}> {c('Link').t`Add folder`} </SidebarListItemContent> </SidebarListItemButton> </SidebarListItem> ); }; export default EmptyFolders;
import React from 'react'; import { c } from 'ttag'; import { SidebarListItem, SidebarListItemButton, SidebarListItemContentIcon, SidebarListItemContent, LabelModal, useModals, } from 'react-components'; interface Props { onFocus: () => void; } const EmptyFolders = ({ onFocus }: Props) => { const { createModal } = useModals(); const handleClick = () => { createModal(<LabelModal type="folder" />); }; return ( <SidebarListItem> <SidebarListItemButton onFocus={onFocus} data-shortcut-target="add-folder" onClick={handleClick}> <SidebarListItemContent right={<SidebarListItemContentIcon name="plus" color="white" />}> {c('Link').t`Add folder`} </SidebarListItemContent> </SidebarListItemButton> </SidebarListItem> ); }; export default EmptyFolders;
Fix notification on folder creation
Fix notification on folder creation
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -9,9 +9,6 @@ LabelModal, useModals, } from 'react-components'; -import { randomIntFromInterval } from 'proton-shared/lib/helpers/function'; -import { LABEL_COLORS, ROOT_FOLDER, LABEL_TYPE } from 'proton-shared/lib/constants'; -import { Folder } from 'proton-shared/lib/interfaces/Folder'; interface Props { onFocus: () => void; @@ -21,13 +18,7 @@ const { createModal } = useModals(); const handleClick = () => { - const newLabel: Pick<Folder, 'Name' | 'Color' | 'ParentID' | 'Type'> = { - Name: '', - Color: LABEL_COLORS[randomIntFromInterval(0, LABEL_COLORS.length - 1)], - ParentID: ROOT_FOLDER, - Type: LABEL_TYPE.MESSAGE_FOLDER, - }; - createModal(<LabelModal label={newLabel} />); + createModal(<LabelModal type="folder" />); }; return (
14f9fc6e7fa71ef1554fa1899b19a02d8e033dba
ts/main.ts
ts/main.ts
import Events = require('./Bridge'); import Application = require('./Application'); var services: { events: Events.Bridge; } = { events: new Events.Bridge() }; //$.fn.hasAttr = function(name: string): boolean { // var attr = this.attr(name); // return attr !== undefined && attr !== false; // //return this.attr(name) !== undefined; //}; var app = new Application(); app.debug();
import Events = require('./Bridge'); import Application = require('./Application'); var animatumApp = new Application(); animatumApp.debug();
Refactor for naming conflict and removal of services global
Refactor for naming conflict and removal of services global
TypeScript
mit
chances/Animatum-Infinitas,chances/Animatum-Infinitas,chances/Animatum-Infinitas
--- +++ @@ -1,18 +1,6 @@ import Events = require('./Bridge'); import Application = require('./Application'); -var services: { - events: Events.Bridge; -} = { - events: new Events.Bridge() -}; +var animatumApp = new Application(); -//$.fn.hasAttr = function(name: string): boolean { -// var attr = this.attr(name); -// return attr !== undefined && attr !== false; -// //return this.attr(name) !== undefined; -//}; - -var app = new Application(); - -app.debug(); +animatumApp.debug();
1aa4827aec24736ce8567f68b9037a664c978ee3
src/atw.ts
src/atw.ts
let fs = require('fs'); let parser = require('./parser.js'); function parse(filename: string, f: (tree: SyntaxNode) => void) { fs.readFile(filename, function (err, data) { if (err) { console.log(err); process.exit(1); } let s = data.toString(); let tree; try { tree = parser.parse(s); } catch (e) { if (e instanceof parser.SyntaxError) { console.log('parse error at ' + filename + ':' + e.line + ',' + e.column + ': ' + e.message); process.exit(1); } else { throw e; } } f(tree); }); } function main() { let fn = process.argv[2]; if (!fn) { console.log("no input provided"); process.exit(1); } parse(fn, function (tree) { console.log(tree); console.log(interpret(tree)); }); } main();
/// <reference path="../typings/node/node.d.ts" /> /// <reference path="interp.ts" /> let fs = require('fs'); let parser = require('./parser.js'); function parse(filename: string, f: (tree: SyntaxNode) => void) { fs.readFile(filename, function (err, data) { if (err) { console.log(err); process.exit(1); } let s = data.toString(); let tree; try { tree = parser.parse(s); } catch (e) { if (e instanceof parser.SyntaxError) { console.log('parse error at ' + filename + ':' + e.line + ',' + e.column + ': ' + e.message); process.exit(1); } else { throw e; } } f(tree); }); } function main() { let fn = process.argv[2]; if (!fn) { console.log("no input provided"); process.exit(1); } parse(fn, function (tree) { console.log(tree); console.log(interpret(tree)); }); } main();
Make my editor happy again
Make my editor happy again Syntastic apparently doesn't support tsconfig.json out of the box.
TypeScript
mit
guoyiteng/braid,guoyiteng/braid,cucapra/braid,cucapra/braid,guoyiteng/braid,cucapra/braid,cucapra/braid,cucapra/braid,guoyiteng/braid,guoyiteng/braid,cucapra/braid,guoyiteng/braid
--- +++ @@ -1,3 +1,6 @@ +/// <reference path="../typings/node/node.d.ts" /> +/// <reference path="interp.ts" /> + let fs = require('fs'); let parser = require('./parser.js');
9ba452bc88fb2e12f9304532c943b3eb160381bb
src/app/interfaces/article.interface.ts
src/app/interfaces/article.interface.ts
export interface Article { id: number; date: string; alias: string; title: string; author: { name: string; info: string; }; intro: string; content: string; }
import { AuthorInfo } from "./author-info.interface"; export interface Article { id: number; date: string; alias: string; title: string; author: AuthorInfo; intro: string; content: string; }
Change property author as author info
Change property author as author info
TypeScript
mit
KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web
--- +++ @@ -1,12 +1,11 @@ +import { AuthorInfo } from "./author-info.interface"; + export interface Article { id: number; date: string; alias: string; title: string; - author: { - name: string; - info: string; - }; + author: AuthorInfo; intro: string; content: string; }
a2a195290fe60a0b2ad87e3dbebe033116e81d12
functions/src/search/index-contents.ts
functions/src/search/index-contents.ts
import * as algoliasearch from 'algoliasearch' import { Request, Response } from 'express' import { FirebaseApp } from '../firebase' import { AlgoliaConfig } from './config' import { indexEvents } from './index-events' import { indexSpeakers } from './index-speakers' import { replaceNonWordCharsWithUnderscores, ensureNotEmpty } from '../strings' export const indexContent = (firebaseApp: FirebaseApp, algoliaConfig: AlgoliaConfig) => (_: Request, response: Response) => { const algolia = algoliasearch( algoliaConfig.application_id, algoliaConfig.api_key ) ensureNotEmpty(algoliaConfig.index_prefix, 'algoliaConfig.index_prefix') const indexPrefix = replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix) Promise.all([ indexSpeakers(firebaseApp, algolia, indexPrefix), indexEvents(firebaseApp, algolia, indexPrefix) ]).then(() => { response.status(200).send('Yay!') }).catch(error => { console.error(error) response.status(500).send('Nay!') }) }
import * as algoliasearch from 'algoliasearch' import { Request, Response } from 'express' import { FirebaseApp } from '../firebase' import { AlgoliaConfig } from './config' import { indexEvents } from './index-events' import { indexSpeakers } from './index-speakers' import { replaceNonWordCharsWithUnderscores, ensureNotEmpty } from '../strings' export const indexContent = (firebaseApp: FirebaseApp, algoliaConfig: AlgoliaConfig) => (_: Request, response: Response) => { const algolia = algoliasearch( algoliaConfig.application_id, algoliaConfig.api_key ) ensureNotEmpty(algoliaConfig.index_prefix, 'algoliaConfig.index_prefix') const indexPrefix = `${replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix)}-` Promise.all([ indexSpeakers(firebaseApp, algolia, indexPrefix), indexEvents(firebaseApp, algolia, indexPrefix) ]).then(() => { response.status(200).send('Yay!') }).catch(error => { console.error(error) response.status(500).send('Nay!') }) }
Add a dash in the Algolia index names after prefix
Add a dash in the Algolia index names after prefix Makes it easier to visually parse
TypeScript
apache-2.0
squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase
--- +++ @@ -15,7 +15,7 @@ ) ensureNotEmpty(algoliaConfig.index_prefix, 'algoliaConfig.index_prefix') - const indexPrefix = replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix) + const indexPrefix = `${replaceNonWordCharsWithUnderscores(algoliaConfig.index_prefix)}-` Promise.all([ indexSpeakers(firebaseApp, algolia, indexPrefix), indexEvents(firebaseApp, algolia, indexPrefix)
36bce08da51e86dd8a6fb9860ae6c618121d40e3
inkweaver/app/login/login.component.ts
inkweaver/app/login/login.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { LoginService } from './login.service'; import { UserService } from '../user/user.service'; import { ApiService } from '../shared/api.service'; import { ParserService } from '../shared/parser.service'; @Component({ selector: 'login', templateUrl: './app/login/login.component.html' }) export class LoginComponent { private data: any; private login: any; constructor( private router: Router, private loginService: LoginService, private userService: UserService, private apiService: ApiService, private parserService: ParserService) { } ngOnInit() { this.data = this.apiService.data; this.data.menuItems = [ { label: 'About', routerLink: ['/about'] } ]; this.login = { username: '', password: '' }; } public signIn() { this.loginService.login(this.login.username, this.login.password) .subscribe(response => { let cookie: string = response.headers.get('Set-Cookie'); console.log(cookie); document.cookie = cookie; this.apiService.connect(); this.userService.getUserPreferences(); this.userService.getUserStories(); this.userService.getUserWikis(); this.router.navigate(['/user']); }); return false; } }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { LoginService } from './login.service'; import { UserService } from '../user/user.service'; import { ApiService } from '../shared/api.service'; import { ParserService } from '../shared/parser.service'; @Component({ selector: 'login', templateUrl: './app/login/login.component.html' }) export class LoginComponent { private data: any; private login: any; constructor( private router: Router, private loginService: LoginService, private userService: UserService, private apiService: ApiService, private parserService: ParserService) { } ngOnInit() { this.data = this.apiService.data; this.data.menuItems = [ { label: 'About', routerLink: ['/about'] } ]; this.login = { username: '', password: '' }; } public signIn() { this.loginService.login(this.login.username, this.login.password) .subscribe(response => { console.log(document.cookie); this.apiService.connect(); this.userService.getUserPreferences(); this.userService.getUserStories(); this.userService.getUserWikis(); this.router.navigate(['/user']); }); return false; } }
Document cookie hopefully not null
Document cookie hopefully not null
TypeScript
mpl-2.0
Plotypus/InkWeaver-Front,Plotypus/InkWeaver-Front,Plotypus/InkWeaver-Front,Plotypus/InkWeaver-Front
--- +++ @@ -36,9 +36,7 @@ public signIn() { this.loginService.login(this.login.username, this.login.password) .subscribe(response => { - let cookie: string = response.headers.get('Set-Cookie'); - console.log(cookie); - document.cookie = cookie; + console.log(document.cookie); this.apiService.connect(); this.userService.getUserPreferences();
23b320e09c23d3b993f743db9b2caa030b5f51ad
app/main.ts
app/main.ts
import { app, BrowserWindow } from 'electron'; import * as electronReload from 'electron-reload'; let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 400, height: 380, webPreferences: { webSecurity: false }, }); mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.on('closed', () => { mainWindow = null; }); } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (mainWindow === null) { createWindow(); } }); electronReload(__dirname, { electron: 'npm start', });
import { app, BrowserWindow } from 'electron'; import * as electronReload from 'electron-reload'; let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ fullscreen: true, webPreferences: { webSecurity: false }, }); mainWindow.loadURL(`file://${__dirname}/index.html`); mainWindow.on('closed', () => { mainWindow = null; }); } app.on('ready', createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (mainWindow === null) { createWindow(); } }); electronReload(__dirname, { electron: 'npm start', });
Change display size to full screen
Change display size to full screen
TypeScript
mit
tanishi/Slackker,tanishi/Slackker,tanishi/Slackker
--- +++ @@ -6,8 +6,7 @@ function createWindow() { mainWindow = new BrowserWindow({ - width: 400, - height: 380, + fullscreen: true, webPreferences: { webSecurity: false }, });
da8720100626585978370a62af5ee0cdca9b6b97
src/firefox/data/scripts/background.ts
src/firefox/data/scripts/background.ts
import user_interface = require('../../../generic_ui/scripts/ui'); import CoreConnector = require('../../../generic_ui/scripts/core_connector'); import FirefoxCoreConnector = require('./firefox_connector'); import FirefoxBrowserApi = require('./firefox_browser_api'); export var ui :user_interface.UserInterface; export var core :CoreConnector; export var browserConnector: FirefoxCoreConnector; function initUI() { browserConnector = new FirefoxCoreConnector(); core = new CoreConnector(browserConnector); var firefoxBrowserApi = new FirefoxBrowserApi(); return new user_interface.UserInterface(core, firefoxBrowserApi); } if (undefined === ui) { ui = initUI(); } ui.browser = 'firefox';
import user_interface = require('../../../generic_ui/scripts/ui'); import CoreConnector = require('../../../generic_ui/scripts/core_connector'); import FirefoxCoreConnector = require('./firefox_connector'); import FirefoxBrowserApi = require('./firefox_browser_api'); export var ui :user_interface.UserInterface; export var core :CoreConnector; export var browserConnector: FirefoxCoreConnector; export var model :user_interface.Model; function initUI() { browserConnector = new FirefoxCoreConnector(); core = new CoreConnector(browserConnector); var firefoxBrowserApi = new FirefoxBrowserApi(); return new user_interface.UserInterface(core, firefoxBrowserApi); } if (undefined === ui) { ui = initUI(); model = ui.model; } ui.browser = 'firefox';
Fix bug with not exporting model in Firefox
Fix bug with not exporting model in Firefox
TypeScript
apache-2.0
IveWong/uproxy,roceys/uproxy,roceys/uproxy,dhkong88/uproxy,itplanes/uproxy,jpevarnek/uproxy,qida/uproxy,jpevarnek/uproxy,MinFu/uproxy,chinarustin/uproxy,MinFu/uproxy,chinarustin/uproxy,jpevarnek/uproxy,chinarustin/uproxy,chinarustin/uproxy,qida/uproxy,itplanes/uproxy,MinFu/uproxy,uProxy/uproxy,uProxy/uproxy,qida/uproxy,chinarustin/uproxy,jpevarnek/uproxy,roceys/uproxy,roceys/uproxy,jpevarnek/uproxy,dhkong88/uproxy,itplanes/uproxy,dhkong88/uproxy,IveWong/uproxy,uProxy/uproxy,qida/uproxy,itplanes/uproxy,itplanes/uproxy,dhkong88/uproxy,uProxy/uproxy,roceys/uproxy,IveWong/uproxy,IveWong/uproxy,qida/uproxy,MinFu/uproxy,MinFu/uproxy,dhkong88/uproxy,uProxy/uproxy
--- +++ @@ -6,6 +6,7 @@ export var ui :user_interface.UserInterface; export var core :CoreConnector; export var browserConnector: FirefoxCoreConnector; +export var model :user_interface.Model; function initUI() { browserConnector = new FirefoxCoreConnector(); core = new CoreConnector(browserConnector); @@ -16,6 +17,7 @@ if (undefined === ui) { ui = initUI(); + model = ui.model; } ui.browser = 'firefox';
f67d34abf666f0359355a5521b93173362784856
ts/main.ts
ts/main.ts
/// <reference path="../typings/browser.d.ts" /> namespace AFCC { export function activate(selector: string) { $(selector).addClass("active"); } export function splashDanceParty() { activate(".dance-party-header"); } export function splashDancePartyBunnies() { activate("#splash .page-background"); } export function showDateLocationHeader() { activate(".date-location-header"); } export function init() { setTimeout(splashDanceParty, Conf.DancePartyHeaderStart); setTimeout(splashDancePartyBunnies, Conf.DancePartyHeaderBunnies); setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader) } } $(document).ready(function() { AFCC.init(); });
/// <reference path="../typings/browser.d.ts" /> namespace AFCC { export function activate(selector: string) { $(selector).addClass("active"); } export function splashDanceParty() { activate(".dance-party-header"); } export function splashDancePartyBunnies() { activate("#splash .page-background"); } export function showDateLocationHeader() { activate(".date-location-header"); } // Fix Google Map scroll issue var mapFixed = false; export function fixMap() { if (mapFixed) return; $('.map-container iframe').css("pointer-events", "none"); $('.map-container').unbind().click(function() { $(this).find('iframe').css("pointer-events", "auto"); mapFixed = false; }); } export function init() { // Splash setTimeout(splashDanceParty, Conf.DancePartyHeaderStart); setTimeout(splashDancePartyBunnies, Conf.DancePartyHeaderBunnies); setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader); // Map fixMap(); $(window).scroll(fixMap); } } $(document).ready(function() { AFCC.init(); });
Fix Google Maps scroll issue
Fix Google Maps scroll issue
TypeScript
mit
fongandrew/wedding,fongandrew/wedding
--- +++ @@ -17,10 +17,26 @@ activate(".date-location-header"); } + // Fix Google Map scroll issue + var mapFixed = false; + export function fixMap() { + if (mapFixed) return; + $('.map-container iframe').css("pointer-events", "none"); + $('.map-container').unbind().click(function() { + $(this).find('iframe').css("pointer-events", "auto"); + mapFixed = false; + }); + } + export function init() { + // Splash setTimeout(splashDanceParty, Conf.DancePartyHeaderStart); setTimeout(splashDancePartyBunnies, Conf.DancePartyHeaderBunnies); - setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader) + setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader); + + // Map + fixMap(); + $(window).scroll(fixMap); } }
448fa7f02f535d925c4b4943bf2ad4e25cdac0c1
src/index.ts
src/index.ts
import * as express from "express"; import * as path from "path"; const app = express(); app.get('/', (req: express.Request, res: express.Response) => { res.send('Hello Typescript!'); }); app.get('/:name', (req: express.Request, res: express.Response) => { let name: string = req.params.name; res.send('Hello ' + name + '!'); }); app.listen('8080'); console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.');
import * as express from "express"; import * as path from "path"; const app:express.Application = express(); app.get('/', (req: express.Request, res: express.Response) => { res.send('Hello Typescript!'); }); app.get('/:name', (req: express.Request, res: express.Response) => { let name: string = req.params.name; res.send('Hello ' + name + '!'); }); app.listen('8080'); console.log('\nApp is running. To view it, open a web browser to http://localhost:8080.\nTo be greeted by the app, visit http://localhost:8080/YourName.\n\nQuit app with ctrl+c.');
Add type declaration to app.
Add type declaration to app.
TypeScript
agpl-3.0
majtom2grndctrl/hello-typescript-express
--- +++ @@ -1,7 +1,7 @@ import * as express from "express"; import * as path from "path"; -const app = express(); +const app:express.Application = express(); app.get('/', (req: express.Request, res: express.Response) => { res.send('Hello Typescript!');
f7b25fc09f32c8585ca85fb7377b1addf8ebf69a
src/types.ts
src/types.ts
import { YveBot } from './core/bot'; export interface YveBotOptions { enableWaitForSleep?: boolean; rule?: Rule; } export interface Rule { name?: string; type?: string; output?: string; message?: string; delay?: number; sleep?: number; transform?: (value: string, rule: Rule, bot: YveBot) => Promise<any>; actions?: RuleAction[]; preActions?: RuleAction[]; replyMessage?: string; options?: RuleOption[]; validators?: RuleValidator[]; next?: RuleNext; exit?: boolean; } export interface RuleOption { label?: string; value?: string | number; next?: RuleNext; } export interface RuleAction { [name: string]: any; } export interface RuleValidator { [name: string]: any; } export type RuleNext = string; export type Answer = string | number; export interface ChatOptions { target?: string; name?: string; inputPlaceholder?: string; inputPlaceholderSingleChoice?: string; inputPlaceholderMutipleChoice?: string; doneMultipleChoiceLabel?: string; andSeparatorText?: string; submitLabel?: string; timestampable?: boolean; timestampFormatter?: (ts: number) => string; autoFocus?: boolean; yveBotOptions?: YveBotOptions; } export type ChatMessageSource = 'BOT' | 'USER';
import { YveBot } from './core/bot'; export interface YveBotOptions { enableWaitForSleep?: boolean; rule?: Rule; } export interface Rule { name?: string; type?: string; output?: string; message?: string; delay?: number; sleep?: number; actions?: RuleAction[]; preActions?: RuleAction[]; replyMessage?: string; options?: RuleOption[]; validators?: RuleValidator[]; next?: RuleNext; exit?: boolean; } export interface RuleOption { label?: string; value?: string | number; next?: RuleNext; } export interface RuleAction { [name: string]: any; } export interface RuleValidator { [name: string]: any; } export type RuleNext = string; export type Answer = string | number; export interface ChatOptions { target?: string; name?: string; inputPlaceholder?: string; inputPlaceholderSingleChoice?: string; inputPlaceholderMutipleChoice?: string; doneMultipleChoiceLabel?: string; andSeparatorText?: string; submitLabel?: string; timestampable?: boolean; timestampFormatter?: (ts: number) => string; autoFocus?: boolean; yveBotOptions?: YveBotOptions; } export type ChatMessageSource = 'BOT' | 'USER';
Remove unnecessary property transform in Rule
Remove unnecessary property transform in Rule
TypeScript
mit
andersonba/yve-bot,andersonba/yve-bot,andersonba/yve-bot
--- +++ @@ -12,7 +12,6 @@ message?: string; delay?: number; sleep?: number; - transform?: (value: string, rule: Rule, bot: YveBot) => Promise<any>; actions?: RuleAction[]; preActions?: RuleAction[]; replyMessage?: string;
b04a5580ce9379bed3bb09905541b0e66d2d1e2b
src/Cli.showhelp.spec.ts
src/Cli.showhelp.spec.ts
import test from 'ava' import { memoryAppender } from './test/setup' import { createNoCommandCli, createArgv } from './test/util' const cli = createNoCommandCli('showHelp') test.beforeEach(() => { memoryAppender.logs = [] }) test('when called with no parameter', t => { cli.run(createArgv()) }) test('when called with -h', t => { cli.run(createArgv('-h')) }) test('when called with --help', t => { cli.run(createArgv('--help')) }) test('when command not found', t => { cli.run(createArgv('some')) })
import test from 'ava' import { stub, SinonStub } from 'sinon' import { createNoCommandCli, createArgv } from './test/util' const cli = createNoCommandCli('showVersion') let showVersion: SinonStub test.beforeEach(() => { showVersion = stub(cli, 'showVersion') }) test.afterEach(() => { showVersion.restore() }) test('with -v', t => { cli.run(createArgv('-v')) t.true(showVersion.called) }) test('with --version', t => { cli.run(createArgv('--version')) t.true(showVersion.called) })
Change test code back to passing state.
Change test code back to passing state.
TypeScript
mit
unional/clibuilder,unional/clibuilder,unional/clibuilder
--- +++ @@ -1,21 +1,22 @@ import test from 'ava' +import { stub, SinonStub } from 'sinon' -import { memoryAppender } from './test/setup' import { createNoCommandCli, createArgv } from './test/util' -const cli = createNoCommandCli('showHelp') +const cli = createNoCommandCli('showVersion') +let showVersion: SinonStub test.beforeEach(() => { - memoryAppender.logs = [] + showVersion = stub(cli, 'showVersion') }) -test('when called with no parameter', t => { - cli.run(createArgv()) +test.afterEach(() => { + showVersion.restore() }) -test('when called with -h', t => { - cli.run(createArgv('-h')) +test('with -v', t => { + cli.run(createArgv('-v')) + t.true(showVersion.called) }) -test('when called with --help', t => { - cli.run(createArgv('--help')) + +test('with --version', t => { + cli.run(createArgv('--version')) + t.true(showVersion.called) }) -test('when command not found', t => { - cli.run(createArgv('some')) -})
e6fe485760a51cb0b43693f995b3262e08384272
src/extension.ts
src/extension.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Alessandro Fragnani. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Container } from './container'; import { registerWhatsNew } from './whats-new/commands'; import { registerGenerateTags } from './commands/generateTags'; import { registerProviders } from './providers'; import { registerWalkthrough } from "./commands/walkthrough"; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { Container.context = context; registerWhatsNew(); registerProviders(); registerGenerateTags(); registerWalkthrough(); vscode.workspace.onDidGrantWorkspaceTrust(() => { registerProviders(); registerGenerateTags(); }) }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Alessandro Fragnani. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Container } from './container'; import { registerWhatsNew } from './whats-new/commands'; import { registerGenerateTags } from './commands/generateTags'; import { registerProviders } from './providers'; import { registerWalkthrough } from "./commands/walkthrough"; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export async function activate(context: vscode.ExtensionContext) { Container.context = context; await registerWhatsNew(); registerProviders(); registerGenerateTags(); registerWalkthrough(); vscode.workspace.onDidGrantWorkspaceTrust(() => { registerProviders(); registerGenerateTags(); }) }
Fix missing async/await for web ready whats-new
Fix missing async/await for web ready whats-new
TypeScript
mit
alefragnani/vscode-language-pascal,alefragnani/vscode-language-pascal
--- +++ @@ -13,11 +13,11 @@ // this method is called when your extension is activated // your extension is activated the very first time the command is executed -export function activate(context: vscode.ExtensionContext) { +export async function activate(context: vscode.ExtensionContext) { Container.context = context; - registerWhatsNew(); + await registerWhatsNew(); registerProviders(); registerGenerateTags(); registerWalkthrough();
cd59c132ca2de8557eb4b232855fe44f7b991ded
src/components/input.tsx
src/components/input.tsx
import * as React from "react" import styled from "styled-components" import colors from "../assets/colors" import * as fonts from "../assets/fonts" import { block } from "./helpers" import { borderedInput } from "./mixins" export interface InputProps extends React.HTMLProps<HTMLInputElement> { error?: boolean block?: boolean } const Input: React.SFC<InputProps> = props => ( <input {...props} /> ) export default styled(Input)` ${borderedInput} ${block(24)} `
import * as React from "react" import styled from "styled-components" import colors from "../assets/colors" import * as fonts from "../assets/fonts" import { block } from "./helpers" import { borderedInput } from "./mixins" export interface InputProps extends React.HTMLProps<HTMLInputElement> { error?: boolean block?: boolean } const Input: React.SFC<InputProps> = ({ block, ...props }) => ( <input {...props} /> ) export default styled(Input)` ${borderedInput} ${block(24)} `
Fix warning by not passing on `block` prop.
[Input] Fix warning by not passing on `block` prop.
TypeScript
mit
craigspaeth/reaction,artsy/reaction,craigspaeth/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction,craigspaeth/reaction
--- +++ @@ -10,7 +10,7 @@ block?: boolean } -const Input: React.SFC<InputProps> = props => ( +const Input: React.SFC<InputProps> = ({ block, ...props }) => ( <input {...props} /> )
e39b75ceb9f40e43e82956aea0161bf8373a8253
src/index.ts
src/index.ts
import { SandboxParameter } from './interfaces'; import nativeAddon from './nativeAddon'; import { SandboxProcess } from './sandboxProcess'; import { existsSync } from 'fs'; if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) { throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme."); } const startSandbox = function (parameter: SandboxParameter) { return new Promise((res, rej) => { nativeAddon.StartChild(parameter, function (err, result) { if (err) rej(err); else res(new SandboxProcess(result.pid, parameter)); }); }); }; export { startSandbox };
import { SandboxParameter } from './interfaces'; import nativeAddon from './nativeAddon'; import { SandboxProcess } from './sandboxProcess'; import { existsSync } from 'fs'; if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) { throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme."); } export async function startSandbox(parameter: SandboxParameter): Promise<SandboxProcess> { return new Promise<SandboxProcess>((res, rej) => { nativeAddon.StartChild(parameter, function (err, result) { if (err) rej(err); else res(new SandboxProcess(result.pid, parameter)); }); }); };
Add return type for startSandbox.
Add return type for startSandbox.
TypeScript
mit
t123yh/simple-sandbox,t123yh/simple-sandbox
--- +++ @@ -7,8 +7,8 @@ throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme."); } -const startSandbox = function (parameter: SandboxParameter) { - return new Promise((res, rej) => { +export async function startSandbox(parameter: SandboxParameter): Promise<SandboxProcess> { + return new Promise<SandboxProcess>((res, rej) => { nativeAddon.StartChild(parameter, function (err, result) { if (err) rej(err); @@ -17,5 +17,3 @@ }); }); }; - -export { startSandbox };
7172e88720f17711f9e2e6f3ae0f693d97848b0a
src/lib/cookie-helper.ts
src/lib/cookie-helper.ts
"use strict"; export default class CookieHelper { public static hasItem(key: string): boolean { return !!this.getItem(key); } public static getItem(key: string): string { const result = document.cookie.replace(new RegExp("(?:(?:^|.*;\\\s*)" + encodeURIComponent(key) + "\\\s*\\\=\\\s*([^;]*).*$)|^.*$"), "$1"); return result ? result[1] : null; } public static setItem(key: string, value: string, expires: Date, path?: string, domain?: string, secure?: boolean): void { document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + "; expires=" + expires.toUTCString() + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : ""); } public static removeItem(key: string, path?: string, domain?: string): void { if (CookieHelper.hasItem(key)) { this.setItem(key, "", new Date(0), path, domain); } } }
"use strict"; export default class CookieHelper { public static hasItem(key: string): boolean { return !!this.getItem(key); } public static getItem(key: string): string { const result = document.cookie.replace(new RegExp("(?:(?:^|.*;\\\s*)" + encodeURIComponent(key) + "\\\s*\\\=\\\s*([^;]*).*$)|^.*$"), "$1"); return result ? result : null; } public static setItem(key: string, value: string, expires: Date, path?: string, domain?: string, secure?: boolean): void { document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value) + "; expires=" + expires.toUTCString() + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : ""); } public static removeItem(key: string, path?: string, domain?: string): void { if (CookieHelper.hasItem(key)) { this.setItem(key, "", new Date(0), path, domain); } } }
Fix bug when getting cookies.
Fix bug when getting cookies.
TypeScript
mit
CocoonIO/cocoon-cloud-sdk,CocoonIO/cocoon-cloud-sdk,CocoonIO/cocoon-cloud-sdk
--- +++ @@ -8,7 +8,7 @@ public static getItem(key: string): string { const result = document.cookie.replace(new RegExp("(?:(?:^|.*;\\\s*)" + encodeURIComponent(key) + "\\\s*\\\=\\\s*([^;]*).*$)|^.*$"), "$1"); - return result ? result[1] : null; + return result ? result : null; } public static setItem(key: string, value: string, expires: Date,
3d39263728c7e0b1dcfb87e49c2b80f89a206fd8
src/definitions/Views.ts
src/definitions/Views.ts
import {ResponseBody} from "./Common"; import {ResponseModel} from "./Handler"; let ViewsDirectory = require("../definitions/ViewsDirectory"); namespace Views { export class View { constructor(id: string, render: RendersResponse) { this.id = id; this.render = render; ViewsDirectory[id] = this; } id: string; render: RendersResponse; } export interface RendersResponse { (model: ResponseModel): ResponseBody | Promise<ResponseBody>; } } export = Views;
import * as ViewsDirectory from "../definitions/ViewsDirectory"; import {ResponseBody} from "./Common"; import {ResponseModel} from "./Handler"; export class View { constructor(id: string, render: RendersResponse) { this.id = id; this.render = render; ViewsDirectory[id] = this; } id: string; render: RendersResponse; } export interface RendersResponse { (model: ResponseModel): ResponseBody | Promise<ResponseBody>; }
Use import instead of require. Remove unnecessary namespace.
Use import instead of require. Remove unnecessary namespace.
TypeScript
agpl-3.0
deegles/cookietime,deegles/cookietime
--- +++ @@ -1,25 +1,20 @@ +import * as ViewsDirectory from "../definitions/ViewsDirectory"; import {ResponseBody} from "./Common"; import {ResponseModel} from "./Handler"; -let ViewsDirectory = require("../definitions/ViewsDirectory"); -namespace Views { +export class View { + constructor(id: string, render: RendersResponse) { + this.id = id; + this.render = render; - export class View { - constructor(id: string, render: RendersResponse) { - this.id = id; - this.render = render; - - ViewsDirectory[id] = this; - } - - id: string; - - render: RendersResponse; + ViewsDirectory[id] = this; } - export interface RendersResponse { - (model: ResponseModel): ResponseBody | Promise<ResponseBody>; - } + id: string; + + render: RendersResponse; } -export = Views; +export interface RendersResponse { + (model: ResponseModel): ResponseBody | Promise<ResponseBody>; +}
30c6b86853d7ebb8711524dd7b649bed180ec7ce
lib/src/_shared/MaskedInput.tsx
lib/src/_shared/MaskedInput.tsx
import * as PropTypes from 'prop-types'; import * as React from 'react'; import MaskedInput, { MaskedInputProps } from 'react-text-mask'; export interface CustomMaskedInputProps extends MaskedInputProps { mask?: MaskedInputProps['mask']; inputRef: React.Ref<any>; } export default class Input extends React.PureComponent<CustomMaskedInputProps> { public static propTypes: any = { mask: PropTypes.any, inputRef: PropTypes.func.isRequired, }; public static defaultProps = { mask: undefined, }; public createInputRef = (ref: MaskedInput | null) => { // @ts-ignore masked input really has input element in the component instance this.props.inputRef(ref ? ref.inputElement : null); }; public render() { const { inputRef, keepCharPositions, ...rest } = this.props; return this.props.mask ? ( <MaskedInput {...rest} ref={this.createInputRef} keepCharPositions={keepCharPositions} /> ) : ( <input {...rest} ref={inputRef} /> ); } }
import * as PropTypes from 'prop-types'; import * as React from 'react'; import MaskedInput, { MaskedInputProps } from 'react-text-mask'; export interface CustomMaskedInputProps extends MaskedInputProps { mask?: MaskedInputProps['mask']; inputRef: React.Ref<any>; } export default class Input extends React.PureComponent<CustomMaskedInputProps> { public static propTypes: any = { mask: PropTypes.any, inputRef: PropTypes.func.isRequired, }; public static defaultProps = { mask: undefined, }; public createInputRef = (ref: MaskedInput | null) => { const { inputRef } = this.props; if (inputRef && typeof inputRef === 'function') { // @ts-ignore inputElement exists in Masked input. Issue in typings inputRef(ref ? ref.inputElement : null); } }; public render() { const { inputRef, keepCharPositions, ...rest } = this.props; return this.props.mask ? ( <MaskedInput {...rest} ref={this.createInputRef} keepCharPositions={keepCharPositions} /> ) : ( <input {...rest} ref={inputRef} /> ); } }
Add @ts-ignore to prevent ts error
Add @ts-ignore to prevent ts error
TypeScript
mit
callemall/material-ui,oliviertassinari/material-ui,oliviertassinari/material-ui,mui-org/material-ui,dmtrKovalenko/material-ui-pickers,dmtrKovalenko/material-ui-pickers,callemall/material-ui,mui-org/material-ui,mui-org/material-ui,callemall/material-ui,mbrookes/material-ui,rscnt/material-ui,callemall/material-ui,rscnt/material-ui,mbrookes/material-ui,oliviertassinari/material-ui,rscnt/material-ui,mbrookes/material-ui
--- +++ @@ -18,8 +18,12 @@ }; public createInputRef = (ref: MaskedInput | null) => { - // @ts-ignore masked input really has input element in the component instance - this.props.inputRef(ref ? ref.inputElement : null); + const { inputRef } = this.props; + + if (inputRef && typeof inputRef === 'function') { + // @ts-ignore inputElement exists in Masked input. Issue in typings + inputRef(ref ? ref.inputElement : null); + } }; public render() {
9026712d5c399e41568207e5b2aba1ceffd765a4
pkg/grid/src/components/icons/Lock.tsx
pkg/grid/src/components/icons/Lock.tsx
import React from 'react'; export const Lock = (props: React.SVGProps<SVGSVGElement>) => ( <svg width="10" height="12" viewBox="-11 -8 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M8 5H9C9.55228 5 10 5.44772 10 6V11C10 11.5523 9.55229 12 9 12H1C0.447716 12 0 11.5523 0 11V6C0 5.44772 0.447715 5 1 5H2V3C2 1.34315 3.34315 0 5 0C6.65685 0 8 1.34315 8 3V5ZM7 5V3C7 1.89543 6.10457 1 5 1C3.89543 1 3 1.89543 3 3V5H7ZM3 6H9V11H1V6H2H3Z" fill="black" strokeMiterlimit="10" /> </svg> );
import React from 'react'; export const Lock = (props: React.SVGProps<SVGSVGElement>) => ( <svg width="10" height="12" viewBox="-11 -8 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M8 5H9C9.55228 5 10 5.44772 10 6V11C10 11.5523 9.55229 12 9 12H1C0.447716 12 0 11.5523 0 11V6C0 5.44772 0.447715 5 1 5H2V3C2 1.34315 3.34315 0 5 0C6.65685 0 8 1.34315 8 3V5ZM7 5V3C7 1.89543 6.10457 1 5 1C3.89543 1 3 1.89543 3 3V5H7ZM3 6H9V11H1V6H2H3Z" className="fill-current" strokeMiterlimit="10" /> </svg> );
Replace fill with class fill-current
Replace fill with class fill-current
TypeScript
mit
ngzax/urbit,ngzax/urbit,urbit/urbit,urbit/urbit,urbit/urbit,ngzax/urbit,ngzax/urbit,ngzax/urbit,ngzax/urbit,ngzax/urbit,urbit/urbit,urbit/urbit,urbit/urbit,urbit/urbit
--- +++ @@ -13,7 +13,7 @@ fillRule="evenodd" clipRule="evenodd" d="M8 5H9C9.55228 5 10 5.44772 10 6V11C10 11.5523 9.55229 12 9 12H1C0.447716 12 0 11.5523 0 11V6C0 5.44772 0.447715 5 1 5H2V3C2 1.34315 3.34315 0 5 0C6.65685 0 8 1.34315 8 3V5ZM7 5V3C7 1.89543 6.10457 1 5 1C3.89543 1 3 1.89543 3 3V5H7ZM3 6H9V11H1V6H2H3Z" - fill="black" + className="fill-current" strokeMiterlimit="10" /> </svg>
3e8c9734970fae2383f8c606b3b8d2ede1238ddd
problems/additional-pylons/solution.ts
problems/additional-pylons/solution.ts
import {ISolution} from '../solution.interface'; export class Solution implements ISolution<string, string> { units = { "Probe": 1, "Zealot": 2, "Sentry": 2, "Stalker": 2, "HighTemplar": 2, "DarkTemplar": 2, "Immortal": 4, "Colossus": 6, "Archon": 4, "Observer": 1, "WarpPrism": 2, "Phoenix": 2, "MothershipCore": 2, "VoidRay": 4, "Oracle": 3, "Tempest": 4, "Carrier": 6, "Mothership": 8 }; solve(input: string): string { let pylons = parseInt(input.split(' ')[0]); let units = input.split(' ').slice(1); return units.join(' '); } }
import {ISolution} from '../solution.interface'; export class Solution implements ISolution<string, string> { units = { "Probe": 1, "Zealot": 2, "Sentry": 2, "Stalker": 2, "HighTemplar": 2, "DarkTemplar": 2, "Immortal": 4, "Colossus": 6, "Archon": 4, "Observer": 1, "WarpPrism": 2, "Phoenix": 2, "MothershipCore": 2, "VoidRay": 4, "Oracle": 3, "Tempest": 4, "Carrier": 6, "Mothership": 8 }; solve(input: string): string { let supply = parseInt(input.split(' ')[0]) * 8; let units = input.split(' ').slice(1); return units.join(' '); } }
STore supply rather than pylon count
STore supply rather than pylon count
TypeScript
unlicense
Jameskmonger/challenges
--- +++ @@ -23,7 +23,7 @@ }; solve(input: string): string { - let pylons = parseInt(input.split(' ')[0]); + let supply = parseInt(input.split(' ')[0]) * 8; let units = input.split(' ').slice(1); return units.join(' ');
92828028db28c92d7d36324d445a69d62351df48
src/remote/activitypub/renderer/index.ts
src/remote/activitypub/renderer/index.ts
export default (x: any) => Object.assign({ '@context': [ 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1', { Hashtag: 'as:Hashtag' } ] }, x);
import config from '../../../config'; import * as uuid from 'uuid'; export default (x: any) => { if (x !== null && typeof x === 'object' && x.id == null) { x.id = `${config.url}/${uuid.v4()}`; } return Object.assign({ '@context': [ 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1', { Hashtag: 'as:Hashtag' } ] }, x); };
Add Activity id if missing
Add Activity id if missing
TypeScript
mit
syuilo/Misskey,syuilo/Misskey
--- +++ @@ -1,7 +1,16 @@ -export default (x: any) => Object.assign({ - '@context': [ - 'https://www.w3.org/ns/activitystreams', - 'https://w3id.org/security/v1', - { Hashtag: 'as:Hashtag' } - ] -}, x); +import config from '../../../config'; +import * as uuid from 'uuid'; + +export default (x: any) => { + if (x !== null && typeof x === 'object' && x.id == null) { + x.id = `${config.url}/${uuid.v4()}`; + } + + return Object.assign({ + '@context': [ + 'https://www.w3.org/ns/activitystreams', + 'https://w3id.org/security/v1', + { Hashtag: 'as:Hashtag' } + ] + }, x); +};
7ce5316d1e5b816ea073e99352e30092471b5271
src/utils/ng-validate.ts
src/utils/ng-validate.ts
import {messageJumpContext, browserSubscribeOnce} from '../communication/message-dispatch'; import {MessageFactory} from '../communication/message-factory'; import {MessageType} from '../communication/message-type'; import {send} from '../backend/indirect-connection'; declare const getAllAngularTestabilities: Function; let unsubscribe: () => void; const handler = () => { // variable getAllAngularTestabilities will be defined by Angular // in debug mode for an Angular application. if (typeof getAllAngularTestabilities === 'function') { messageJumpContext(MessageFactory.frameworkLoaded()); if (unsubscribe) { unsubscribe(); } return true; } // We do this to make sure message is display when Augury is first opened. browserSubscribeOnce(MessageType.Initialize, () => { send(MessageFactory.notNgApp()); }); // Called each time browser is refreshed. send(MessageFactory.notNgApp()); return false; }; if (!handler()) { const subscribe = () => { if (MutationObserver) { const observer = new MutationObserver(mutations => handler()); observer.observe(document, { childList: true, subtree: true }); return () => observer.disconnect(); } const eventKeys = ['DOMNodeInserted', 'DOMNodeRemoved']; eventKeys.forEach(k => document.addEventListener(k, handler, false)); return () => eventKeys.forEach(k => document.removeEventListener(k, handler, false)); }; unsubscribe = subscribe(); }
import {messageJumpContext, browserSubscribeOnce} from '../communication/message-dispatch'; import {MessageFactory} from '../communication/message-factory'; import {MessageType} from '../communication/message-type'; import {send} from '../backend/indirect-connection'; declare const getAllAngularTestabilities: Function; declare const getAllAngularRootElements: Function; declare const ng: any; let unsubscribe: () => void; const handler = () => { // variable getAllAngularTestabilities will be defined by Angular // in debug mode for an Angular application. if (ng && (<any>window).getAllAngularRootElements && ng.probe(getAllAngularRootElements()[0])) { messageJumpContext(MessageFactory.frameworkLoaded()); if (unsubscribe) { unsubscribe(); } return true; } // We do this to make sure message is display when Augury is first opened. browserSubscribeOnce(MessageType.Initialize, () => { send(MessageFactory.notNgApp()); }); // Called each time browser is refreshed. send(MessageFactory.notNgApp()); return false; }; if (!handler()) { const subscribe = () => { if (MutationObserver) { const observer = new MutationObserver(mutations => handler()); observer.observe(document, { childList: true, subtree: true }); return () => observer.disconnect(); } const eventKeys = ['DOMNodeInserted', 'DOMNodeRemoved']; eventKeys.forEach(k => document.addEventListener(k, handler, false)); return () => eventKeys.forEach(k => document.removeEventListener(k, handler, false)); }; unsubscribe = subscribe(); }
Update prod mode check to reflect changes in angular core
Update prod mode check to reflect changes in angular core
TypeScript
mit
rangle/augury,rangle/augury,rangle/batarangle,rangle/batarangle,rangle/batarangle,rangle/batarangle,rangle/augury,rangle/augury
--- +++ @@ -4,13 +4,15 @@ import {send} from '../backend/indirect-connection'; declare const getAllAngularTestabilities: Function; +declare const getAllAngularRootElements: Function; +declare const ng: any; let unsubscribe: () => void; const handler = () => { // variable getAllAngularTestabilities will be defined by Angular // in debug mode for an Angular application. - if (typeof getAllAngularTestabilities === 'function') { + if (ng && (<any>window).getAllAngularRootElements && ng.probe(getAllAngularRootElements()[0])) { messageJumpContext(MessageFactory.frameworkLoaded()); if (unsubscribe) {
4e699ce9212b790db69dcbe20e5bcfe01e393d6a
src/__tests__/server-test.ts
src/__tests__/server-test.ts
(jest as any).disableAutomock(); import middleware from '../server'; describe('retax server', () => { it('exposes the middleware', () => { expect(middleware instanceof Function).toBeTruthy(); }); });
(jest as any).disableAutomock(); import middleware from '../server'; describe('retax server', () => { const serverConfig = { serverRendering: true, }; it('exposes the middleware', () => { expect(middleware instanceof Function).toBeTruthy(); expect(middleware(serverConfig) instanceof Function); }); });
Increase the coverage to 100%.
Increase the coverage to 100%. Just to have a green badge! These tests for 'retax' are not really revelant. All sub retax modules are already tested.
TypeScript
mit
retaxJS/retax
--- +++ @@ -3,7 +3,12 @@ import middleware from '../server'; describe('retax server', () => { + const serverConfig = { + serverRendering: true, + }; + it('exposes the middleware', () => { expect(middleware instanceof Function).toBeTruthy(); + expect(middleware(serverConfig) instanceof Function); }); });
59836faeabaa39b69cf7dad0334e72d51a61b3b6
commands/device/run-application.ts
commands/device/run-application.ts
///<reference path="../../../.d.ts"/> "use strict"; import options = require("./../../options"); import helpers = require("./../../helpers"); export class RunApplicationOnDeviceCommand implements ICommand { constructor(private $devicesServices: Mobile.IDevicesServices, private $stringParameter: ICommandParameter) { } allowedParameters: ICommandParameter[] = [this.$stringParameter]; public execute(args: string[]): IFuture<void> { return (() => { this.$devicesServices.initialize({ deviceId: options.device, skipInferPlatform: true }).wait(); var action = (device: Mobile.IDevice) => { return (() => device.runApplication(args[0]).wait()).future<void>()(); }; this.$devicesServices.execute(action).wait(); }).future<void>()(); } } $injector.registerCommand("device|run", RunApplicationOnDeviceCommand);
///<reference path="../../../.d.ts"/> "use strict"; import options = require("./../../options"); import helpers = require("./../../helpers"); export class RunApplicationOnDeviceCommand implements ICommand { constructor(private $devicesServices: Mobile.IDevicesServices, private $errors: IErrors, private $stringParameter: ICommandParameter) { } allowedParameters: ICommandParameter[] = [this.$stringParameter]; public execute(args: string[]): IFuture<void> { return (() => { this.$devicesServices.initialize({ deviceId: options.device, skipInferPlatform: true }).wait(); if (this.$devicesServices.deviceCount > 1) { this.$errors.fail("More than one device found. Specify device explicitly with --device option.To discover device ID, use $appbuilder device command."); } var action = (device: Mobile.IDevice) => { return (() => device.runApplication(args[0]).wait()).future<void>()(); }; this.$devicesServices.execute(action).wait(); }).future<void>()(); } } $injector.registerCommand("device|run", RunApplicationOnDeviceCommand);
Throw error if run command is executed and more than one device found
Throw error if run command is executed and more than one device found
TypeScript
apache-2.0
telerik/mobile-cli-lib,telerik/mobile-cli-lib
--- +++ @@ -7,6 +7,7 @@ export class RunApplicationOnDeviceCommand implements ICommand { constructor(private $devicesServices: Mobile.IDevicesServices, + private $errors: IErrors, private $stringParameter: ICommandParameter) { } allowedParameters: ICommandParameter[] = [this.$stringParameter]; @@ -15,6 +16,10 @@ return (() => { this.$devicesServices.initialize({ deviceId: options.device, skipInferPlatform: true }).wait(); + if (this.$devicesServices.deviceCount > 1) { + this.$errors.fail("More than one device found. Specify device explicitly with --device option.To discover device ID, use $appbuilder device command."); + } + var action = (device: Mobile.IDevice) => { return (() => device.runApplication(args[0]).wait()).future<void>()(); }; this.$devicesServices.execute(action).wait(); }).future<void>()();
9d1e69bc77fa510a57f2d9f05e0548d8ba1c98f4
front/react/components/sidebar/index.tsx
front/react/components/sidebar/index.tsx
import * as React from 'react'; const Sidebar = (props: { width: number } = { width: 200 }) => ( <div style={{ width: props.width, flex: 1, overflow: 'auto', backgroundColor: '#666', }}> </div> ) export default Sidebar
import * as React from 'react'; const Sidebar = (props: { width: number } = { width: 200 }) => ( <div style={{ width: props.width, flex: 1, overflow: 'auto', backgroundColor: '#444', }}> </div> ) export default Sidebar
Set sidebar bg to 444
Set sidebar bg to 444
TypeScript
mit
paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,paypac/node-concierge,the-concierge/concierge
--- +++ @@ -5,7 +5,7 @@ width: props.width, flex: 1, overflow: 'auto', - backgroundColor: '#666', + backgroundColor: '#444', }}> </div> )
90dc07219f744c76fab0df0395c23d7e672fab9f
examples/react-ts/src/button.stories.tsx
examples/react-ts/src/button.stories.tsx
import React from 'react'; import { Meta } from '@storybook/react'; import { Button } from './button'; export default { component: Button, title: 'Examples / Button' } as Meta; export const WithArgs = (args: any) => <Button {...args} />; WithArgs.args = { label: 'With args' }; export const Basic = () => <Button label="Click me" />;
import React from 'react'; import { Meta } from '@storybook/react'; import { Button } from './button'; export default { component: Button, title: 'Examples / Button', argTypes: { onClick: { action: 'click ' } }, } as Meta; export const WithArgs = (args: any) => <Button {...args} />; WithArgs.args = { label: 'With args' }; export const Basic = () => <Button label="Click me" />;
Add click action to react-ts example
Add click action to react-ts example
TypeScript
mit
storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook
--- +++ @@ -2,7 +2,11 @@ import { Meta } from '@storybook/react'; import { Button } from './button'; -export default { component: Button, title: 'Examples / Button' } as Meta; +export default { + component: Button, + title: 'Examples / Button', + argTypes: { onClick: { action: 'click ' } }, +} as Meta; export const WithArgs = (args: any) => <Button {...args} />; WithArgs.args = { label: 'With args' };
0efcea0215dc3e858283332f9897027b628a955e
src/tinymce-editor-settings.service.ts
src/tinymce-editor-settings.service.ts
import { Injectable } from '@angular/core'; @Injectable() export class TinymceEditorSettingsService { skin_url = '/assets/tinymce/skins/lightgray'; toolbar = 'undo redo | styleselect | bold italic | link image'; plugins = 'link paste'; schema = 'html5'; }
import { Injectable } from '@angular/core'; @Injectable() export class TinymceEditorSettingsService { skin_url = '/assets/tinymce/skins/lightgray'; toolbar = 'undo redo | styleselect | bold italic | link image'; schema = 'html5'; }
Remove plugins, should be added by user
Remove plugins, should be added by user
TypeScript
mit
mchlbrnd/ng-tinymce,mchlbrnd/ng-tinymce
--- +++ @@ -4,7 +4,6 @@ export class TinymceEditorSettingsService { skin_url = '/assets/tinymce/skins/lightgray'; toolbar = 'undo redo | styleselect | bold italic | link image'; - plugins = 'link paste'; schema = 'html5'; }
a278e719ebaa497bb75a8f82c7ddf938b8478a24
test/unit/utils/index.ts
test/unit/utils/index.ts
import Vuex from 'vuex' import {shallowMount, createLocalVue} from '@vue/test-utils' export const mountMixin = ( component: object, mountOptions: object = {}, template: string = '<div />' ) => { const localVue = createLocalVue(); localVue.use(Vuex); return shallowMount({ template, mixins: [component] }, { localVue, ...mountOptions }) }; export const mountMixinWithStore = ( component: object, storeOptions: object = {}, mountOptions: object = {}, template: string = '<div />' ) => { const localVue = createLocalVue(); localVue.use(Vuex); const store = new Vuex.Store({ ...storeOptions }); return shallowMount({ template, mixins: [component] }, { store, localVue, ...mountOptions }) }; export const createContextMock = (props = {}) => ({ // @ts-ignore commit: jest.fn(), // @ts-ignore dispatch: jest.fn(), // @ts-ignore ...props })
import Vuex from 'vuex' import { shallowMount, createLocalVue, Wrapper, ThisTypedShallowMountOptions } from '@vue/test-utils'; import Vue, { ComponentOptions } from 'vue'; export const mountMixin = <V extends Vue>( component: ComponentOptions<V>, mountOptions: ThisTypedShallowMountOptions<V> = {}, template = '<div />' ): Wrapper<V> => { const localVue = createLocalVue(); localVue.use(Vuex); return shallowMount({ template, mixins: [component] }, { localVue, ...mountOptions }) }; export const mountMixinWithStore = <V extends Vue>( component: ComponentOptions<V>, storeOptions: object = {}, mountOptions: ThisTypedShallowMountOptions<V> = {}, template = '<div />' ): Wrapper<V> => { const localVue = createLocalVue(); localVue.use(Vuex); const store = new Vuex.Store({ ...storeOptions }); return shallowMount({ template, mixins: [component] }, { store, localVue, ...mountOptions }) }; export const createContextMock = (props = {}) => ({ // @ts-ignore commit: jest.fn(), // @ts-ignore dispatch: jest.fn(), // @ts-ignore ...props })
Improve typescript support for test utils
Improve typescript support for test utils
TypeScript
mit
DivanteLtd/vue-storefront,pkarw/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront
--- +++ @@ -1,11 +1,12 @@ import Vuex from 'vuex' -import {shallowMount, createLocalVue} from '@vue/test-utils' +import { shallowMount, createLocalVue, Wrapper, ThisTypedShallowMountOptions } from '@vue/test-utils'; +import Vue, { ComponentOptions } from 'vue'; -export const mountMixin = ( - component: object, - mountOptions: object = {}, - template: string = '<div />' -) => { +export const mountMixin = <V extends Vue>( + component: ComponentOptions<V>, + mountOptions: ThisTypedShallowMountOptions<V> = {}, + template = '<div />' +): Wrapper<V> => { const localVue = createLocalVue(); localVue.use(Vuex); @@ -19,12 +20,12 @@ }) }; -export const mountMixinWithStore = ( - component: object, +export const mountMixinWithStore = <V extends Vue>( + component: ComponentOptions<V>, storeOptions: object = {}, - mountOptions: object = {}, - template: string = '<div />' -) => { + mountOptions: ThisTypedShallowMountOptions<V> = {}, + template = '<div />' +): Wrapper<V> => { const localVue = createLocalVue(); localVue.use(Vuex);
a5c786c25289f05029a82b75a4224d3a79165f35
app/src/renderer/components/paper/paper-menu.tsx
app/src/renderer/components/paper/paper-menu.tsx
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as React from 'react'; import { PolymerComponent } from './polymer'; import { omitOwnProps } from '../../../common/utils'; /** * React component that wraps a Polymer paper-menu custom element. */ export class PaperMenuComponent extends PolymerComponent<PolymerElements.PaperMenu, PaperMenuComponent.IProps> { protected get cssVars() { const styles = this.props.styles; const vars: any = {}; if (styles) { if (styles.backgroundColor) { vars['--paper-menu-background-color'] = styles.backgroundColor; } if (styles.textColor) { vars['--paper-menu-color'] = styles.textColor; } } return vars; } protected get eventBindings(): PolymerComponent.IEventBinding[] { return []; } protected renderElement(props: PaperMenuComponent.IProps) { const elementProps = omitOwnProps(props, ['styles']); return ( <paper-menu {...elementProps}></paper-menu> ); } } export namespace PaperMenuComponent { export interface IProps extends PolymerComponent.IProps { /** Sets the selected element, by default the value should be the index of a menu item. */ selected?: string | number; styles?: { backgroundColor?: string; textColor?: string; }; } }
// Copyright (c) 2016 Vadim Macagon // MIT License, see LICENSE file for full terms. import * as React from 'react'; import { PolymerComponent } from './polymer'; import { omitOwnProps } from '../../../common/utils'; /** * React component that wraps a Polymer paper-menu custom element. */ export class PaperMenuComponent extends PolymerComponent<PolymerElements.PaperMenu, PaperMenuComponent.IProps> { /** Returns the index of the given item. */ indexOf(item: PolymerElements.PaperItem): number { return this.element.indexOf(item); } protected get cssVars() { const styles = this.props.styles; const vars: any = {}; if (styles) { if (styles.backgroundColor) { vars['--paper-menu-background-color'] = styles.backgroundColor; } if (styles.textColor) { vars['--paper-menu-color'] = styles.textColor; } } return vars; } protected get eventBindings(): PolymerComponent.IEventBinding[] { return []; } protected renderElement(props: PaperMenuComponent.IProps) { const elementProps = omitOwnProps(props, ['styles']); return ( <paper-menu {...elementProps}></paper-menu> ); } } export namespace PaperMenuComponent { export interface IProps extends PolymerComponent.IProps { /** Sets the selected element, by default the value should be the index of a menu item. */ selected?: string | number; styles?: { backgroundColor?: string; textColor?: string; }; } }
Add ability to retrieve the index of an item in the PaperMenuComponent
Add ability to retrieve the index of an item in the PaperMenuComponent
TypeScript
mit
debugworkbench/hydragon,debugworkbench/hydragon,debugworkbench/hydragon
--- +++ @@ -10,6 +10,11 @@ */ export class PaperMenuComponent extends PolymerComponent<PolymerElements.PaperMenu, PaperMenuComponent.IProps> { + + /** Returns the index of the given item. */ + indexOf(item: PolymerElements.PaperItem): number { + return this.element.indexOf(item); + } protected get cssVars() { const styles = this.props.styles;
75ea14061485456441ce80ec5c4bd3604ced4e23
src/svg/components/Spinner.ts
src/svg/components/Spinner.ts
import Config from '../../Config'; import Component from './Component'; class Spinner extends Component { constructor() { super(); } public render(): void { let width: number = this.config.get('imageWidth'), height: number = this.config.get('imageHeight'), marginLeft: number = this.config.get('marginLeft'); this.svg.append('image') .attr('class', 'spinner') .style('opacity', 1) .attr('xlink:href', '../../../images/Spinner.svg') .attr('transform', 'translate(' + (width - marginLeft - 200) + ',' + (height - 200) + ')'); } public update(data: [{}]) { if (typeof data !== undefined && data.length != 0) { this.svg.select('.spinner').style('opacity', 0); } } public transition() {} public clear() {} } export default Spinner;
import Config from '../../Config'; import Component from './Component'; class Spinner extends Component { constructor() { super(); } public render(): void { let width: number = this.config.get('imageWidth'), height: number = this.config.get('imageHeight'), marginLeft: number = this.config.get('marginLeft'); this.svg.append('image') .attr('class', 'spinner') .style('opacity', 1) .attr('xlink:href', '../../../images/Spinner.svg') .attr('width', 200) .attr('height', 200) .attr('transform', 'translate(' + (width - marginLeft - 200) + ',' + (height - 200) + ')'); } public update(data: [{}]) { if (typeof data !== undefined && data.length != 0) { this.svg.select('.spinner').style('opacity', 0); } } public transition() {} public clear() {} } export default Spinner;
Solve issue that spinner doesn't show on firefox
Solve issue that spinner doesn't show on firefox
TypeScript
apache-2.0
proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic,proteus-h2020/proteic
--- +++ @@ -15,6 +15,8 @@ .attr('class', 'spinner') .style('opacity', 1) .attr('xlink:href', '../../../images/Spinner.svg') + .attr('width', 200) + .attr('height', 200) .attr('transform', 'translate(' + (width - marginLeft - 200) + ',' + (height - 200) + ')'); }
bf548c07630f22949808e36142af13d5c77fbd99
packages/lesswrong/lib/collections/books/collection.ts
packages/lesswrong/lib/collections/books/collection.ts
import { createCollection } from '../../vulcan-lib'; import schema from './schema'; import { makeEditable } from '../../editor/make_editable'; import { addUniversalFields, getDefaultResolvers, getDefaultMutations } from '../../collectionUtils' export const Books: BooksCollection = createCollection({ collectionName: 'Books', typeName: 'Book', schema, resolvers: getDefaultResolvers('Books'), mutations: getDefaultMutations('Books'), }); export const makeEditableOptions = { order: 20, getLocalStorageId: (book, name) => { if (book._id) { return {id: `${book._id}_${name}`, verify: false} } return {id: `collection: ${book.collectionId}_${name}`, verify: false} }, } makeEditable({ collection: Books, options: makeEditableOptions }) addUniversalFields({collection: Books}) export default Books;
import { createCollection } from '../../vulcan-lib'; import schema from './schema'; import { makeEditable } from '../../editor/make_editable'; import { addUniversalFields, getDefaultResolvers, getDefaultMutations } from '../../collectionUtils' export const Books: BooksCollection = createCollection({ collectionName: 'Books', typeName: 'Book', schema, resolvers: getDefaultResolvers('Books'), mutations: getDefaultMutations('Books'), }); export const makeEditableOptions = { order: 20, getLocalStorageId: (book, name) => { if (book._id) { return {id: `${book._id}_${name}`, verify: true} } return {id: `collection: ${book.collectionId}_${name}`, verify: false} }, } makeEditable({ collection: Books, options: makeEditableOptions }) addUniversalFields({collection: Books}) export default Books;
Make book have verify true again when editing an existing one
Make book have verify true again when editing an existing one
TypeScript
mit
Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope
--- +++ @@ -14,7 +14,7 @@ export const makeEditableOptions = { order: 20, getLocalStorageId: (book, name) => { - if (book._id) { return {id: `${book._id}_${name}`, verify: false} } + if (book._id) { return {id: `${book._id}_${name}`, verify: true} } return {id: `collection: ${book.collectionId}_${name}`, verify: false} }, }
bdadb1f83da249d86a3d41639355626602bc287e
test/src/filebrowser/model.spec.ts
test/src/filebrowser/model.spec.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import expect = require('expect.js'); import { MockServiceManager } from 'jupyter-js-services/lib/mockmanager'; import { FileBrowserModel } from '../../../lib/filebrowser'; describe('filebrowser/model', () => { describe('FileBrowserModel', () => { describe('#constructor()', () => { it('should construct a new file browser model', () => { let manager = new MockServiceManager(); let model = new FileBrowserModel({ manager }); expect(model).to.be.a(FileBrowserModel); }); }); describe('#pathChanged', () => { it('should be emitted when the path changes', () => { }); }); describe('#refreshed', () => { }); describe('#fileChanged', () => { }); describe('#path', () => { }); describe('#items', () => { }); describe('#isDisposed', () => { }); describe('#sessions', () => { }); describe('#kernelspecs', () => { }); describe('#dispose()', () => { }); describe('#cd()', () => { }); describe('#refresh()', () => { }); describe('#deleteFile()', () => { }); describe('#download()', () => { }); describe('#newUntitled()', () => { }); describe('#rename()', () => { }); describe('#upload()', () => { }); describe('#shutdown()', () => { }); }); });
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import expect = require('expect.js'); import { createServiceManager } from 'jupyter-js-services'; import { FileBrowserModel } from '../../../lib/filebrowser'; describe('filebrowser/model', () => { describe('FileBrowserModel', () => { describe('#constructor()', () => { it('should construct a new file browser model', (done) => { createServiceManager().then(manager => { let model = new FileBrowserModel({ manager }); expect(model).to.be.a(FileBrowserModel); done(); }); }); }); describe('#pathChanged', () => { it('should be emitted when the path changes', () => { }); }); describe('#refreshed', () => { }); describe('#fileChanged', () => { }); describe('#path', () => { }); describe('#items', () => { }); describe('#isDisposed', () => { }); describe('#sessions', () => { }); describe('#kernelspecs', () => { }); describe('#dispose()', () => { }); describe('#cd()', () => { }); describe('#refresh()', () => { }); describe('#deleteFile()', () => { }); describe('#download()', () => { }); describe('#newUntitled()', () => { }); describe('#rename()', () => { }); describe('#upload()', () => { }); describe('#shutdown()', () => { }); }); });
Remove use of mock service manager
Remove use of mock service manager
TypeScript
bsd-3-clause
eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab
--- +++ @@ -4,8 +4,8 @@ import expect = require('expect.js'); import { - MockServiceManager -} from 'jupyter-js-services/lib/mockmanager'; + createServiceManager +} from 'jupyter-js-services'; import { FileBrowserModel @@ -18,10 +18,12 @@ describe('#constructor()', () => { - it('should construct a new file browser model', () => { - let manager = new MockServiceManager(); - let model = new FileBrowserModel({ manager }); - expect(model).to.be.a(FileBrowserModel); + it('should construct a new file browser model', (done) => { + createServiceManager().then(manager => { + let model = new FileBrowserModel({ manager }); + expect(model).to.be.a(FileBrowserModel); + done(); + }); }); });
140d6ad27886e84cae643392ea39d801a1020dc4
tests/cases/fourslash/genericCombinators3.ts
tests/cases/fourslash/genericCombinators3.ts
/// <reference path='fourslash.ts'/> ////interface Collection<T, U> { ////} //// ////interface Combinators { //// map<T, U>(c: Collection<T,U>, f: (x: T, y: U) => any): Collection<any, any>; //// map<T, U, V>(c: Collection<T,U>, f: (x: T, y: U) => V): Collection<T, V>; ////} //// ////var c2: Collection<number, string>; //// ////var _: Combinators; //// ////var r1a/*9*/ = _.ma/*1c*/p(c2, (x/*1a*/,y/*1b*/) => { return x + "" }); // check quick info of map here goTo.marker('1a'); verify.quickInfoIs('number'); goTo.marker('1b'); verify.quickInfoIs('string'); goTo.marker('1c'); verify.quickInfoIs('<T, U, V>(c: Collection<number, string>, f: (x: number, y: string) => string): Collection<number, string> (+ 1 overload(s))');
/// <reference path='fourslash.ts'/> ////interface Collection<T, U> { ////} //// ////interface Combinators { //// map<T, U>(c: Collection<T,U>, f: (x: T, y: U) => any): Collection<any, any>; //// map<T, U, V>(c: Collection<T,U>, f: (x: T, y: U) => V): Collection<T, V>; ////} //// ////var c2: Collection<number, string>; //// ////var _: Combinators; //// ////var r1a/*9*/ = _.ma/*1c*/p(c2, (x/*1a*/,y/*1b*/) => { return x + "" }); // check quick info of map here goTo.marker('1a'); verify.quickInfoIs('number'); goTo.marker('1b'); verify.quickInfoIs('string'); goTo.marker('1c'); verify.quickInfoIs('<T, U, V>(c: Collection<number, string>, f: (x: number, y: string) => string): Collection<number, string> (+ 1 overload(s))'); goTo.marker('9'); verify.quickInfoIs('Collection<number, string>');
Test update for resolved bug
Test update for resolved bug
TypeScript
apache-2.0
fdecampredon/jsx-typescript-old-version,popravich/typescript,popravich/typescript,mbrowne/typescript-dci,hippich/typescript,hippich/typescript,mbebenita/shumway.ts,mbrowne/typescript-dci,popravich/typescript,mbebenita/shumway.ts,hippich/typescript,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci
--- +++ @@ -22,3 +22,6 @@ goTo.marker('1c'); verify.quickInfoIs('<T, U, V>(c: Collection<number, string>, f: (x: number, y: string) => string): Collection<number, string> (+ 1 overload(s))'); + +goTo.marker('9'); +verify.quickInfoIs('Collection<number, string>');
1a46e41ccb3b2f164f8ab0ad708f5d7b32a11972
coffee-chats/src/main/webapp/src/util/fetch.ts
coffee-chats/src/main/webapp/src/util/fetch.ts
import React from "react"; /** * A hook that fetches JSON data from a URL using a GET request * * @param url: URL to fetch data from */ export function useFetch(url: string): any { const [data, setData] = React.useState(null); React.useEffect(() => { (async () => { const response = await fetch(url); const json = await response.json(); if (!response.ok && json.loginUrl) { window.location.href = json.loginUrl; } else { setData(json); } })(); }, [url]); return data; }
import React from "react"; interface ResponseRaceDetect { response: Response; json: any; raceOccurred: boolean; } const fetchAndDetectRaces: (url: string) => Promise<ResponseRaceDetect> = (() => { let requestId = 0; return async (url: string) => { const currentRequestId = ++requestId; const response = await fetch(url); const json = await response.json(); const raceOccurred = requestId != currentRequestId; return {response, json, raceOccurred}; } })(); /** * A hook that fetches JSON data from a URL using a GET request * * @param url: URL to fetch data from */ export function useFetch(url: string): any { const [data, setData] = React.useState(null); React.useEffect(() => { (async () => { const {response, json, raceOccurred} = await fetchAndDetectRaces(url); if (raceOccurred) { return; } if (!response.ok && json.loginUrl) { window.location.href = json.loginUrl; } else { setData(json); } })(); }, [url]); return data; }
Add race detection to useFetch
Add race detection to useFetch
TypeScript
apache-2.0
googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020
--- +++ @@ -1,4 +1,24 @@ import React from "react"; + +interface ResponseRaceDetect { + response: Response; + json: any; + raceOccurred: boolean; +} + +const fetchAndDetectRaces: (url: string) => Promise<ResponseRaceDetect> = (() => { + let requestId = 0; + + return async (url: string) => { + const currentRequestId = ++requestId; + + const response = await fetch(url); + const json = await response.json(); + const raceOccurred = requestId != currentRequestId; + + return {response, json, raceOccurred}; + } +})(); /** * A hook that fetches JSON data from a URL using a GET request @@ -10,8 +30,11 @@ React.useEffect(() => { (async () => { - const response = await fetch(url); - const json = await response.json(); + const {response, json, raceOccurred} = await fetchAndDetectRaces(url); + + if (raceOccurred) { + return; + } if (!response.ok && json.loginUrl) { window.location.href = json.loginUrl;
336e93f3bc77af25c7a81c4ebacd949fdd12af96
types/task-worklet/index.d.ts
types/task-worklet/index.d.ts
// Type definitions for task-worklet 0.1 // Project: https://github.com/GoogleChromeLabs/task-worklet // Definitions by: Karol Majewski <https://github.com/karol-majewski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 declare class TaskQueue { constructor(options?: Options); postTask(taskName: string, ...args: any[]): Task; addModule(moduleURL: string): Promise<void>; } interface Options { size?: number; } export interface Task<T = any> { id: number; state: State; result: Promise<T>; } export type State = | 'cancelled' | 'completed' | 'fulfilled' | 'pending' | 'scheduled'; export default TaskQueue; export as namespace TaskQueue;
// Type definitions for task-worklet 0.1 // Project: https://github.com/developit/task-worklet // Definitions by: Karol Majewski <https://github.com/karol-majewski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 declare class TaskQueue { constructor(options?: Options); postTask(taskName: string, ...args: any[]): Task; addModule(moduleURL: string): Promise<void>; } interface Options { size?: number; } export interface Task<T = any> { id: number; state: State; result: Promise<T>; } export type State = | 'cancelled' | 'completed' | 'fulfilled' | 'pending' | 'scheduled'; export default TaskQueue; export as namespace TaskQueue;
Use the correct repository URL
Use the correct repository URL
TypeScript
mit
magny/DefinitelyTyped,borisyankov/DefinitelyTyped,mcliment/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped
--- +++ @@ -1,5 +1,5 @@ // Type definitions for task-worklet 0.1 -// Project: https://github.com/GoogleChromeLabs/task-worklet +// Project: https://github.com/developit/task-worklet // Definitions by: Karol Majewski <https://github.com/karol-majewski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9
ee545fb5d3222ff0dfec38661f277fe82b82124f
ui/src/idai_shapes/Shapes.tsx
ui/src/idai_shapes/Shapes.tsx
import React, { ReactElement, useEffect, useState } from 'react'; import { Route, Switch, Redirect } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import { LoginContext } from '../App'; import { getPersistedLogin } from '../login'; import { doLogout } from '../logout'; import ShapesNav from '../shared/navbar/ShapesNav'; import BrowseSelect from './browseselect/BrowseSelect'; import { useRouteMatch } from 'react-router-dom'; import Home from './Home/Home'; import NotFound from '../shared/NotFound'; export default function Shapes(): ReactElement { const [loginData, setLoginData] = useState(getPersistedLogin()); const match = useRouteMatch(); useEffect(() => { document.title = 'iDAI.shapes'; }, []); const baseUrl = match.path || '/'; return ( <BrowserRouter> <LoginContext.Provider value={ loginData }> <ShapesNav onLogout={ doLogout(setLoginData) } /> <Switch> <Route path= {baseUrl} exact component={ Home } /> <Redirect exact from={`${baseUrl}document`} to= {baseUrl} /> <Route path={ `${baseUrl}document/:documentId?` } component={ BrowseSelect } /> <Route component={ NotFound } /> </Switch> </LoginContext.Provider> </BrowserRouter> ); }
import React, { ReactElement, useEffect, useState } from 'react'; import { Route, Switch } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import { LoginContext } from '../App'; import { getPersistedLogin } from '../login'; import { doLogout } from '../logout'; import ShapesNav from '../shared/navbar/ShapesNav'; import BrowseSelect from './browseselect/BrowseSelect'; import { useRouteMatch } from 'react-router-dom'; import Home from './Home/Home'; import NotFound from '../shared/NotFound'; export default function Shapes(): ReactElement { const [loginData, setLoginData] = useState(getPersistedLogin()); const match = useRouteMatch(); useEffect(() => { document.title = 'iDAI.shapes'; }, []); const baseUrl = match.path || '/'; return ( <BrowserRouter> <LoginContext.Provider value={ loginData }> <ShapesNav onLogout={ doLogout(setLoginData) } /> <Switch> <Route path= {baseUrl} exact component={ Home } /> <Route path={ `${baseUrl}document/:documentId?` } component={ BrowseSelect } /> <Route component={ NotFound } /> </Switch> </LoginContext.Provider> </BrowserRouter> ); }
Revert "Redirect to <Home /> if no documentId in url"
Revert "Redirect to <Home /> if no documentId in url" This reverts commit b44ecbbe376e4f331826dff98e843d8fa982cc6d. # Conflicts: # ui/src/idai_shapes/Shapes.tsx
TypeScript
apache-2.0
dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web
--- +++ @@ -1,5 +1,5 @@ import React, { ReactElement, useEffect, useState } from 'react'; -import { Route, Switch, Redirect } from 'react-router'; +import { Route, Switch } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import { LoginContext } from '../App'; import { getPersistedLogin } from '../login'; @@ -29,7 +29,6 @@ <ShapesNav onLogout={ doLogout(setLoginData) } /> <Switch> <Route path= {baseUrl} exact component={ Home } /> - <Redirect exact from={`${baseUrl}document`} to= {baseUrl} /> <Route path={ `${baseUrl}document/:documentId?` } component={ BrowseSelect } /> <Route component={ NotFound } /> </Switch>
e9abb31537a2c0c31410fec665e6e50e65c28faf
src/vs/workbench/contrib/notebook/browser/constants.ts
src/vs/workbench/contrib/notebook/browser/constants.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Scrollable Element export const SCROLLABLE_ELEMENT_PADDING_TOP = 20; // Cell sizing related export const CELL_MARGIN = 8; export const CELL_RUN_GUTTER = 28; export const CODE_CELL_LEFT_MARGIN = 32; export const EDITOR_TOOLBAR_HEIGHT = 0; export const BOTTOM_CELL_TOOLBAR_GAP = 18; export const BOTTOM_CELL_TOOLBAR_HEIGHT = 50; export const CELL_STATUSBAR_HEIGHT = 22; // Margin above editor export const CELL_TOP_MARGIN = 6; export const CELL_BOTTOM_MARGIN = 6; // Top and bottom padding inside the monaco editor in a cell, which are included in `cell.editorHeight` // export const EDITOR_TOP_PADDING = 12; export const EDITOR_BOTTOM_PADDING = 4; export const EDITOR_BOTTOM_PADDING_WITHOUT_STATUSBAR = 12; export const CELL_OUTPUT_PADDING = 14; export const COLLAPSED_INDICATOR_HEIGHT = 24;
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Scrollable Element export const SCROLLABLE_ELEMENT_PADDING_TOP = 20; // Cell sizing related export const CELL_MARGIN = 8; export const CELL_RUN_GUTTER = 28; export const CODE_CELL_LEFT_MARGIN = 32; export const EDITOR_TOOLBAR_HEIGHT = 0; export const BOTTOM_CELL_TOOLBAR_GAP = 16; export const BOTTOM_CELL_TOOLBAR_HEIGHT = 24; export const CELL_STATUSBAR_HEIGHT = 22; // Margin above editor export const CELL_TOP_MARGIN = 6; export const CELL_BOTTOM_MARGIN = 6; // Top and bottom padding inside the monaco editor in a cell, which are included in `cell.editorHeight` // export const EDITOR_TOP_PADDING = 12; export const EDITOR_BOTTOM_PADDING = 4; export const EDITOR_BOTTOM_PADDING_WITHOUT_STATUSBAR = 12; export const CELL_OUTPUT_PADDING = 14; export const COLLAPSED_INDICATOR_HEIGHT = 24;
Reduce height of notebook add new cell toolbar
Reduce height of notebook add new cell toolbar Fixes #110274
TypeScript
mit
eamodio/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode
--- +++ @@ -13,8 +13,8 @@ export const CODE_CELL_LEFT_MARGIN = 32; export const EDITOR_TOOLBAR_HEIGHT = 0; -export const BOTTOM_CELL_TOOLBAR_GAP = 18; -export const BOTTOM_CELL_TOOLBAR_HEIGHT = 50; +export const BOTTOM_CELL_TOOLBAR_GAP = 16; +export const BOTTOM_CELL_TOOLBAR_HEIGHT = 24; export const CELL_STATUSBAR_HEIGHT = 22; // Margin above editor
71652865f6af409a07d3058ce86bb375e9461553
console/src/app/core/models/prometheus-chart-dao.mode.ts
console/src/app/core/models/prometheus-chart-dao.mode.ts
import { Observable } from 'rxjs'; import { PrometheusApiService } from '../services/prometheus-api/prometheus-api.service'; import { MongooseChartDataProvider } from './mongoose-chart-data-provider.interface'; export class PrometheusChartDao { private chartDataProvider: MongooseChartDataProvider; constructor(private prometheusApiService: PrometheusApiService) { this.chartDataProvider = prometheusApiService; } public getDuration(): Observable<any> { return this.chartDataProvider.getDuration(); } }
Add implimentation of MongooseChartDataProvider to prometheus service.
Add implimentation of MongooseChartDataProvider to prometheus service.
TypeScript
mit
emc-mongoose/console,emc-mongoose/console,emc-mongoose/console
--- +++ @@ -0,0 +1,17 @@ +import { Observable } from 'rxjs'; +import { PrometheusApiService } from '../services/prometheus-api/prometheus-api.service'; +import { MongooseChartDataProvider } from './mongoose-chart-data-provider.interface'; + +export class PrometheusChartDao { + + private chartDataProvider: MongooseChartDataProvider; + + constructor(private prometheusApiService: PrometheusApiService) { + this.chartDataProvider = prometheusApiService; + } + + public getDuration(): Observable<any> { + return this.chartDataProvider.getDuration(); + } + +}
8eee3cab5013253a58ef9cbb183cfbf9d37f7e0d
src/lib/stitching/convection/stitching.ts
src/lib/stitching/convection/stitching.ts
import { GraphQLSchema } from "graphql" export const consignmentStitchingEnvironment = ( localSchema: GraphQLSchema, convectionSchema: GraphQLSchema & { transforms: any } ) => ({ // The SDL used to declare how to stitch an object extensionSchema: ` extend type ConsignmentSubmission { artist: Artist } `, // Resolvers for the above resolvers: { ConsignmentSubmission: { artist: { fragment: `fragment SubmissionArtist on ConsignmentSubmission { artist_id }`, resolve: (parent, _args, context, info) => { const id = parent.artist_id return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "artist", args: { id, }, context, info, transforms: convectionSchema.transforms, }) }, }, }, }, })
import { GraphQLSchema } from "graphql" export const consignmentStitchingEnvironment = ( localSchema: GraphQLSchema, convectionSchema: GraphQLSchema & { transforms: any } ) => ({ // The SDL used to declare how to stitch an object extensionSchema: ` extend type ConsignmentSubmission { artist: Artist } `, // Resolvers for the above resolvers: { ConsignmentSubmission: { artist: { fragment: `fragment SubmissionArtist on ConsignmentSubmission { artistId }`, resolve: (parent, _args, context, info) => { const id = parent.artistId return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "artist", args: { id, }, context, info, transforms: convectionSchema.transforms, }) }, }, }, }, })
Fix convection artist id mapping
Fix convection artist id mapping
TypeScript
mit
artsy/metaphysics,artsy/metaphysics,artsy/metaphysics
--- +++ @@ -15,9 +15,9 @@ resolvers: { ConsignmentSubmission: { artist: { - fragment: `fragment SubmissionArtist on ConsignmentSubmission { artist_id }`, + fragment: `fragment SubmissionArtist on ConsignmentSubmission { artistId }`, resolve: (parent, _args, context, info) => { - const id = parent.artist_id + const id = parent.artistId return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query",
b619a44b5dfcc95db028034dd1f9a05b859f28ba
lib/msal-node/src/client/IConfidentialClientApplication.ts
lib/msal-node/src/client/IConfidentialClientApplication.ts
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AuthenticationResult, ClientCredentialRequest, OnBehalfOfRequest } from "@azure/msal-common"; import { NodeConfigurationAuthError } from "../error/NodeConfigurationAuthError"; export interface IConfidentialClientApplication { acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult>; acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult>; } export const stubbedConfidentialClientApplication: IConfidentialClientApplication = { acquireTokenByClientCredential: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenOnBehalfOf: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); } };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { AuthenticationResult, AuthorizationCodeRequest, AuthorizationUrlRequest, ClientCredentialRequest, Logger, OnBehalfOfRequest, RefreshTokenRequest, SilentFlowRequest } from "@azure/msal-common"; import { NodeConfigurationAuthError } from "../error/NodeConfigurationAuthError"; import { TokenCache } from "../cache/TokenCache"; export interface IConfidentialClientApplication { getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>; acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>; acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>; acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult>; acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult>; acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult>; getTokenCache(): TokenCache; getLogger(): Logger; setLogger(logger: Logger): void; } export const stubbedConfidentialClientApplication: IConfidentialClientApplication = { getAuthCodeUrl: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenByCode: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenSilent: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenByRefreshToken: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenByClientCredential: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenOnBehalfOf: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, getTokenCache: () => { throw NodeConfigurationAuthError.createStubTokenCacheCalledError(); }, getLogger: () => { throw NodeConfigurationAuthError.createStubPcaInstanceCalledError(); }, setLogger: () => { throw NodeConfigurationAuthError.createStubPcaInstanceCalledError(); } };
Add authcode, silent and refreshtoken flows to CCA
Add authcode, silent and refreshtoken flows to CCA
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -3,20 +3,48 @@ * Licensed under the MIT License. */ -import { AuthenticationResult, ClientCredentialRequest, OnBehalfOfRequest } from "@azure/msal-common"; +import { AuthenticationResult, AuthorizationCodeRequest, AuthorizationUrlRequest, ClientCredentialRequest, Logger, OnBehalfOfRequest, RefreshTokenRequest, SilentFlowRequest } from "@azure/msal-common"; import { NodeConfigurationAuthError } from "../error/NodeConfigurationAuthError"; - +import { TokenCache } from "../cache/TokenCache"; export interface IConfidentialClientApplication { + getAuthCodeUrl(request: AuthorizationUrlRequest): Promise<string>; + acquireTokenByCode(request: AuthorizationCodeRequest): Promise<AuthenticationResult>; + acquireTokenSilent(request: SilentFlowRequest): Promise<AuthenticationResult>; + acquireTokenByRefreshToken(request: RefreshTokenRequest): Promise<AuthenticationResult>; acquireTokenByClientCredential(request: ClientCredentialRequest): Promise<AuthenticationResult>; acquireTokenOnBehalfOf(request: OnBehalfOfRequest): Promise<AuthenticationResult>; + getTokenCache(): TokenCache; + getLogger(): Logger; + setLogger(logger: Logger): void; } export const stubbedConfidentialClientApplication: IConfidentialClientApplication = { + getAuthCodeUrl: () => { + return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); + }, + acquireTokenByCode: () => { + return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); + }, + acquireTokenSilent: () => { + return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); + }, + acquireTokenByRefreshToken: () => { + return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); + }, acquireTokenByClientCredential: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); }, acquireTokenOnBehalfOf: () => { return Promise.reject(NodeConfigurationAuthError.createStubPcaInstanceCalledError); + }, + getTokenCache: () => { + throw NodeConfigurationAuthError.createStubTokenCacheCalledError(); + }, + getLogger: () => { + throw NodeConfigurationAuthError.createStubPcaInstanceCalledError(); + }, + setLogger: () => { + throw NodeConfigurationAuthError.createStubPcaInstanceCalledError(); } };
4ed3b4514d74b7488c7fbf5e5bd2118193f62171
src/newtab/components/WeatherCard/ForecastItem/styles.ts
src/newtab/components/WeatherCard/ForecastItem/styles.ts
import styled from 'styled-components'; import opacity from '../../../../shared/defaults/opacity'; import typography from '../../../../shared/mixins/typography'; import images from '../../../../shared/mixins/images'; export const StyledForecastItem = styled.div` display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-left: 16px; padding-top: 8px; padding-bottom: 8px; ${typography.robotoRegular()}; color: rgba(0, 0, 0, ${opacity.light.secondaryText}); `; export const InfoContainer = styled.div` display: flex; align-items: center; justify-content: space-between; margin-right: 16px; `; export interface WeatherIconProps { src: string; } export const WeatherIcon = styled.div` width: 24px; height: 24px; display: flex; margin-right: 32px; ${images.center('24px', 'auto')}; background-image: url(${({ src }: WeatherIconProps) => src}); `; export const TempContainer = styled.div` display: flex; justify-self: right; `; export interface TempProps { night?: boolean; } export const Temp = styled.div` color: rgba( 0, 0, 0, ${({ night }: TempProps) => (night ? opacity.light.secondaryText : opacity.light.primaryText)} ); `;
import styled from 'styled-components'; import opacity from '../../../../shared/defaults/opacity'; import typography from '../../../../shared/mixins/typography'; import images from '../../../../shared/mixins/images'; export const StyledForecastItem = styled.div` display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-left: 16px; padding-top: 8px; padding-bottom: 8px; ${typography.robotoRegular()}; color: rgba(0, 0, 0, ${opacity.light.secondaryText}); `; export const InfoContainer = styled.div` display: flex; align-items: center; justify-content: space-between; margin-right: 16px; `; export interface WeatherIconProps { src: string; } export const WeatherIcon = styled.div` width: 24px; height: 24px; display: flex; margin-right: 16px; ${images.center('24px', 'auto')}; background-image: url(${({ src }: WeatherIconProps) => src}); `; export const TempContainer = styled.div` width: 64px; text-align: right; white-space: nowrap; `; export interface TempProps { night?: boolean; } export const Temp = styled.span` color: rgba( 0, 0, 0, ${({ night }: TempProps) => (night ? opacity.light.secondaryText : opacity.light.primaryText)} ); `;
Change weather icon position in forecast
:lipstick: Change weather icon position in forecast
TypeScript
apache-2.0
Nersent/Wexond,Nersent/Wexond
--- +++ @@ -32,22 +32,23 @@ width: 24px; height: 24px; display: flex; - margin-right: 32px; + margin-right: 16px; ${images.center('24px', 'auto')}; background-image: url(${({ src }: WeatherIconProps) => src}); `; export const TempContainer = styled.div` - display: flex; - justify-self: right; + width: 64px; + text-align: right; + white-space: nowrap; `; export interface TempProps { night?: boolean; } -export const Temp = styled.div` +export const Temp = styled.span` color: rgba( 0, 0,
38fc8a00fe4dfa7d2e47da48fe98633e372753e8
src/server/app.ts
src/server/app.ts
/// <reference path='../../typings/express/express.d.ts' /> import express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.use(express.static('public')); var server = app.listen(1949, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
/// <reference path='../../typings/express/express.d.ts' /> import express = require('express'); var STATIC_PATH = '/static'; var PORT = 1949; var app = express(); app.get('/', function (req, res) { res.send( 'Example app at: ' + 'localhost:' + PORT + STATIC_PATH + '/index.html'); }); app.use(STATIC_PATH, express.static(__dirname + '/../public')); // app.use(express.static('public')); var server = app.listen(PORT, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); console.log( 'Example app at: ' + 'localhost:' + port + STATIC_PATH + '/index.html'); });
Update express server. Better log and hello world.
Update express server. Better log and hello world.
TypeScript
mit
ku-kueihsi/dummy_react,ku-kueihsi/dummy_react,ku-kueihsi/dummy_react
--- +++ @@ -1,15 +1,23 @@ /// <reference path='../../typings/express/express.d.ts' /> import express = require('express'); + +var STATIC_PATH = '/static'; +var PORT = 1949; + var app = express(); app.get('/', function (req, res) { - res.send('Hello World!'); + res.send( + 'Example app at: ' + 'localhost:' + PORT + STATIC_PATH + '/index.html'); }); -app.use(express.static('public')); -var server = app.listen(1949, function () { +app.use(STATIC_PATH, express.static(__dirname + '/../public')); +// app.use(express.static('public')); +var server = app.listen(PORT, function () { var host = server.address().address; var port = server.address().port; - + console.log('Example app listening at http://%s:%s', host, port); + console.log( + 'Example app at: ' + 'localhost:' + port + STATIC_PATH + '/index.html'); });
aa3482633b2af29642343f2c890a7363366637ff
mobile/ios/simulator/ios-simulator-application-manager.ts
mobile/ios/simulator/ios-simulator-application-manager.ts
///<reference path="../../../.d.ts"/> "use strict"; import {ApplicationManagerBase} from "../../application-manager-base"; import Future = require("fibers/future"); export class IOSSimulatorApplicationManager extends ApplicationManagerBase implements Mobile.IDeviceApplicationManager { constructor(private iosSim: any, private identifier: string) { super(); } public getInstalledApplications(): IFuture<string[]> { return Future.fromResult(this.iosSim.getInstalledApplications(this.identifier)); } public installApplication(packageFilePath: string): IFuture<void> { return this.iosSim.installApplication(this.identifier, packageFilePath); } public uninstallApplication(appIdentifier: string): IFuture<void> { return this.iosSim.uninstallApplication(this.identifier, appIdentifier); } public startApplication(appIdentifier: string): IFuture<void> { return this.iosSim.startApplication(this.identifier, appIdentifier); } public stopApplication(cfBundleExecutable: string): IFuture<void> { return this.iosSim.stopApplication(this.identifier, cfBundleExecutable); } public canStartApplication(): boolean { return true; } }
///<reference path="../../../.d.ts"/> "use strict"; import {ApplicationManagerBase} from "../../application-manager-base"; import Future = require("fibers/future"); export class IOSSimulatorApplicationManager extends ApplicationManagerBase implements Mobile.IDeviceApplicationManager { constructor(private iosSim: any, private identifier: string, private $options: ICommonOptions) { super(); } private deviceLoggingStarted = false; public getInstalledApplications(): IFuture<string[]> { return Future.fromResult(this.iosSim.getInstalledApplications(this.identifier)); } public installApplication(packageFilePath: string): IFuture<void> { return this.iosSim.installApplication(this.identifier, packageFilePath); } public uninstallApplication(appIdentifier: string): IFuture<void> { return this.iosSim.uninstallApplication(this.identifier, appIdentifier); } public startApplication(appIdentifier: string): IFuture<void> { return (() => { let launchResult = this.iosSim.startApplication(this.identifier, appIdentifier).wait(); if (!this.$options.justlaunch && !this.deviceLoggingStarted) { this.deviceLoggingStarted = true; this.iosSim.printDeviceLog(this.identifier, launchResult); } }).future<void>()(); } public stopApplication(cfBundleExecutable: string): IFuture<void> { return this.iosSim.stopApplication(this.identifier, cfBundleExecutable); } public canStartApplication(): boolean { return true; } }
Print iOS Simulator device logs
Print iOS Simulator device logs When using `tns run ios` and `tns livesync ios` for iOS Simulator, we exit the process immediately instead of printing device logs. Call the printDeviceLogs method from iOSSimPortable that will fix the issue.
TypeScript
apache-2.0
telerik/mobile-cli-lib,telerik/mobile-cli-lib
--- +++ @@ -6,9 +6,12 @@ export class IOSSimulatorApplicationManager extends ApplicationManagerBase implements Mobile.IDeviceApplicationManager { constructor(private iosSim: any, - private identifier: string) { + private identifier: string, + private $options: ICommonOptions) { super(); } + + private deviceLoggingStarted = false; public getInstalledApplications(): IFuture<string[]> { return Future.fromResult(this.iosSim.getInstalledApplications(this.identifier)); @@ -23,7 +26,14 @@ } public startApplication(appIdentifier: string): IFuture<void> { - return this.iosSim.startApplication(this.identifier, appIdentifier); + return (() => { + let launchResult = this.iosSim.startApplication(this.identifier, appIdentifier).wait(); + if (!this.$options.justlaunch && !this.deviceLoggingStarted) { + this.deviceLoggingStarted = true; + this.iosSim.printDeviceLog(this.identifier, launchResult); + } + + }).future<void>()(); } public stopApplication(cfBundleExecutable: string): IFuture<void> {
51094e0542c73d073c1c00329ce48332817c6ff6
packages/reg-keygen-git-hash-plugin/src/git-cmd-client.ts
packages/reg-keygen-git-hash-plugin/src/git-cmd-client.ts
import { execSync } from "child_process"; export class GitCmdClient { currentName() { return execSync("git branch | grep \"^\\*\" | cut -b 3-", { encoding: "utf8" }); } revParse(currentName: string) { return execSync(`git rev-parse ${currentName}`, { encoding: "utf8" }); } showBranch() { return execSync("git show-branch -a --sha1-name", { encoding: "utf8" }); } logFirstParent() { return execSync("git log -n 1000 --oneline --first-parent", { encoding: "utf8" }); } logGraph() { return execSync("git log -n 1000 --graph --pretty=format:\"%h %p\"", { encoding: "utf8" }); } }
import { execSync } from "child_process"; export class GitCmdClient { currentName() { return execSync("git branch | grep \"^\\*\" | cut -b 3-", { encoding: "utf8" }); } revParse(currentName: string) { return execSync(`git rev-parse ${currentName}`, { encoding: "utf8" }); } showBranch() { return execSync("git show-branch -a --sha1-name", { encoding: "utf8" }); } logFirstParent() { // TODO need review. // the --first-parent option sometimes hides base hash candidates,,, is it correct? // return execSync("git log -n 1000 --oneline --first-parent", { encoding: "utf8" }); return execSync("git log -n 1000 --oneline", { encoding: "utf8" }); } logGraph() { return execSync("git log -n 1000 --graph --pretty=format:\"%h %p\"", { encoding: "utf8" }); } }
Fix cmd and todo comment
Fix cmd and todo comment
TypeScript
mit
reg-viz/reg-suit,reg-viz/reg-suit,reg-viz/reg-suit,reg-viz/reg-suit
--- +++ @@ -15,7 +15,10 @@ } logFirstParent() { - return execSync("git log -n 1000 --oneline --first-parent", { encoding: "utf8" }); + // TODO need review. + // the --first-parent option sometimes hides base hash candidates,,, is it correct? + // return execSync("git log -n 1000 --oneline --first-parent", { encoding: "utf8" }); + return execSync("git log -n 1000 --oneline", { encoding: "utf8" }); } logGraph() {
808f01f528291852ce8ffe2d0b83e0104da3174a
src/extension.ts
src/extension.ts
import { commands } from 'vscode'; import * as subwordNavigation from './commands'; export function activate() { commands.registerTextEditorCommand( 'subwordNavigation.cursorSubwordLeft', subwordNavigation.cursorSubwordLeft); commands.registerTextEditorCommand( 'subwordNavigation.cursorSubwordRight', subwordNavigation.cursorSubwordRight); commands.registerTextEditorCommand( 'subwordNavigation.cursorSubwordLeftSelect', subwordNavigation.cursorSubwordLeftSelect); commands.registerTextEditorCommand( 'subwordNavigation.cursorSubwordRightSelect', subwordNavigation.cursorSubwordRightSelect); commands.registerTextEditorCommand( 'subwordNavigation.deleteSubwordLeft', subwordNavigation.deleteSubwordLeft); commands.registerTextEditorCommand( 'subwordNavigation.deleteSubwordRight', subwordNavigation.deleteSubwordRight); }
import { commands, window } from 'vscode'; import * as subwordNavigation from './commands'; export function activate() { commands.registerCommand( 'subwordNavigation.cursorSubwordLeft', () => subwordNavigation.cursorSubwordLeft(window.activeTextEditor)); commands.registerCommand( 'subwordNavigation.cursorSubwordRight', () => subwordNavigation.cursorSubwordRight(window.activeTextEditor)); commands.registerCommand( 'subwordNavigation.cursorSubwordLeftSelect', () => subwordNavigation.cursorSubwordLeftSelect(window.activeTextEditor)); commands.registerCommand( 'subwordNavigation.cursorSubwordRightSelect', () => subwordNavigation.cursorSubwordRightSelect(window.activeTextEditor)); commands.registerCommand( 'subwordNavigation.deleteSubwordLeft', () => subwordNavigation.deleteSubwordLeft(window.activeTextEditor)); commands.registerCommand( 'subwordNavigation.deleteSubwordRight', () => subwordNavigation.deleteSubwordRight(window.activeTextEditor)); }
Stop navigation needlessly entering editor history
Stop navigation needlessly entering editor history
TypeScript
mit
ow--/vscode-subword-navigation
--- +++ @@ -1,28 +1,28 @@ -import { commands } from 'vscode'; +import { commands, window } from 'vscode'; import * as subwordNavigation from './commands'; export function activate() { - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.cursorSubwordLeft', - subwordNavigation.cursorSubwordLeft); + () => subwordNavigation.cursorSubwordLeft(window.activeTextEditor)); - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.cursorSubwordRight', - subwordNavigation.cursorSubwordRight); + () => subwordNavigation.cursorSubwordRight(window.activeTextEditor)); - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.cursorSubwordLeftSelect', - subwordNavigation.cursorSubwordLeftSelect); + () => subwordNavigation.cursorSubwordLeftSelect(window.activeTextEditor)); - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.cursorSubwordRightSelect', - subwordNavigation.cursorSubwordRightSelect); + () => subwordNavigation.cursorSubwordRightSelect(window.activeTextEditor)); - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.deleteSubwordLeft', - subwordNavigation.deleteSubwordLeft); + () => subwordNavigation.deleteSubwordLeft(window.activeTextEditor)); - commands.registerTextEditorCommand( + commands.registerCommand( 'subwordNavigation.deleteSubwordRight', - subwordNavigation.deleteSubwordRight); + () => subwordNavigation.deleteSubwordRight(window.activeTextEditor)); }
5a15e92f268cff9c0a823f4d583c2b2b95f7d091
src/v2/components/AdvancedSearch/components/AdvancedSearchFilter/components/FieldsFilter/index.tsx
src/v2/components/AdvancedSearch/components/AdvancedSearchFilter/components/FieldsFilter/index.tsx
import React from 'react' import { FilterContainer, FilterProps, CategoryLabel, } from 'v2/components/AdvancedSearch/components/AdvancedSearchFilter' import { FilterOption } from 'v2/components/AdvancedSearch/components/AdvancedSearchFilter/components/FilterOption' import { FieldsEnum } from '__generated__/globalTypes' export const FieldsFilter: React.FC<FilterProps> = ({ currentFilters, toggleFilter, clearAndSetAll, currentDisabledFilters, }) => { const updateProps = { field: 'fields' as any, toggleFilter, currentDisabledFilters, } const typedCurrentFilter = currentFilters as FieldsEnum[] const defaultSelected = !typedCurrentFilter || typedCurrentFilter?.length === 0 || typedCurrentFilter?.includes(FieldsEnum.ALL) return ( <FilterContainer> <CategoryLabel>Fields</CategoryLabel> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.ALL} {...updateProps} toggleFilter={clearAndSetAll} active={defaultSelected} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.NAME} {...updateProps} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.DESCRIPTION} {...updateProps} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.DOMAIN} {...updateProps} /> </FilterContainer> ) }
import React from 'react' import { FilterContainer, FilterProps, CategoryLabel, } from 'v2/components/AdvancedSearch/components/AdvancedSearchFilter' import { FilterOption } from 'v2/components/AdvancedSearch/components/AdvancedSearchFilter/components/FilterOption' import { FieldsEnum } from '__generated__/globalTypes' export const FieldsFilter: React.FC<FilterProps> = ({ currentFilters, toggleFilter, clearAndSetAll, currentDisabledFilters, }) => { const updateProps = { field: 'fields' as any, toggleFilter, currentDisabledFilters, } const typedCurrentFilter = currentFilters as FieldsEnum[] const defaultSelected = !typedCurrentFilter || typedCurrentFilter?.length === 0 || typedCurrentFilter?.includes(FieldsEnum.ALL) return ( <FilterContainer> <CategoryLabel>Fields</CategoryLabel> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.ALL} {...updateProps} toggleFilter={clearAndSetAll} active={defaultSelected} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.NAME} {...updateProps} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.DESCRIPTION} {...updateProps} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.CONTENT} {...updateProps} /> <FilterOption currentFilters={currentFilters} filter={FieldsEnum.DOMAIN} {...updateProps} /> </FilterContainer> ) }
Add content field to filters
Add content field to filters
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -47,6 +47,11 @@ /> <FilterOption currentFilters={currentFilters} + filter={FieldsEnum.CONTENT} + {...updateProps} + /> + <FilterOption + currentFilters={currentFilters} filter={FieldsEnum.DOMAIN} {...updateProps} />
d2af2581556b032e2954ea0562cf0e0458bbdd17
src/utils/get-link.ts
src/utils/get-link.ts
// import from npm import * as Map from "es6-map"; import { assignIn } from "lodash"; // declare an interface for the object that is // used to describe each link and stored in the // map interface LinkState { hasLoaded: boolean; wasRejected: boolean; error?: any; link: HTMLLinkElement; } /** * map for link names against utility objects * @type {Map<string, LinkState>} */ const loadedLinks = new Map<string, LinkState>(); /** * Get a style or other linked resource from a remote location. * @param name {string} - The name of the resource to be retrieved. * @param url {string} - The URL/location of the resource to be retrieved. */ export function getLink(url: string, name: string) { if (!loadedLinks.has(name)) { const link: HTMLLinkElement = document.createElement("link"); const body = document.getElementsByTagName("body")[0]; assignIn(link, { href: url, rel: "stylesheet", type: "text/css", }); body.appendChild(link); const linkObject: LinkState = { hasLoaded: false, link, wasRejected: false, }; loadedLinks.set(name, linkObject); } return loadedLinks.get(name); } // make the "getLink" method the default export export default getLink;
// import from npm import * as Map from "es6-map"; import { assignIn } from "lodash"; // declare an interface for the object that is // used to describe each link and stored in the // map interface LinkState { hasLoaded: boolean; wasRejected: boolean; error?: any; link: HTMLLinkElement; } /** * map for link names against utility objects * @type {Map<string, LinkState>} */ const loadedLinks = new Map<string, LinkState>(); /** * Get a style or other linked resource from a remote location. * @param name {string} - The name of the resource to be retrieved. * @param url {string} - The URL/location of the resource to be retrieved. */ export function getLink(url: string, name: string) { if (!loadedLinks.has(name) && !document.querySelector(`link[href="${url}"]`)) { const link: HTMLLinkElement = document.createElement("link"); const body = document.getElementsByTagName("body")[0]; assignIn(link, { href: url, rel: "stylesheet", type: "text/css", }); body.appendChild(link); const linkObject: LinkState = { hasLoaded: false, link, wasRejected: false, }; loadedLinks.set(name, linkObject); } return loadedLinks.get(name); } // make the "getLink" method the default export export default getLink;
Add a check for existing stylesheet in DOM in getLink method.
Add a check for existing stylesheet in DOM in getLink method.
TypeScript
mit
Josh-ES/react-here-maps,Josh-ES/react-here-maps
--- +++ @@ -24,7 +24,7 @@ * @param url {string} - The URL/location of the resource to be retrieved. */ export function getLink(url: string, name: string) { - if (!loadedLinks.has(name)) { + if (!loadedLinks.has(name) && !document.querySelector(`link[href="${url}"]`)) { const link: HTMLLinkElement = document.createElement("link"); const body = document.getElementsByTagName("body")[0];