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 |
|---|---|---|---|---|---|---|---|---|---|---|
3e6f7ab0f1cd7054c354699ad4594e5c0538d783 | app/src/lib/stores/helpers/onboarding-tutorial.ts | app/src/lib/stores/helpers/onboarding-tutorial.ts | export class OnboardingTutorial {
public constructor() {
this.skipInstallEditor = false
this.skipCreatePR = false
}
public getCurrentStep() {
// call all other methods to check where we're at
}
if (this.skipInstallEditor) {
private async isEditorInstalled(): Promise<boolean> {
return true
}
return false
}
private isBranchCreated(): boolean {
return false
}
private isReadmeEdited(): boolean {
return false
}
private hasCommit(): boolean {
return false
}
private commitPushed(): boolean {
return false
}
private pullRequestCreated(): boolean {
if (this.skipCreatePR) {
return true
}
return false
}
public skipEditorInstall() {
this.skipEditorInstall = true
}
public skipCreatePR() {
this.skipCreatePR = true
}
}
| export class OnboardingTutorial {
public constructor({ resolveEditor, getEditor }) {
this.skipInstallEditor = false
this.skipCreatePR = false
this.resolveEditor = resolveEditor
this.getEditor = getEditor
}
public getCurrentStep() {
// call all other methods to check where we're at
}
private async isEditorInstalled(): Promise<boolean> {
if (this.skipInstallEditor || this.getEditor()) {
return true
} else {
await this.resolveEditor()
return !!this.getEditor()
}
}
private isBranchCreated(): boolean {
return false
}
private isReadmeEdited(): boolean {
return false
}
private hasCommit(): boolean {
return false
}
private commitPushed(): boolean {
return false
}
private pullRequestCreated(): boolean {
if (this.skipCreatePR) {
return true
}
return false
}
public skipEditorInstall() {
this.skipEditorInstall = true
}
public skipCreatePR() {
this.skipCreatePR = true
}
}
| Check if editor is installed | Check if editor is installed
| TypeScript | mit | kactus-io/kactus,say25/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,say25/desktop,desktop/desktop,desktop/desktop | ---
+++
@@ -1,18 +1,22 @@
export class OnboardingTutorial {
- public constructor() {
+ public constructor({ resolveEditor, getEditor }) {
this.skipInstallEditor = false
this.skipCreatePR = false
+ this.resolveEditor = resolveEditor
+ this.getEditor = getEditor
}
public getCurrentStep() {
// call all other methods to check where we're at
}
- if (this.skipInstallEditor) {
private async isEditorInstalled(): Promise<boolean> {
+ if (this.skipInstallEditor || this.getEditor()) {
return true
+ } else {
+ await this.resolveEditor()
+ return !!this.getEditor()
}
- return false
}
private isBranchCreated(): boolean { |
09ca7a4eafae1fda2e6929697ee792cf215afb00 | src/v2/components/AuthForm/components/CloseButton/index.tsx | src/v2/components/AuthForm/components/CloseButton/index.tsx | import React from 'react'
import styled from 'styled-components'
import Icons from 'v2/components/UI/Icons'
const Container = styled.a`
display: block;
position: absolute;
top: 0;
right: 0;
padding: ${x => x.theme.space[6]};
`
interface Props {
onClose?: () => void
}
const CloseButton: React.FC<Props> = ({ onClose }) => {
const onClick = onClose ? onClose : () => (location.href = '/')
return (
<Container onClick={onClick}>
<Icons name="X" color="gray.base" />
</Container>
)
}
export default CloseButton
| import React from 'react'
import styled from 'styled-components'
import Icons from 'v2/components/UI/Icons'
const Container = styled.a`
display: block;
position: absolute;
top: 0;
right: 0;
padding: ${x => x.theme.space[6]};
cursor: pointer;
`
interface Props {
onClose?: () => void
}
const CloseButton: React.FC<Props> = ({ onClose }) => {
const onClick = onClose ? onClose : () => (location.href = '/')
return (
<Container onClick={onClick}>
<Icons name="X" color="gray.base" />
</Container>
)
}
export default CloseButton
| Add pointer back login close button | Add pointer back login close button
| TypeScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -9,6 +9,7 @@
top: 0;
right: 0;
padding: ${x => x.theme.space[6]};
+ cursor: pointer;
`
interface Props { |
f23ff7fc541991ceb63b73ddbf67dc3d04a2cb38 | packages/components/components/modalTwo/useModalState.ts | packages/components/components/modalTwo/useModalState.ts | import { useState } from 'react';
import { generateUID } from '../../helpers';
import { useControlled } from '../../hooks';
const useModalState = (options?: { open?: boolean; onClose?: () => void; onExit?: () => void }) => {
const { open: controlledOpen, onClose, onExit } = options || {};
const [key, setKey] = useState(() => generateUID());
const [open, setOpen] = useControlled(controlledOpen);
const handleClose = () => {
setOpen(false);
onClose?.();
};
const handleExit = () => {
setKey(generateUID());
onExit?.();
};
const modalProps = {
key,
open,
onClose: handleClose,
onExit: handleExit,
};
return [modalProps, setOpen] as const;
};
export default useModalState;
| import { useState } from 'react';
import { generateUID } from '../../helpers';
import { useControlled } from '../../hooks';
const useModalState = (options?: { open?: boolean; onClose?: () => void; onExit?: () => void }) => {
const { open: controlledOpen, onClose, onExit } = options || {};
const [key, setKey] = useState(() => generateUID());
const [open, setOpen] = useControlled(controlledOpen);
const [render, setRender] = useState(open);
const handleSetOpen = (newValue: boolean) => {
if (newValue) {
setOpen(true);
setRender(true);
} else {
setOpen(false);
}
};
const handleClose = () => {
handleSetOpen(false);
onClose?.();
};
const handleExit = () => {
setRender(false);
setKey(generateUID());
onExit?.();
};
const modalProps = {
key,
open,
onClose: handleClose,
onExit: handleExit,
};
return [modalProps, handleSetOpen, render] as const;
};
export default useModalState;
| Add mechanism to conditionally render modal | Add mechanism to conditionally render modal
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -7,15 +7,25 @@
const { open: controlledOpen, onClose, onExit } = options || {};
const [key, setKey] = useState(() => generateUID());
+ const [open, setOpen] = useControlled(controlledOpen);
+ const [render, setRender] = useState(open);
- const [open, setOpen] = useControlled(controlledOpen);
+ const handleSetOpen = (newValue: boolean) => {
+ if (newValue) {
+ setOpen(true);
+ setRender(true);
+ } else {
+ setOpen(false);
+ }
+ };
const handleClose = () => {
- setOpen(false);
+ handleSetOpen(false);
onClose?.();
};
const handleExit = () => {
+ setRender(false);
setKey(generateUID());
onExit?.();
};
@@ -27,7 +37,7 @@
onExit: handleExit,
};
- return [modalProps, setOpen] as const;
+ return [modalProps, handleSetOpen, render] as const;
};
export default useModalState; |
56a0bee42d77cfba3822bad1a9f11bc9677e9471 | ng-app/src/modules/app/components/software-editor-view/software-editor-view.component.ts | ng-app/src/modules/app/components/software-editor-view/software-editor-view.component.ts | import { Component, OnInit } from '@angular/core';
import { ControlGroup } from '../../core/controls/control-group';
import { ControlsService } from '../../services/controls.service';
@Component({
templateUrl: 'software-editor-view.component.html',
styleUrls: ['software-editor-view.component.css']
})
export class SoftwareEditorViewComponent implements OnInit {
controlGroups: ControlGroup[] = [];
constructor(private controlsService: ControlsService) {}
ngOnInit(): void {
this.fetchGroups();
}
/**
* Fetches groups from the ControlsService.
*/
private fetchGroups() {
this.controlsService.getGroups()
.subscribe((groups) => this.controlGroups = groups, (e) => {
console.error('Error occurred while retrieving of control groups.', e);
});
}
}
| import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/of';
import {ProjectService} from '../../services/project.service';
import {Project} from '../../core/projects/project';
import {ControlGroup} from '../../core/controls/control-group';
import {ControlsService} from '../../services/controls.service';
@Component({
templateUrl: 'software-editor-view.component.html',
styleUrls: ['software-editor-view.component.css']
})
export class SoftwareEditorViewComponent implements OnInit {
project: Project;
controlGroups: ControlGroup[] = [];
constructor(private route: ActivatedRoute, private projectService: ProjectService,
private controlsService: ControlsService) {
}
ngOnInit(): void {
this.fetchGroups();
this.route.params
.switchMap((params: Params) => this.projectService.getProject(params['id']))
.subscribe((project: Project) => this.project = project, (e) => {
console.error('Error occurred while retrieving of project.', e);
});
}
/**
* Fetches groups from the ControlsService.
*/
private fetchGroups() {
this.controlsService.getGroups()
.subscribe((groups) => this.controlGroups = groups, (e) => {
console.error('Error occurred while retrieving of control groups.', e);
});
}
}
| Load project by id for Project Software view. | [Client] Load project by id for Project Software view.
| TypeScript | mit | azasypkin/frunze,azasypkin/frunze,azasypkin/frunze,azasypkin/frunze | ---
+++
@@ -1,19 +1,36 @@
-import { Component, OnInit } from '@angular/core';
+import {Component, OnInit} from '@angular/core';
+import {ActivatedRoute, Params} from '@angular/router';
-import { ControlGroup } from '../../core/controls/control-group';
-import { ControlsService } from '../../services/controls.service';
+import 'rxjs/add/operator/switchMap';
+import 'rxjs/add/observable/of';
+
+import {ProjectService} from '../../services/project.service';
+
+import {Project} from '../../core/projects/project';
+
+import {ControlGroup} from '../../core/controls/control-group';
+import {ControlsService} from '../../services/controls.service';
@Component({
templateUrl: 'software-editor-view.component.html',
styleUrls: ['software-editor-view.component.css']
})
export class SoftwareEditorViewComponent implements OnInit {
+ project: Project;
controlGroups: ControlGroup[] = [];
- constructor(private controlsService: ControlsService) {}
+ constructor(private route: ActivatedRoute, private projectService: ProjectService,
+ private controlsService: ControlsService) {
+ }
ngOnInit(): void {
this.fetchGroups();
+
+ this.route.params
+ .switchMap((params: Params) => this.projectService.getProject(params['id']))
+ .subscribe((project: Project) => this.project = project, (e) => {
+ console.error('Error occurred while retrieving of project.', e);
+ });
}
/**
@@ -21,8 +38,8 @@
*/
private fetchGroups() {
this.controlsService.getGroups()
- .subscribe((groups) => this.controlGroups = groups, (e) => {
- console.error('Error occurred while retrieving of control groups.', e);
- });
+ .subscribe((groups) => this.controlGroups = groups, (e) => {
+ console.error('Error occurred while retrieving of control groups.', e);
+ });
}
} |
09e45ca3a968df96d06a5428a9e4e09c92f0f762 | src/types.ts | src/types.ts | /*!
* This source file is part of the EdgeDB open source project.
*
* Copyright 2019-present MagicStack Inc. and the EdgeDB authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export type NamedTuple<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly length: number;
} & Iterable<any>;
export type Tuple<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly length: number;
} & Iterable<any>;
export type ObjectShape<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly id: string;
};
| /*!
* This source file is part of the EdgeDB open source project.
*
* Copyright 2019-present MagicStack Inc. and the EdgeDB authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export type NamedTuple<T = any> = {
readonly [_: number]: any;
} & {
readonly length: number;
} & {readonly [K in keyof T]-?: T[K]} &
Iterable<any>;
export type Tuple<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly length: number;
} & Iterable<any>;
export type ObjectShape<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly id: string;
};
| Tweak the NamedTuple type to allow arbitrary number keys | Tweak the NamedTuple type to allow arbitrary number keys
| TypeScript | apache-2.0 | edgedb/edgedb-js,edgedb/edgedb-js | ---
+++
@@ -16,9 +16,12 @@
* limitations under the License.
*/
-export type NamedTuple<T = any> = {readonly [K in keyof T]-?: T[K]} & {
+export type NamedTuple<T = any> = {
+ readonly [_: number]: any;
+} & {
readonly length: number;
-} & Iterable<any>;
+} & {readonly [K in keyof T]-?: T[K]} &
+ Iterable<any>;
export type Tuple<T = any> = {readonly [K in keyof T]-?: T[K]} & {
readonly length: number; |
36d94d4491080e07514397448707326e35b307fb | src/AccordionItemHeading/AccordionItemHeading.tsx | src/AccordionItemHeading/AccordionItemHeading.tsx | import { default as classnames } from 'classnames';
import * as React from 'react';
import { UUID } from '../ItemContainer/ItemContainer';
type AccordionItemHeadingProps = React.HTMLAttributes<HTMLDivElement> & {
hideBodyClassName: string;
expanded: boolean;
uuid: UUID;
setExpanded(uuid: UUID, expanded: boolean): void;
};
type AccordionItemHeadingState = {};
export default class AccordionItemHeading extends React.Component<
AccordionItemHeadingProps,
AccordionItemHeadingState
> {
handleClick = (): void => {
const { uuid, expanded, setExpanded } = this.props;
setExpanded(uuid, !expanded);
};
handleKeyPress = (evt: React.KeyboardEvent<HTMLDivElement>): void => {
if (evt.charCode === 13 || evt.charCode === 32) {
evt.preventDefault();
this.handleClick();
}
};
render(): JSX.Element {
const {
className,
hideBodyClassName,
setExpanded,
expanded,
uuid,
...rest
} = this.props;
const id = `accordion__heading-${uuid}`;
const ariaControls = `accordion__panel-${uuid}`;
const role = 'button';
const titleClassName = classnames(className, {
[hideBodyClassName]: hideBodyClassName && !expanded,
});
return (
<div
id={id}
aria-expanded={expanded}
aria-controls={ariaControls}
className={titleClassName}
onClick={this.handleClick}
role="button"
tabIndex={0}
onKeyPress={this.handleKeyPress}
{...rest}
/>
);
}
}
| import { default as classnames } from 'classnames';
import * as React from 'react';
import { UUID } from '../ItemContainer/ItemContainer';
type AccordionItemHeadingProps = React.HTMLAttributes<HTMLDivElement> & {
hideBodyClassName: string;
expanded: boolean;
uuid: UUID;
setExpanded(uuid: UUID, expanded: boolean): void;
};
type AccordionItemHeadingState = {};
export default class AccordionItemHeading extends React.Component<
AccordionItemHeadingProps,
AccordionItemHeadingState
> {
handleClick = (): void => {
const { uuid, expanded, setExpanded } = this.props;
setExpanded(uuid, !expanded);
};
handleKeyPress = (evt: React.KeyboardEvent<HTMLDivElement>): void => {
if (evt.charCode === 13 || evt.charCode === 32) {
evt.preventDefault();
this.handleClick();
}
};
render(): JSX.Element {
const {
className,
hideBodyClassName,
setExpanded,
expanded,
uuid,
...rest
} = this.props;
const id = `accordion__heading-${uuid}`;
const ariaControls = `accordion__panel-${uuid}`;
const headingClassName = classnames(className, {
[hideBodyClassName]: hideBodyClassName && !expanded,
});
return (
<div
id={id}
aria-expanded={expanded}
aria-controls={ariaControls}
className={headingClassName}
onClick={this.handleClick}
role="button"
tabIndex={0}
onKeyPress={this.handleKeyPress}
{...rest}
/>
);
}
}
| Remove redundant constant and fix semantics 'title' -> 'heading' | Remove redundant constant and fix semantics 'title' -> 'heading'
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -40,8 +40,7 @@
const id = `accordion__heading-${uuid}`;
const ariaControls = `accordion__panel-${uuid}`;
- const role = 'button';
- const titleClassName = classnames(className, {
+ const headingClassName = classnames(className, {
[hideBodyClassName]: hideBodyClassName && !expanded,
});
@@ -50,7 +49,7 @@
id={id}
aria-expanded={expanded}
aria-controls={ariaControls}
- className={titleClassName}
+ className={headingClassName}
onClick={this.handleClick}
role="button"
tabIndex={0} |
5f5f91c3d030cf05bc6a884aae60a22e7349db3a | src/elements/Button.tsx | src/elements/Button.tsx | import * as React from 'react';
import * as classNames from 'classnames';
import {
Bulma,
removeStateProps, removeColorProps, removeFullWidthProps,
getStateModifiers, getColorModifiers, getFullWidthModifiers,
withHelpersModifiers,
} from './../bulma';
import { combineModifiers, getHTMLProps } from './../helpers';
export interface Button<T> extends
Bulma.Render, Bulma.State, Bulma.Color, Bulma.FullWidth,
React.HTMLProps<T> {
isLink?: boolean,
isOutlined?: boolean,
isInverted?: boolean,
}
export const Button: React.SFC<Button<HTMLButtonElement | HTMLAnchorElement>> = (props) => {
const className = classNames(
'button',
{
'is-link': props.isLink,
'is-outlined': props.isOutlined,
'is-inverted': props.isInverted,
...combineModifiers(props, getStateModifiers, getColorModifiers, getFullWidthModifiers)
},
props.className,
);
const { render, isLink, isOutlined, isInverted, ...rest } = props;
const HTMLProps = getHTMLProps(
rest,
removeStateProps,
removeColorProps,
removeFullWidthProps,
);
if (render) return render({ ...HTMLProps, className });
const anchor = (
<a {...HTMLProps} role='button' className={className} />
)
const button = (
<button {...HTMLProps} type={props.type || 'button'} className={className} />
)
return props.href ? anchor : button;
}
export default withHelpersModifiers(Button); | import * as React from 'react';
import * as classNames from 'classnames';
import {
Bulma,
removeStateProps, removeColorProps, removeFullWidthProps,
getStateModifiers, getColorModifiers, getFullWidthModifiers,
withHelpersModifiers,
} from './../bulma';
import { combineModifiers, getHTMLProps } from './../helpers';
export interface Button<T> extends
Bulma.Render, Bulma.State, Bulma.Color,
React.HTMLProps<T> {
isLink?: boolean,
isOutlined?: boolean,
isInverted?: boolean,
}
export const Button: React.SFC<Button<HTMLButtonElement | HTMLAnchorElement>> = (props) => {
const className = classNames(
'button',
{
'is-link': props.isLink,
'is-outlined': props.isOutlined,
'is-inverted': props.isInverted,
...combineModifiers(props, getStateModifiers, getColorModifiers, getFullWidthModifiers)
},
props.className,
);
const { render, isLink, isOutlined, isInverted, ...rest } = props;
const HTMLProps = getHTMLProps(
rest,
removeStateProps,
removeColorProps,
removeFullWidthProps,
);
if (render) return render({ ...HTMLProps, className });
const anchor = (
<a {...HTMLProps} role='button' className={className} />
)
const button = (
<button {...HTMLProps} type={props.type || 'button'} className={className} />
)
return props.href ? anchor : button;
}
export default withHelpersModifiers(Button); | Remove FullWidth Interface since this is a general modifier for all Bulma Components | Remove FullWidth Interface since this is a general modifier for all Bulma Components
| TypeScript | mit | AlgusDark/bloomer,AlgusDark/bloomer | ---
+++
@@ -10,7 +10,7 @@
import { combineModifiers, getHTMLProps } from './../helpers';
export interface Button<T> extends
- Bulma.Render, Bulma.State, Bulma.Color, Bulma.FullWidth,
+ Bulma.Render, Bulma.State, Bulma.Color,
React.HTMLProps<T> {
isLink?: boolean,
isOutlined?: boolean, |
04634ea4775ee34837031dabff835b705cc5e5c3 | client/Commands/Command.ts | client/Commands/Command.ts | import * as ko from "knockout";
import { Store } from "../Utility/Store";
import { LegacyCommandSettingsKeys } from "./LegacyCommandSettingsKeys";
export class Command {
public ShowOnActionBar: KnockoutObservable<boolean>;
public ToolTip: KnockoutComputed<string>;
public KeyBinding: string;
constructor(
public Id: string,
public Description: string,
public ActionBinding: () => any,
defaultKeyBinding: string,
public FontAwesomeIcon: string,
defaultShowOnActionBar = true,
public LockOnActionBar = false) {
this.ShowOnActionBar = ko.observable(defaultShowOnActionBar);
if (LockOnActionBar) {
this.ShowOnActionBar.subscribe(_ => {
this.ShowOnActionBar(true);
});
}
this.ToolTip = ko.pureComputed(() => `${this.Description} [${this.KeyBinding}]`);
const savedKeybinding = Store.Load<string>(Store.KeyBindings, this.Id);
const legacyKeybinding = LegacyCommandSettingsKeys[this.Id] && Store.Load<string>(Store.KeyBindings, LegacyCommandSettingsKeys[this.Id]);
this.KeyBinding = savedKeybinding || legacyKeybinding || defaultKeyBinding;
let showOnActionBarSetting = Store.Load<boolean>(Store.ActionBar, this.Description);
if (showOnActionBarSetting != null) {
this.ShowOnActionBar(showOnActionBarSetting);
}
}
}
| import * as ko from "knockout";
import _ = require("lodash");
import { Settings } from "../Settings/Settings";
import { Store } from "../Utility/Store";
import { CommandSetting } from "./CommandSetting";
import { LegacyCommandSettingsKeys } from "./LegacyCommandSettingsKeys";
export class Command {
public ShowOnActionBar: KnockoutObservable<boolean>;
public ToolTip: KnockoutComputed<string>;
public KeyBinding: string;
constructor(
public Id: string,
public Description: string,
public ActionBinding: () => any,
defaultKeyBinding: string,
public FontAwesomeIcon: string,
defaultShowOnActionBar = true,
public LockOnActionBar = false) {
this.ShowOnActionBar = ko.observable(defaultShowOnActionBar);
if (LockOnActionBar) {
this.ShowOnActionBar.subscribe(_ => {
this.ShowOnActionBar(true);
});
}
this.ToolTip = ko.pureComputed(() => `${this.Description} [${this.KeyBinding}]`);
const settings = Store.Load<Settings>(Store.User, "Settings");
const commandSetting = settings && _.find(settings.Commands, c => c.Name == this.Id);
const legacyKeybinding = LegacyCommandSettingsKeys[this.Id] && Store.Load<string>(Store.KeyBindings, LegacyCommandSettingsKeys[this.Id]);
this.KeyBinding = commandSetting.KeyBinding || legacyKeybinding || defaultKeyBinding;
let showOnActionBarSetting = Store.Load<boolean>(Store.ActionBar, this.Description);
if (showOnActionBarSetting != null) {
this.ShowOnActionBar(showOnActionBarSetting);
}
}
}
| Load command setting from Settings store | Load command setting from Settings store
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,6 +1,9 @@
import * as ko from "knockout";
+import _ = require("lodash");
+import { Settings } from "../Settings/Settings";
import { Store } from "../Utility/Store";
+import { CommandSetting } from "./CommandSetting";
import { LegacyCommandSettingsKeys } from "./LegacyCommandSettingsKeys";
export class Command {
@@ -24,10 +27,12 @@
this.ToolTip = ko.pureComputed(() => `${this.Description} [${this.KeyBinding}]`);
- const savedKeybinding = Store.Load<string>(Store.KeyBindings, this.Id);
+ const settings = Store.Load<Settings>(Store.User, "Settings");
+ const commandSetting = settings && _.find(settings.Commands, c => c.Name == this.Id);
+
const legacyKeybinding = LegacyCommandSettingsKeys[this.Id] && Store.Load<string>(Store.KeyBindings, LegacyCommandSettingsKeys[this.Id]);
- this.KeyBinding = savedKeybinding || legacyKeybinding || defaultKeyBinding;
+ this.KeyBinding = commandSetting.KeyBinding || legacyKeybinding || defaultKeyBinding;
let showOnActionBarSetting = Store.Load<boolean>(Store.ActionBar, this.Description);
if (showOnActionBarSetting != null) { |
db8511828ec094844d7e445a10ccbc9e0795b640 | src/components/artwork_filter/total_count.tsx | src/components/artwork_filter/total_count.tsx | import * as numeral from "numeral"
import * as React from "react"
import * as Relay from "react-relay"
import styled from "styled-components"
import { secondary } from "../../assets/fonts"
interface TotalCountProps extends RelayProps, React.HTMLProps<TotalCount> {
filter_artworks: any
}
export class TotalCount extends React.Component<TotalCountProps, null> {
render() {
const total = this.props.filter_artworks.counts.total
const s = total !== 1 ? "s" : ""
return (
<div className={this.props.className}>
{numeral(total).format("0,0")} Work{s}
</div>
)
}
}
const StyledTotalCount = styled(TotalCount)`
font-style: italic;
${secondary.style}
`
export default Relay.createContainer(StyledTotalCount, {
fragments: {
filter_artworks: () => Relay.QL`
fragment on FilterArtworks {
counts {
total
}
}
`,
},
})
interface RelayProps {
filter_artworks: {
counts: {
total: number | null
} | null
}
}
| import numeral from "numeral"
import * as React from "react"
import * as Relay from "react-relay"
import styled from "styled-components"
import { secondary } from "../../assets/fonts"
interface TotalCountProps extends RelayProps, React.HTMLProps<TotalCount> {
filter_artworks: any
}
export class TotalCount extends React.Component<TotalCountProps, null> {
render() {
const total = this.props.filter_artworks.counts.total
const s = total !== 1 ? "s" : ""
return (
<div className={this.props.className}>
{numeral(total).format("0,0")} Work{s}
</div>
)
}
}
const StyledTotalCount = styled(TotalCount)`
font-style: italic;
${secondary.style}
`
export default Relay.createContainer(StyledTotalCount, {
fragments: {
filter_artworks: () => Relay.QL`
fragment on FilterArtworks {
counts {
total
}
}
`,
},
})
interface RelayProps {
filter_artworks: {
counts: {
total: number | null
} | null
}
}
| Fix another 'TypeError: numeral is not a function' | Fix another 'TypeError: numeral is not a function'
| TypeScript | mit | xtina-starr/reaction,artsy/reaction-force,craigspaeth/reaction,craigspaeth/reaction,artsy/reaction,xtina-starr/reaction,craigspaeth/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction | ---
+++
@@ -1,4 +1,4 @@
-import * as numeral from "numeral"
+import numeral from "numeral"
import * as React from "react"
import * as Relay from "react-relay"
|
d2d437ea22c74e226e5dd489f4fdc24446a099d7 | src/nerdbank-streams/src/tests/DeferredTests.ts | src/nerdbank-streams/src/tests/DeferredTests.ts | import 'jasmine';
import { Deferred } from '../Deferred';
describe('Deferred', () => {
var deferred: Deferred<void>;
beforeEach(() => {
deferred = new Deferred<void>();
});
it('indicates completion', () => {
expect(deferred.isCompleted).toBe(false);
expect(deferred.isResolved).toBe(false);
expect(deferred.isRejected).toBe(false);
deferred.resolve();
expect(deferred.isCompleted).toBe(true);
expect(deferred.isResolved).toBe(true);
expect(deferred.isRejected).toBe(false);
});
it('indicates error', () => {
expect(deferred.isCompleted).toBe(false);
expect(deferred.error).toBeUndefined();
expect(deferred.isRejected).toBe(false);
expect(deferred.isResolved).toBe(false);
var e = new Error("hi")
deferred.reject(e);
expect(deferred.isCompleted).toBe(true);
expect(deferred.error).toBe(e);
expect(deferred.isRejected).toBe(true);
expect(deferred.isResolved).toBe(false);
});
});
| import 'jasmine';
import { Deferred } from '../Deferred';
describe('Deferred', () => {
var deferred: Deferred<void>;
beforeEach(() => {
deferred = new Deferred<void>();
});
it('indicates completion', () => {
expect(deferred.isCompleted).toBe(false);
expect(deferred.isResolved).toBe(false);
expect(deferred.isRejected).toBe(false);
deferred.resolve();
expect(deferred.isCompleted).toBe(true);
expect(deferred.isResolved).toBe(true);
expect(deferred.isRejected).toBe(false);
});
it('indicates error', async () => {
expect(deferred.isCompleted).toBe(false);
expect(deferred.error).toBeUndefined();
expect(deferred.isRejected).toBe(false);
expect(deferred.isResolved).toBe(false);
var e = new Error("hi");
deferred.reject(e);
expect(deferred.isCompleted).toBe(true);
expect(deferred.error).toBe(e);
expect(deferred.isRejected).toBe(true);
expect(deferred.isResolved).toBe(false);
// We must observe the rejected promise or else Jasmine will fail at the command line anyway.
try {
await deferred.promise;
}
catch { }
});
});
| Fix command line test failure | Fix command line test failure
| TypeScript | mit | AArnott/Nerdbank.FullDuplexStream | ---
+++
@@ -18,16 +18,22 @@
expect(deferred.isRejected).toBe(false);
});
- it('indicates error', () => {
+ it('indicates error', async () => {
expect(deferred.isCompleted).toBe(false);
expect(deferred.error).toBeUndefined();
expect(deferred.isRejected).toBe(false);
expect(deferred.isResolved).toBe(false);
- var e = new Error("hi")
+ var e = new Error("hi");
deferred.reject(e);
expect(deferred.isCompleted).toBe(true);
expect(deferred.error).toBe(e);
expect(deferred.isRejected).toBe(true);
expect(deferred.isResolved).toBe(false);
+
+ // We must observe the rejected promise or else Jasmine will fail at the command line anyway.
+ try {
+ await deferred.promise;
+ }
+ catch { }
});
}); |
efa12c7ccc91f644d227ab7666ce14cb18475dd3 | resources/assets/lib/scores-show/buttons.tsx | resources/assets/lib/scores-show/buttons.tsx | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import ScoreJson from 'interfaces/score-json';
import { route } from 'laroute';
import { PopupMenuPersistent } from 'popup-menu-persistent';
import * as React from 'react';
import { ReportReportable } from 'report-reportable';
import { canBeReported } from 'score-helper';
interface Props {
score: ScoreJson;
}
export default function Buttons(props: Props) {
return (
<div className='score-buttons'>
{props.score.replay && (
<a
className='btn-osu-big btn-osu-big--rounded'
data-turbolinks={false}
href={route('scores.download', { mode: props.score.mode, score: props.score.best_id })}
>
{osu.trans('users.show.extra.top_ranks.download_replay')}
</a>
)}
{canBeReported(props.score) && (
<div className='score-buttons__menu'>
<PopupMenuPersistent>
{() => (
<ReportReportable
baseKey='scores'
className='simple-menu__item'
reportableId={props.score.best_id?.toString() ?? ''}
reportableType={`score_best_${props.score.mode}`}
user={props.score.user}
/>
)}
</PopupMenuPersistent>
</div>
)}
</div>
);
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import ScoreJson from 'interfaces/score-json';
import { route } from 'laroute';
import { PopupMenuPersistent } from 'popup-menu-persistent';
import * as React from 'react';
import { ReportReportable } from 'report-reportable';
import { canBeReported } from 'score-helper';
interface Props {
score: ScoreJson;
}
export default function Buttons(props: Props) {
return (
<div className='score-buttons'>
{props.score.replay && (
<a
className='js-login-required--click btn-osu-big btn-osu-big--rounded'
data-turbolinks={false}
href={route('scores.download', { mode: props.score.mode, score: props.score.best_id })}
>
{osu.trans('users.show.extra.top_ranks.download_replay')}
</a>
)}
{canBeReported(props.score) && (
<div className='score-buttons__menu'>
<PopupMenuPersistent>
{() => (
<ReportReportable
baseKey='scores'
className='simple-menu__item'
reportableId={props.score.best_id?.toString() ?? ''}
reportableType={`score_best_${props.score.mode}`}
user={props.score.user}
/>
)}
</PopupMenuPersistent>
</div>
)}
</div>
);
}
| Handle login requirement for score replay download | Handle login requirement for score replay download
| TypeScript | agpl-3.0 | LiquidPL/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,LiquidPL/osu-web,ppy/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,nanaya/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web,ppy/osu-web,nanaya/osu-web | ---
+++
@@ -17,7 +17,7 @@
<div className='score-buttons'>
{props.score.replay && (
<a
- className='btn-osu-big btn-osu-big--rounded'
+ className='js-login-required--click btn-osu-big btn-osu-big--rounded'
data-turbolinks={false}
href={route('scores.download', { mode: props.score.mode, score: props.score.best_id })}
> |
75a704b88e4f122072f3b098284a0318349180c7 | tob-web/src/app/cred/timeline-cred.component.ts | tob-web/src/app/cred/timeline-cred.component.ts | import { Component, Input } from '@angular/core';
import { Model } from '../data-types';
@Component({
selector: 'timeline-cred',
templateUrl: '../../themes/_active/cred/timeline-cred.component.html',
})
export class TimelineCredComponent {
protected _cred: Model.Credential;
constructor() { }
get credential() {
return this._cred;
}
@Input() set credential(cred: Model.Credential) {
this._cred = cred;
}
get related_topic_name() {
//let topic = this._cred && this._cred.related_topics && this._cred.related_topics[0];
//if(topic && topic.names && topic.names.length) return topic.names[0].text;
return this._cred && this._cred.relatedPreferredName;
}
get topic_name() {
return this._cred && this._cred.topic && this._cred.topic.local_name.text;
//return this._cred && this._cred.names.length && this._cred.names[0].text;
}
}
| import { Component, Input } from '@angular/core';
import { Model } from '../data-types';
@Component({
selector: 'timeline-cred',
templateUrl: '../../themes/_active/cred/timeline-cred.component.html',
})
export class TimelineCredComponent {
protected _cred: Model.Credential;
constructor() { }
get credential() {
return this._cred;
}
@Input() set credential(cred: Model.Credential) {
this._cred = cred;
}
get related_topic_name() {
//let topic = this._cred && this._cred.related_topics && this._cred.related_topics[0];
//if(topic && topic.names && topic.names.length) return topic.names[0].text;
return this._cred && this._cred.relatedPreferredName;
}
get topic_name() {
return this._cred && this._cred.local_name && this._cred.local_name.text;
//return this._cred && this._cred.topic && this._cred.topic.local_name.text;
//return this._cred && this._cred.names.length && this._cred.names[0].text;
}
}
| Fix display name on timeline | Fix display name on timeline
Signed-off-by: Ian Costanzo <57a33a5496950fec8433e4dd83347673459dcdfc@anon-solutions.ca>
| TypeScript | apache-2.0 | swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook | ---
+++
@@ -25,7 +25,8 @@
}
get topic_name() {
- return this._cred && this._cred.topic && this._cred.topic.local_name.text;
+ return this._cred && this._cred.local_name && this._cred.local_name.text;
+ //return this._cred && this._cred.topic && this._cred.topic.local_name.text;
//return this._cred && this._cred.names.length && this._cred.names[0].text;
}
|
ff828b9e863004b4141ab04b3c8374fda494b61e | sample/22-graphql-prisma/src/posts/posts.resolver.ts | sample/22-graphql-prisma/src/posts/posts.resolver.ts | import {
Query,
Resolver,
Subscription,
Mutation,
Args,
Info,
} from '@nestjs/graphql';
import { PrismaService } from '../prisma/prisma.service';
import { Post } from '../graphql.schema';
@Resolver()
export class PostsResolver {
constructor(private readonly prisma: PrismaService) {}
@Query('posts')
async getPosts(@Args() args, @Info() info): Promise<Post[]> {
return await this.prisma.query.posts(args, info);
}
@Query('post')
async getPost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.query.post(args, info);
}
@Mutation('createPost')
async createPost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.mutation.createPost(args, info);
}
@Subscription('post')
onUserMutation() {
return {
subscribe: (obj, args, ctx, info) => {
return this.prisma.subscription.post(args, info);
},
};
}
}
| import {
Query,
Resolver,
Subscription,
Mutation,
Args,
Info,
} from '@nestjs/graphql';
import { PrismaService } from '../prisma/prisma.service';
import { BatchPayload } from '../prisma/prisma.binding';
import { Post } from '../graphql.schema';
@Resolver()
export class PostsResolver {
constructor(private readonly prisma: PrismaService) {}
@Query('posts')
async getPosts(@Args() args, @Info() info): Promise<Post[]> {
return await this.prisma.query.posts(args, info);
}
@Query('post')
async getPost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.query.post(args, info);
}
@Mutation('createPost')
async createPost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.mutation.createPost(args, info);
}
@Mutation('updatePost')
async updatePost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.mutation.updatePost(args, info);
}
@Mutation('updateManyPosts')
async updateManyPosts(@Args() args, @Info() info): Promise<BatchPayload> {
return await this.prisma.mutation.updateManyPosts(args, info);
}
@Mutation('deletePost')
async deletePost(@Args() args, @Info() info): Promise<Post> {
return await this.prisma.mutation.deletePost(args, info);
}
@Mutation('deleteManyPosts')
async deleteManyPosts(@Args() args, @Info() info): Promise<BatchPayload> {
return await this.prisma.mutation.deleteManyPosts(args, info);
}
@Subscription('post')
onUserMutation() {
return {
subscribe: (obj, args, ctx, info) => {
return this.prisma.subscription.post(args, info);
},
};
}
}
| Implement all supoorted queries and mutations | feat: Implement all supoorted queries and mutations
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -7,6 +7,7 @@
Info,
} from '@nestjs/graphql';
import { PrismaService } from '../prisma/prisma.service';
+import { BatchPayload } from '../prisma/prisma.binding';
import { Post } from '../graphql.schema';
@Resolver()
@@ -28,6 +29,26 @@
return await this.prisma.mutation.createPost(args, info);
}
+ @Mutation('updatePost')
+ async updatePost(@Args() args, @Info() info): Promise<Post> {
+ return await this.prisma.mutation.updatePost(args, info);
+ }
+
+ @Mutation('updateManyPosts')
+ async updateManyPosts(@Args() args, @Info() info): Promise<BatchPayload> {
+ return await this.prisma.mutation.updateManyPosts(args, info);
+ }
+
+ @Mutation('deletePost')
+ async deletePost(@Args() args, @Info() info): Promise<Post> {
+ return await this.prisma.mutation.deletePost(args, info);
+ }
+
+ @Mutation('deleteManyPosts')
+ async deleteManyPosts(@Args() args, @Info() info): Promise<BatchPayload> {
+ return await this.prisma.mutation.deleteManyPosts(args, info);
+ }
+
@Subscription('post')
onUserMutation() {
return { |
226430c9ef1d7dc10befd03b99c607a0ebaffc43 | app/scripts/components/experts/requests/ExpertRequestState.tsx | app/scripts/components/experts/requests/ExpertRequestState.tsx | import * as classNames from 'classnames';
import * as React from 'react';
import { react2angular } from 'react2angular';
import { RequestState } from './types';
interface ExpertRequestStateProps {
model: {
state: RequestState;
};
}
const LabelClasses = {
Active: '',
Pending: 'progress-bar-warning',
Cancelled: 'progress-bar-danger',
Finished: 'progress-bar-success',
};
const getLabelClass = (state: RequestState): string => LabelClasses[state] || 'label-info';
export const ExpertRequestState = (props: ExpertRequestStateProps) => (
<div className="progress pull-left state-indicator m-b-none">
<span className={classNames(getLabelClass(props.model.state), 'progress-bar', 'p-w-sm', 'full-width')}>
{props.model.state.toUpperCase()}
</span>
</div>
);
export default react2angular(ExpertRequestState, ['model']);
| import * as classNames from 'classnames';
import * as React from 'react';
import { react2angular } from 'react2angular';
import { RequestState } from './types';
interface ExpertRequestStateProps {
model: {
state: RequestState;
};
}
const LabelClasses = {
Active: '',
Pending: 'progress-bar-warning',
Cancelled: 'progress-bar-danger',
Finished: 'progress-bar-success',
};
const getLabelClass = (state: RequestState): string => LabelClasses[state] || 'label-info';
const getLabel = (state: RequestState): string => {
if (state === 'Pending') {
return 'Waiting for proposals'.toUpperCase();
}
return state.toUpperCase();
};
export const ExpertRequestState = (props: ExpertRequestStateProps) => (
<div className="progress pull-left state-indicator m-b-none">
<span className={classNames(getLabelClass(props.model.state), 'progress-bar', 'p-w-sm', 'full-width')}>
{getLabel(props.model.state)}
</span>
</div>
);
export default react2angular(ExpertRequestState, ['model']);
| Rename expert contract state: Pending -> Waiting for proposals | Rename expert contract state: Pending -> Waiting for proposals [WAL-1410]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -19,10 +19,17 @@
const getLabelClass = (state: RequestState): string => LabelClasses[state] || 'label-info';
+const getLabel = (state: RequestState): string => {
+ if (state === 'Pending') {
+ return 'Waiting for proposals'.toUpperCase();
+ }
+ return state.toUpperCase();
+};
+
export const ExpertRequestState = (props: ExpertRequestStateProps) => (
<div className="progress pull-left state-indicator m-b-none">
<span className={classNames(getLabelClass(props.model.state), 'progress-bar', 'p-w-sm', 'full-width')}>
- {props.model.state.toUpperCase()}
+ {getLabel(props.model.state)}
</span>
</div>
); |
229b73c46d30fe0daae3caadf13b416885fe2322 | src/app/services/ts-screener-data.service.ts | src/app/services/ts-screener-data.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class TsScreenerDataService {
private history: Array<number> = [1];
private dataRecord: Array<[number, string]> = [];
constructor() { }
public saveData(state: number, choice: string): void {
this.dataRecord.push([this.history[this.history.length-1], choice]);
this.history.push(state);
console.log(this.history);
console.log(this.dataRecord);
}
public moveStateBackward(): number {
if(this.history.length <= 1) {
return null;
}
this.history.pop();
this.dataRecord.pop();
return this.history[this.history.length-1];
}
}
| import { Injectable } from '@angular/core';
@Injectable()
export class TsScreenerDataService {
private history: Array<number> = [1];
private dataRecord: Array<{state, choice}> = [];
constructor() { }
public saveData(state: number, choice: string): void {
this.dataRecord.push({state: this.history[this.history.length-1], choice: choice});
this.history.push(state);
console.log(this.history);
console.log(this.dataRecord);
}
public moveStateBackward(): number {
if(this.history.length <= 1) {
return null;
}
this.history.pop();
this.dataRecord.pop();
console.log(this.history);
console.log(this.dataRecord);
return this.history[this.history.length-1];
}
}
| Store data in object as opposed to array | Store data in object as opposed to array
| TypeScript | mit | marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website | ---
+++
@@ -3,12 +3,12 @@
@Injectable()
export class TsScreenerDataService {
private history: Array<number> = [1];
- private dataRecord: Array<[number, string]> = [];
+ private dataRecord: Array<{state, choice}> = [];
constructor() { }
public saveData(state: number, choice: string): void {
- this.dataRecord.push([this.history[this.history.length-1], choice]);
+ this.dataRecord.push({state: this.history[this.history.length-1], choice: choice});
this.history.push(state);
console.log(this.history);
console.log(this.dataRecord);
@@ -22,6 +22,9 @@
this.history.pop();
this.dataRecord.pop();
+ console.log(this.history);
+ console.log(this.dataRecord);
+
return this.history[this.history.length-1];
}
} |
5d51de7b780d31a0a49f9df988794a4cc1945abc | app/components/pipes/sanitizer-pipe/sanitizer.pipe.ts | app/components/pipes/sanitizer-pipe/sanitizer.pipe.ts | import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: 'sanitizeHtml',
pure: false
})
export class SanitizerPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(v: string): SafeHtml {
let html = this._sanitizer.bypassSecurityTrustHtml(v);
if (html.hasOwnProperty("changingThisBreaksApplicationSecurity") && html["changingThisBreaksApplicationSecurity"].startsWith("<p>")) {
html["changingThisBreaksApplicationSecurity"] = "<p>" + html["changingThisBreaksApplicationSecurity"].substr(html["changingThisBreaksApplicationSecurity"].indexOf('.') + 1);
}
return html;
}
} | import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: 'sanitizeHtml',
pure: false
})
export class SanitizerPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
transform(v: string): SafeHtml {
console.log("sanitize: " + v);
let html = this._sanitizer.bypassSecurityTrustHtml(v);
if (html.hasOwnProperty("changingThisBreaksApplicationSecurity") && /^<p>\d+\./.test(html["changingThisBreaksApplicationSecurity"])) {
html["changingThisBreaksApplicationSecurity"] = "<p>" + html["changingThisBreaksApplicationSecurity"].substr(html["changingThisBreaksApplicationSecurity"].indexOf('.') + 1);
}
return html;
}
} | Fix broken links in details view | Fix broken links in details view
The matching for sanitizing elements in the reference list was too eager.
Instead of just checking if the HTML starts with "<p>" it now checks if
it starts with the REGEX "<p>\d+\.".
fixes #51
Signed-off-by: Armin Hueneburg <ce14971603cce67272d611a4f194786e96eb4828@gmail.com>
| TypeScript | mit | ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE | ---
+++
@@ -11,8 +11,9 @@
}
transform(v: string): SafeHtml {
+ console.log("sanitize: " + v);
let html = this._sanitizer.bypassSecurityTrustHtml(v);
- if (html.hasOwnProperty("changingThisBreaksApplicationSecurity") && html["changingThisBreaksApplicationSecurity"].startsWith("<p>")) {
+ if (html.hasOwnProperty("changingThisBreaksApplicationSecurity") && /^<p>\d+\./.test(html["changingThisBreaksApplicationSecurity"])) {
html["changingThisBreaksApplicationSecurity"] = "<p>" + html["changingThisBreaksApplicationSecurity"].substr(html["changingThisBreaksApplicationSecurity"].indexOf('.') + 1);
}
return html; |
a9fb75e2ee35c204e143f8988fb1ad15656dd798 | packages/common/src/server/utils/cleanGlobPatterns.ts | packages/common/src/server/utils/cleanGlobPatterns.ts | import {resolve} from "path";
const normalizePath = require("normalize-path");
function mapExcludes(excludes: string[]) {
return excludes.map((s: string) => `!${s.replace(/!/gi, "")}`);
}
function mapExtensions(file: string): string {
if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
file = file.replace(/\.ts$/i, ".js");
}
return file;
}
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
return []
.concat(files as never)
.map((s: string) => resolve(s))
.concat(mapExcludes(excludes) as never)
.map(mapExtensions)
.map((s: string) => normalizePath(s));
}
| import {resolve} from "path";
const normalizePath = require("normalize-path");
function isTsEnv() {
return require.extensions[".ts"] || process.env["TS_TEST"] || process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === "test";
}
function mapExcludes(excludes: string[]) {
return excludes.map((s: string) => `!${s.replace(/!/gi, "")}`);
}
function mapExtensions(file: string): string {
if (!isTsEnv()) {
file = file.replace(/\.ts$/i, ".js");
}
return file;
}
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
return []
.concat(files as never)
.map((s: string) => resolve(s))
.concat(mapExcludes(excludes) as never)
.map(mapExtensions)
.map((s: string) => normalizePath(s));
}
| Add support for jest unit test framework | fix(common): Add support for jest unit test framework
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,13 +1,17 @@
import {resolve} from "path";
const normalizePath = require("normalize-path");
+
+function isTsEnv() {
+ return require.extensions[".ts"] || process.env["TS_TEST"] || process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === "test";
+}
function mapExcludes(excludes: string[]) {
return excludes.map((s: string) => `!${s.replace(/!/gi, "")}`);
}
function mapExtensions(file: string): string {
- if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
+ if (!isTsEnv()) {
file = file.replace(/\.ts$/i, ".js");
}
|
e72197c5e49b69708ebc3aceff6e484b4b1c9966 | src/app/components/authbar/authbar.component.spec.ts | src/app/components/authbar/authbar.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AuthbarComponent } from './authbar.component';
describe('AuthbarComponent', () => {
let component: AuthbarComponent;
let fixture: ComponentFixture<AuthbarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AuthbarComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {AuthbarComponent} from './authbar.component';
import {By} from '@angular/platform-browser';
describe('AuthbarComponent', () => {
let component: AuthbarComponent;
let fixture: ComponentFixture<AuthbarComponent>;
const
user1 = {name: 'John Doe'},
user2 = {name: 'Micky Mouse'};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AuthbarComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthbarComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
expect(component).toBeTruthy();
});
it('should display user name', () => {
const expectedName = user1.name;
component.user = user1;
fixture.detectChanges();
const userName = fixture.debugElement.query(By.css('.user-name')).nativeElement;
expect(userName.textContent.trim()).toBe(expectedName);
expect(userName.textContent.trim()).not.toBe('');
});
it('should indicate online', () => {
const expectedClass = 'green';
component.user = user1;
component.online = true;
fixture.detectChanges();
const avatar = fixture.debugElement.query(By.css('.avatar')).nativeElement;
expect(avatar.classList).toContain(expectedClass);
});
it('should indicate offline', () => {
const expectedClass = 'green';
component.user = user1;
component.online = false;
fixture.detectChanges();
const avatar = fixture.debugElement.query(By.css('.avatar')).nativeElement;
expect(avatar.classList).not.toContain(expectedClass);
});
});
| Update authbar component unit tests | Update authbar component unit tests
| TypeScript | mit | VitaliySokolov/chat-angular4,VitaliySokolov/chat-angular4,VitaliySokolov/chat-angular4 | ---
+++
@@ -1,10 +1,14 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
-import { AuthbarComponent } from './authbar.component';
+import {AuthbarComponent} from './authbar.component';
+import {By} from '@angular/platform-browser';
describe('AuthbarComponent', () => {
let component: AuthbarComponent;
let fixture: ComponentFixture<AuthbarComponent>;
+ const
+ user1 = {name: 'John Doe'},
+ user2 = {name: 'Micky Mouse'};
beforeEach(async(() => {
TestBed.configureTestingModule({
@@ -16,10 +20,37 @@
beforeEach(() => {
fixture = TestBed.createComponent(AuthbarComponent);
component = fixture.componentInstance;
- fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
+
+ it('should display user name', () => {
+ const expectedName = user1.name;
+ component.user = user1;
+ fixture.detectChanges();
+ const userName = fixture.debugElement.query(By.css('.user-name')).nativeElement;
+ expect(userName.textContent.trim()).toBe(expectedName);
+ expect(userName.textContent.trim()).not.toBe('');
+ });
+
+ it('should indicate online', () => {
+ const expectedClass = 'green';
+ component.user = user1;
+ component.online = true;
+ fixture.detectChanges();
+ const avatar = fixture.debugElement.query(By.css('.avatar')).nativeElement;
+ expect(avatar.classList).toContain(expectedClass);
+ });
+
+ it('should indicate offline', () => {
+ const expectedClass = 'green';
+ component.user = user1;
+ component.online = false;
+ fixture.detectChanges();
+ const avatar = fixture.debugElement.query(By.css('.avatar')).nativeElement;
+ expect(avatar.classList).not.toContain(expectedClass);
+
+ });
}); |
b41f817ae1138aa83e970a800a0b9d77bae18b24 | test/runner.ts | test/runner.ts | import { createRunner } from 'atom-mocha-test-runner';
module.exports = createRunner(
{
htmlTitle: `atom-languageclient Tests - pid ${process.pid}`,
reporter: process.env.MOCHA_REPORTER || 'spec',
colors: process.platform !== 'win32',
overrideTestPaths: [/spec$/, /test/],
},
(mocha) => {
mocha.timeout(parseInt(process.env.MOCHA_TIMEOUT || '5000', 10));
if (process.env.APPVEYOR_API_URL) {
mocha.reporter(require('mocha-appveyor-reporter'));
}
},
);
| import { createRunner } from 'atom-mocha-test-runner';
const testRunner = createRunner(
{
htmlTitle: `atom-languageclient Tests - pid ${process.pid}`,
reporter: process.env.MOCHA_REPORTER || 'spec',
},
(mocha) => {
mocha.timeout(parseInt(process.env.MOCHA_TIMEOUT || '5000', 10));
if (process.env.APPVEYOR_API_URL) {
mocha.reporter(require('mocha-appveyor-reporter'));
}
},
);
export = function runnerWrapper(options) {
// Replace the test path with the current path since Atom's internal runner
// picks the wrong one by default
options.testPaths = [__dirname];
return testRunner(options);
};
| Enable tests to run inside of Atom | Enable tests to run inside of Atom
| TypeScript | mit | atom/atom-languageclient,atom/atom-languageclient,atom/atom-languageclient | ---
+++
@@ -1,11 +1,9 @@
import { createRunner } from 'atom-mocha-test-runner';
-module.exports = createRunner(
+const testRunner = createRunner(
{
htmlTitle: `atom-languageclient Tests - pid ${process.pid}`,
reporter: process.env.MOCHA_REPORTER || 'spec',
- colors: process.platform !== 'win32',
- overrideTestPaths: [/spec$/, /test/],
},
(mocha) => {
mocha.timeout(parseInt(process.env.MOCHA_TIMEOUT || '5000', 10));
@@ -14,3 +12,10 @@
}
},
);
+
+export = function runnerWrapper(options) {
+ // Replace the test path with the current path since Atom's internal runner
+ // picks the wrong one by default
+ options.testPaths = [__dirname];
+ return testRunner(options);
+}; |
f855fb4eeb36240784e0f1a8c0c9031ba46ab03b | app/components/searchBox.tsx | app/components/searchBox.tsx | export default function SearchBox({
text,
onChange,
}: {
text: string;
onChange: (text: string) => void;
}) {
return (
<div>
<style jsx={true}>{`
.search_input {
width: 100%;
outline: none;
height: 50px;
padding: 0px 10px 0px 42px;
color: #ffffff;
transition: ease-in-out, 0.35s ease-in-out;
border: none;
box-shadow: 2px 1px 3px gray;
font-size: 12pt;
font-weight: none;
background: #ee6e73 url(/search_icon_color_feature.svg) no-repeat
scroll 14px 17px;
}
.search_input:focus {
color: #000000;
background: #ffffff url(/search_icon_color_black.svg) no-repeat scroll
14px 17px;
}
.search_input:focus ::placeholder {
color: #999999;
}
.search_input ::placeholder {
color: #eebdbf;
}
`}</style>
<div>
<input
className="search_input"
placeholder="Search gifs"
value={text}
onChange={(e) => onChange(e.target.value)}
/>
</div>
</div>
);
}
| export default function SearchBox({
text,
onChange,
}: {
text: string;
onChange: (text: string) => void;
}) {
return (
<div>
<style jsx={true}>{`
.search_input {
width: 100%;
outline: none;
padding: 22px 10px 16px 52px;
color: #ffffff;
transition: ease-in-out, 0.35s ease-in-out;
border: none;
box-shadow: 2px 1px 3px gray;
font-size: 12pt;
font-weight: none;
background: #ee6e73 url(/search_icon_color_feature.svg) no-repeat
scroll 20px 22px;
}
.search_input:focus {
color: #000000;
background: #ffffff url(/search_icon_color_black.svg) no-repeat scroll
20px 22px;
}
.search_input:focus ::placeholder {
color: #999999;
}
.search_input ::placeholder {
color: #eebdbf;
}
`}</style>
<div>
<input
className="search_input"
placeholder="Search gifs"
value={text}
onChange={(e) => onChange(e.target.value)}
/>
</div>
</div>
);
}
| Clean up search box height, padding | Clean up search box height, padding
| TypeScript | apache-2.0 | thenickreynolds/popcorngif,thenickreynolds/popcorngif | ---
+++
@@ -11,8 +11,7 @@
.search_input {
width: 100%;
outline: none;
- height: 50px;
- padding: 0px 10px 0px 42px;
+ padding: 22px 10px 16px 52px;
color: #ffffff;
transition: ease-in-out, 0.35s ease-in-out;
border: none;
@@ -20,13 +19,13 @@
font-size: 12pt;
font-weight: none;
background: #ee6e73 url(/search_icon_color_feature.svg) no-repeat
- scroll 14px 17px;
+ scroll 20px 22px;
}
.search_input:focus {
color: #000000;
background: #ffffff url(/search_icon_color_black.svg) no-repeat scroll
- 14px 17px;
+ 20px 22px;
}
.search_input:focus ::placeholder { |
aaa75f3c106b7ea4fb308e838a8b9dee74ad15dc | projects/lib/src/public_api.ts | projects/lib/src/public_api.ts | export * from './angular-oauth-oidic.module';
export * from './oauth-service';
export * from './token-validation/jwks-validation-handler';
export * from './token-validation/null-validation-handler';
export * from './token-validation/validation-handler';
export * from './url-helper.service';
export * from './auth.config';
export * from './types';
export * from './tokens';
export * from './events';
export * from './interceptors/default-oauth.interceptor';
export * from './interceptors/resource-server-error-handler';
export * from './oauth-module.config';
| export * from './angular-oauth-oidic.module';
export * from './oauth-service';
export * from './token-validation/crypto-handler';
export * from './token-validation/jwks-validation-handler';
export * from './token-validation/null-validation-handler';
export * from './token-validation/validation-handler';
export * from './url-helper.service';
export * from './auth.config';
export * from './types';
export * from './tokens';
export * from './events';
export * from './interceptors/default-oauth.interceptor';
export * from './interceptors/resource-server-error-handler';
export * from './oauth-module.config';
| Add CryptoHandler to public api. | Add CryptoHandler to public api.
| TypeScript | mit | manfredsteyer/angular-oauth2-oidc,manfredsteyer/angular-oauth2-oidc,manfredsteyer/angular-oauth2-oidc | ---
+++
@@ -1,5 +1,6 @@
export * from './angular-oauth-oidic.module';
export * from './oauth-service';
+export * from './token-validation/crypto-handler';
export * from './token-validation/jwks-validation-handler';
export * from './token-validation/null-validation-handler';
export * from './token-validation/validation-handler'; |
9824cc624b7d22d05d7f3ba926d1555edd0e74ec | src/v2/Apps/Conversation/__tests__/Reply.jest.tsx | src/v2/Apps/Conversation/__tests__/Reply.jest.tsx | import React from "react"
import { useTracking } from "v2/Artsy/Analytics/useTracking"
import { MockedConversation } from "v2/Apps/__tests__/Fixtures/Conversation"
import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql"
import { Reply } from "../Components/Reply"
import { mount } from "enzyme"
import { Environment } from "relay-runtime"
jest.mock("v2/Artsy/Analytics/useTracking")
describe("Reply", () => {
describe("tracking", () => {
const trackEvent = jest.fn()
beforeEach(() => {
const mockTracking = useTracking as jest.Mock
mockTracking.mockImplementation(() => {
return {
trackEvent,
}
})
})
afterEach(() => {
jest.clearAllMocks()
})
it("tracks event when text input is focused", async () => {
const wrapper = mount(
<Reply
conversation={
(MockedConversation as unknown) as Conversation_conversation
}
environment={{} as Environment}
refetch={jest.fn}
/>
)
wrapper.find("textarea").simulate("focus")
expect(trackEvent).toHaveBeenCalledWith({
action: "focusedOnConversationMessageInput",
impulse_conversation_id: "conversation1",
})
})
it.todo("tracks event when a message is sent")
})
})
| import React from "react"
import { useTracking } from "v2/Artsy/Analytics/useTracking"
import { MockedConversation } from "v2/Apps/__tests__/Fixtures/Conversation"
import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql"
import { Reply } from "../Components/Reply"
import { mount } from "enzyme"
import { Environment } from "react-relay"
jest.mock("v2/Artsy/Analytics/useTracking")
describe("Reply", () => {
describe("tracking", () => {
const trackEvent = jest.fn()
beforeEach(() => {
const mockTracking = useTracking as jest.Mock
mockTracking.mockImplementation(() => {
return {
trackEvent,
}
})
})
afterEach(() => {
jest.clearAllMocks()
})
it("tracks event when text input is focused", async () => {
const wrapper = mount(
<Reply
conversation={
(MockedConversation as unknown) as Conversation_conversation
}
environment={{} as Environment}
refetch={jest.fn}
/>
)
wrapper.find("textarea").simulate("focus")
expect(trackEvent).toHaveBeenCalledWith({
action: "focusedOnConversationMessageInput",
impulse_conversation_id: "conversation1",
})
})
it.todo("tracks event when a message is sent")
})
})
| Fix relay env type mismatch | Fix relay env type mismatch
| TypeScript | mit | joeyAghion/force,artsy/force,joeyAghion/force,artsy/force-public,joeyAghion/force,joeyAghion/force,eessex/force,eessex/force,eessex/force,eessex/force,artsy/force,artsy/force-public,artsy/force,artsy/force | ---
+++
@@ -4,7 +4,7 @@
import { Conversation_conversation } from "v2/__generated__/Conversation_conversation.graphql"
import { Reply } from "../Components/Reply"
import { mount } from "enzyme"
-import { Environment } from "relay-runtime"
+import { Environment } from "react-relay"
jest.mock("v2/Artsy/Analytics/useTracking")
|
41ffe4f9f96ce6c956aec110cf1b6f9396eec1c2 | AzureFunctions.Client/app/models/constants.ts | AzureFunctions.Client/app/models/constants.ts | export class Constants {
public static runtimeVersion = "~0.4";
public static nodeVersion = "5.9.1";
public static latest = "latest";
public static runtimeVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
public static nodeVersionAppSettingName = "WEBSITE_NODE_DEFAULT_VERSION";
}
| export class Constants {
public static runtimeVersion = "~0.5";
public static nodeVersion = "6.4.0";
public static latest = "latest";
public static runtimeVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
public static nodeVersionAppSettingName = "WEBSITE_NODE_DEFAULT_VERSION";
}
| Update runtime and node versions | Update runtime and node versions
| TypeScript | apache-2.0 | agruning/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal,chunye/azure-functions-ux,projectkudu/AzureFunctions,chunye/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,agruning/azure-functions-ux,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal | ---
+++
@@ -1,6 +1,6 @@
export class Constants {
- public static runtimeVersion = "~0.4";
- public static nodeVersion = "5.9.1";
+ public static runtimeVersion = "~0.5";
+ public static nodeVersion = "6.4.0";
public static latest = "latest";
public static runtimeVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
public static nodeVersionAppSettingName = "WEBSITE_NODE_DEFAULT_VERSION"; |
2170266f5187e2aa586b42aa54b91f1082a75b7e | packages/apollo-cache-inmemory/src/optimism.ts | packages/apollo-cache-inmemory/src/optimism.ts | declare function require(id: string): any;
export type OptimisticWrapperFunction<
T = (...args: any[]) => any,
> = T & {
// The .dirty(...) method of an optimistic function takes exactly the same
// parameter types as the original function.
dirty: T;
};
export type OptimisticWrapOptions = {
max?: number;
disposable?: boolean;
makeCacheKey?(...args: any[]): any;
};
const { wrap }: {
wrap<T>(
originalFunction: T,
options?: OptimisticWrapOptions,
): OptimisticWrapperFunction<T>;
} = require('optimism'); // tslint:disable-line
export { wrap };
export class CacheKeyNode {
private children: Map<any, CacheKeyNode> | null = null;
private key: object | null = null;
lookup(...args: any[]) {
return this.lookupArray(args);
}
lookupArray(array: any[]) {
let node: CacheKeyNode = this;
array.forEach(value => {
node = node.getOrCreate(value);
});
return node.key || (node.key = Object.create(null));
}
getOrCreate(value: any) {
const map = this.children || (this.children = new Map);
return map.get(value) || map.set(value, new CacheKeyNode).get(value);
}
}
| declare function require(id: string): any;
export type OptimisticWrapperFunction<
T = (...args: any[]) => any,
> = T & {
// The .dirty(...) method of an optimistic function takes exactly the same
// parameter types as the original function.
dirty: T;
};
export type OptimisticWrapOptions = {
max?: number;
disposable?: boolean;
makeCacheKey?(...args: any[]): any;
};
const { wrap }: {
wrap<T>(
originalFunction: T,
options?: OptimisticWrapOptions,
): OptimisticWrapperFunction<T>;
} = require('optimism'); // tslint:disable-line
export { wrap };
export class CacheKeyNode<KeyType = object> {
private children: Map<any, CacheKeyNode<KeyType>> | null = null;
private key: KeyType | null = null;
lookup(...args: any[]): KeyType {
return this.lookupArray(args);
}
lookupArray(array: any[]): KeyType {
let node: CacheKeyNode<KeyType> = this;
array.forEach(value => {
node = node.getOrCreate(value);
});
return node.key || (node.key = Object.create(null));
}
getOrCreate(value: any): CacheKeyNode<KeyType> {
const map = this.children || (this.children = new Map);
return map.get(value) || map.set(value, new CacheKeyNode<KeyType>()).get(value);
}
}
| Add generic KeyType parameter to CacheKeyNode class. | Add generic KeyType parameter to CacheKeyNode class.
| TypeScript | mit | apollographql/apollo-client,apollostack/apollo-client,apollographql/apollo-client,apollostack/apollo-client,apollostack/apollo-client | ---
+++
@@ -23,24 +23,24 @@
export { wrap };
-export class CacheKeyNode {
- private children: Map<any, CacheKeyNode> | null = null;
- private key: object | null = null;
+export class CacheKeyNode<KeyType = object> {
+ private children: Map<any, CacheKeyNode<KeyType>> | null = null;
+ private key: KeyType | null = null;
- lookup(...args: any[]) {
+ lookup(...args: any[]): KeyType {
return this.lookupArray(args);
}
- lookupArray(array: any[]) {
- let node: CacheKeyNode = this;
+ lookupArray(array: any[]): KeyType {
+ let node: CacheKeyNode<KeyType> = this;
array.forEach(value => {
node = node.getOrCreate(value);
});
return node.key || (node.key = Object.create(null));
}
- getOrCreate(value: any) {
+ getOrCreate(value: any): CacheKeyNode<KeyType> {
const map = this.children || (this.children = new Map);
- return map.get(value) || map.set(value, new CacheKeyNode).get(value);
+ return map.get(value) || map.set(value, new CacheKeyNode<KeyType>()).get(value);
}
} |
07b2885f964fd2dc636e361431bdd81c3ecc7931 | packages/@sanity/desk-tool/src/diffs/slug/SlugFieldDiff.tsx | packages/@sanity/desk-tool/src/diffs/slug/SlugFieldDiff.tsx | import React from 'react'
import {ObjectDiff, StringDiff} from '@sanity/diff'
import {Annotation} from '../../panes/documentPane/history/types'
import {DiffComponent, SchemaType} from '../types'
import {StringFieldDiff} from '../string/StringFieldDiff'
interface Slug {
current?: string
}
export const SlugFieldDiff: DiffComponent<ObjectDiff<Annotation>> = ({diff, schemaType}) => {
const currentField = schemaType.fields?.find(field => field.name === 'current')
const currentDiff = diff.fields.current
if (!currentField || currentDiff?.action !== 'changed' || currentDiff?.type !== 'string') {
return null
}
return (
<StringFieldDiff
diff={currentDiff}
schemaType={currentField as SchemaType<StringDiff<Annotation>>}
/>
)
}
| import React from 'react'
import {ObjectDiff, StringDiff} from '@sanity/diff'
import {Annotation} from '../../panes/documentPane/history/types'
import {DiffComponent, SchemaType} from '../types'
import {StringFieldDiff} from '../string/StringFieldDiff'
interface Slug {
current?: string
}
export const SlugFieldDiff: DiffComponent<ObjectDiff<Annotation>> = ({diff, schemaType}) => {
const currentField = schemaType.fields?.find(field => field.name === 'current')
const currentDiff = diff.fields.current
if (!currentField || currentDiff?.type !== 'string') {
return null
}
return (
<StringFieldDiff
diff={currentDiff}
schemaType={currentField as SchemaType<StringDiff<Annotation>>}
/>
)
}
| Fix slug diff not rendering unless changed | [desk-tool] Fix slug diff not rendering unless changed
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -11,7 +11,7 @@
export const SlugFieldDiff: DiffComponent<ObjectDiff<Annotation>> = ({diff, schemaType}) => {
const currentField = schemaType.fields?.find(field => field.name === 'current')
const currentDiff = diff.fields.current
- if (!currentField || currentDiff?.action !== 'changed' || currentDiff?.type !== 'string') {
+ if (!currentField || currentDiff?.type !== 'string') {
return null
}
|
c0299b7cc5b55f57a3191931e178acc4a02dc849 | test/git-process-test.ts | test/git-process-test.ts | import * as chai from 'chai'
const expect = chai.expect
import * as path from 'path'
import { GitProcess, GitError } from '../lib'
const temp = require('temp').track()
describe('git-process', () => {
it('can launch git', async () => {
const result = await GitProcess.execWithOutput([ '--version' ], __dirname)
expect(result.stdout.length).to.be.greaterThan(0)
})
it('returns exit code when folder is empty', async () => {
const testRepoPath = temp.mkdirSync('desktop-git-test-blank')
const result = await GitProcess.execWithOutput([ 'show', 'HEAD' ], testRepoPath)
expect(result.exitCode).to.equal(128)
})
describe('errors', () => {
it('raises error when folder does not exist', async () => {
const testRepoPath = path.join(temp.path(), 'desktop-does-not-exist')
let error: Error | null = null
try {
await GitProcess.execWithOutput([ 'show', 'HEAD' ], testRepoPath)
} catch (e) {
error = e
}
expect(error!.message).to.equal('Unable to find path to repository on disk.')
})
it('can parse errors', () => {
const error = GitProcess.parseError('fatal: Authentication failed')
expect(error).to.equal(GitError.SSHAuthenticationFailed)
})
})
})
| import * as chai from 'chai'
const expect = chai.expect
import * as path from 'path'
import { GitProcess, GitError } from '../lib'
const temp = require('temp').track()
describe('git-process', () => {
it('can launch git', async () => {
const result = await GitProcess.execWithOutput([ '--version' ], __dirname)
expect(result.stdout.length).to.be.greaterThan(0)
})
it('returns exit code when folder is empty', async () => {
const testRepoPath = temp.mkdirSync('desktop-git-test-blank')
const result = await GitProcess.execWithOutput([ 'show', 'HEAD' ], testRepoPath)
expect(result.exitCode).to.equal(128)
})
describe('errors', () => {
it('raises error when folder does not exist', async () => {
const testRepoPath = path.join(temp.path(), 'desktop-does-not-exist')
let error: Error | null = null
try {
await GitProcess.execWithOutput([ 'show', 'HEAD' ], testRepoPath)
} catch (e) {
error = e
}
expect(error!.message).to.equal('Unable to find path to repository on disk.')
})
it('can parse errors', () => {
const error = GitProcess.parseError('fatal: Authentication failed')
expect(error).to.equal(GitError.SSHAuthenticationFailed)
})
it('can parse bad revision errors', () => {
const error = GitProcess.parseError("fatal: bad revision 'beta..origin/beta'")
expect(error).to.equal(GitError.BadRevision)
})
})
})
| Test bad revision error parsing | Test bad revision error parsing
| TypeScript | mit | desktop/dugite,desktop/dugite,desktop/dugite | ---
+++
@@ -37,5 +37,10 @@
const error = GitProcess.parseError('fatal: Authentication failed')
expect(error).to.equal(GitError.SSHAuthenticationFailed)
})
+
+ it('can parse bad revision errors', () => {
+ const error = GitProcess.parseError("fatal: bad revision 'beta..origin/beta'")
+ expect(error).to.equal(GitError.BadRevision)
+ })
})
}) |
18f9b5a43fd0c20e663c487f9e9c23ab1242ed33 | packages/components/containers/heading/SupportDropdownButton.tsx | packages/components/containers/heading/SupportDropdownButton.tsx | import React, { Ref } from 'react';
import { c } from 'ttag';
import { Icon, DropdownCaret } from '../../';
interface Props extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
content?: string;
className?: string;
isOpen?: boolean;
buttonRef?: Ref<HTMLButtonElement>;
}
const SupportDropdownButton = ({ content = c('Header').t`Support`, className, isOpen, buttonRef, ...rest }: Props) => {
return (
<button type="button" className={className} aria-expanded={isOpen} ref={buttonRef} {...rest}>
<Icon name="support1" className="flex-item-noshrink topnav-icon mr0-5 flex-item-centered-vert" />
<span className="navigation-title topnav-linkText mr0-5">{content}</span>
<DropdownCaret isOpen={isOpen} className="expand-caret topnav-icon mtauto mbauto" />
</button>
);
};
export default SupportDropdownButton;
| import React, { Ref } from 'react';
import { c } from 'ttag';
import { Icon, DropdownCaret } from '../../';
interface Props extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
content?: string;
className?: string;
isOpen?: boolean;
buttonRef?: Ref<HTMLButtonElement>;
}
const SupportDropdownButton = ({ content = c('Header').t`Help`, className, isOpen, buttonRef, ...rest }: Props) => {
return (
<button type="button" className={className} aria-expanded={isOpen} ref={buttonRef} {...rest}>
<Icon name="support1" className="flex-item-noshrink topnav-icon mr0-5 flex-item-centered-vert" />
<span className="navigation-title topnav-linkText mr0-5">{content}</span>
<DropdownCaret isOpen={isOpen} className="expand-caret topnav-icon mtauto mbauto" />
</button>
);
};
export default SupportDropdownButton;
| Rename support button to help | Rename support button to help
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -9,7 +9,7 @@
buttonRef?: Ref<HTMLButtonElement>;
}
-const SupportDropdownButton = ({ content = c('Header').t`Support`, className, isOpen, buttonRef, ...rest }: Props) => {
+const SupportDropdownButton = ({ content = c('Header').t`Help`, className, isOpen, buttonRef, ...rest }: Props) => {
return (
<button type="button" className={className} aria-expanded={isOpen} ref={buttonRef} {...rest}>
<Icon name="support1" className="flex-item-noshrink topnav-icon mr0-5 flex-item-centered-vert" /> |
ff0eda29d18d80c37e13900d06426520e2fc7365 | frontend/src/hacking-instructor/tutorialUnavailable.ts | frontend/src/hacking-instructor/tutorialUnavailable.ts | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs
} from './helpers/helpers'
import { ChallengeInstruction } from './'
export const TutorialUnavailableInstruction: ChallengeInstruction = {
name: null,
hints: [
{
text:
'😓 Sorry, this hacking challenge does not have a step-by-step tutorial (yet) ... 🧭 Can you find your own way to solve it?',
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
"✍️ Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how! 🏫",
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
'And now: 👾 **GLHF** with this challenge! ',
fixture: 'app-navbar',
resolved: waitInMs(10000)
}
]
}
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs
} from './helpers/helpers'
import { ChallengeInstruction } from './'
export const TutorialUnavailableInstruction: ChallengeInstruction = {
name: null,
hints: [
{
text:
'😓 Sorry, this hacking challenge does not have a step-by-step tutorial (yet) ... 🧭 Can you find your own way to solve it?',
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
'✍️ Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how! 🏫',
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
'And now: 👾 **GLHF** with this challenge!',
fixture: 'app-navbar',
resolved: waitInMs(10000)
}
]
}
| Fix trailing spaces and quotation marks | Fix trailing spaces and quotation marks
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -19,13 +19,13 @@
},
{
text:
- "✍️ Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how! 🏫",
+ '✍️ Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how! 🏫',
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
- 'And now: 👾 **GLHF** with this challenge! ',
+ 'And now: 👾 **GLHF** with this challenge!',
fixture: 'app-navbar',
resolved: waitInMs(10000)
} |
a73835056a0100a066ae2cd2c2f0f55546053d6e | resources/app/auth/components/register/register.component.ts | resources/app/auth/components/register/register.component.ts | export class RegisterComponent implements ng.IComponentOptions {
static NAME: string = 'appRegister';
template: any;
controllerAs: string;
controller;
constructor() {
this.template = require('./register.component.html');
this.controllerAs = '$ctrl';
this.controller = RegisterController;
}
}
class RegisterController implements ng.IComponentController {
static $inject = ['$http', '$state', '$httpParamSerializerJQLike'];
title: string;
user;
emailUsed = false;
constructor(
private http: ng.IHttpService,
private $state: ng.ui.IStateService,
private httpParamSerializerJQLike: ng.IHttpParamSerializer
) {
this.title = "Register Page";
this.user = {};
}
register() {
this.http.post(
'http://localhost:8080/api/register',
this.httpParamSerializerJQLike(this.user),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then(response => {
console.log(response.data);
if (response.data === 'email already used') {
this.emailUsed = true;
return;
}
if (response.data['status'] === 'success') {
this.$state.go('app.auth.login');
}
})
}
} | import { IHttpResponse } from "angular";
export interface ResponseRegister extends IHttpResponse<object> {
data: {
data: {
message: string;
};
status: string;
};
}
export class RegisterComponent implements ng.IComponentOptions {
static NAME: string = 'appRegister';
template: any;
controllerAs: string;
controller;
constructor() {
this.template = require('./register.component.html');
this.controllerAs = '$ctrl';
this.controller = RegisterController;
}
}
class RegisterController implements ng.IComponentController {
static $inject = ['$http', '$state', '$httpParamSerializerJQLike'];
title: string;
user;
emailUsed = false;
constructor(
private http: ng.IHttpService,
private $state: ng.ui.IStateService,
private httpParamSerializerJQLike: ng.IHttpParamSerializer
) {
this.title = "Register Page";
this.user = {};
}
register() {
this.http.post(
'http://localhost:8080/api/register',
this.httpParamSerializerJQLike(this.user),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
).then(response => {
console.log(response.data);
if (response.data === 'email already used') {
this.emailUsed = true;
return;
}
if (response.data['status'] === 'success') {
this.$state.go('app.auth.login');
}
})
}
} | Add ResponseRegister interface in register | Add ResponseRegister interface in register
| TypeScript | mit | ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io | ---
+++
@@ -1,3 +1,14 @@
+import { IHttpResponse } from "angular";
+
+export interface ResponseRegister extends IHttpResponse<object> {
+ data: {
+ data: {
+ message: string;
+ };
+ status: string;
+ };
+}
+
export class RegisterComponent implements ng.IComponentOptions {
static NAME: string = 'appRegister';
template: any; |
74fa589f9d5e40744b9be500c6f2a01244c588c0 | app/src/lib/get-os.ts | app/src/lib/get-os.ts | import * as OS from 'os'
import { UAParser } from 'ua-parser-js'
/** Get the OS we're currently running on. */
export function getOS() {
if (__DARWIN__) {
// On macOS, OS.release() gives us the kernel version which isn't terribly
// meaningful to any human being, so we'll parse the User Agent instead.
// See https://github.com/desktop/desktop/issues/1130.
const parser = new UAParser()
const os = parser.getOS()
return `${os.name} ${os.version}`
} else if (__WIN32__) {
return `Windows ${OS.release()}`
} else {
return `${OS.type()} ${OS.release()}`
}
}
/** See the OS we're currently running on is at least Mojave. */
export function isMojaveOrLater() {
if (__DARWIN__) {
const parser = new UAParser()
const os = parser.getOS()
// Check that it is Mojave or later
if (os.version && os.version.split('.')[1] > '13') {
return true
}
}
return false
}
| import * as OS from 'os'
import { UAParser } from 'ua-parser-js'
/** Get the OS we're currently running on. */
export function getOS() {
if (__DARWIN__) {
// On macOS, OS.release() gives us the kernel version which isn't terribly
// meaningful to any human being, so we'll parse the User Agent instead.
// See https://github.com/desktop/desktop/issues/1130.
const parser = new UAParser()
const os = parser.getOS()
return `${os.name} ${os.version}`
} else if (__WIN32__) {
return `Windows ${OS.release()}`
} else {
return `${OS.type()} ${OS.release()}`
}
}
/** See the OS we're currently running on is at least Mojave. */
export function isMojaveOrLater() {
if (__DARWIN__) {
const parser = new UAParser()
const os = parser.getOS()
if (os.version == null) {
return false
}
const parts = os.version.split('.')
if (parts.length !== 2) {
// unknown version format, giving up
return false
}
return parts[1] > '13'
}
return false
}
| Clean Up Mojave or later | Clean Up Mojave or later
| TypeScript | mit | j-f1/forked-desktop,say25/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,say25/desktop,say25/desktop,artivilla/desktop,say25/desktop | ---
+++
@@ -22,10 +22,18 @@
if (__DARWIN__) {
const parser = new UAParser()
const os = parser.getOS()
- // Check that it is Mojave or later
- if (os.version && os.version.split('.')[1] > '13') {
- return true
+
+ if (os.version == null) {
+ return false
}
+
+ const parts = os.version.split('.')
+ if (parts.length !== 2) {
+ // unknown version format, giving up
+ return false
+ }
+
+ return parts[1] > '13'
}
return false
} |
3c600608d3ebbae13738ee6b7361f5ef52a734e5 | tests/cases/fourslash/completionEntryForImportName.ts | tests/cases/fourslash/completionEntryForImportName.ts | ///<reference path="fourslash.ts" />
////import /*1*/q = /*2*/
verifyIncompleteImport();
goTo.marker('2');
edit.insert("a.");
verifyIncompleteImport();
function verifyIncompleteImport() {
goTo.marker('1');
verify.completionListIsEmpty();
verify.quickInfoIs("import q");
} | ///<reference path="fourslash.ts" />
////import /*1*/ /*2*/
goTo.marker('1');
verify.completionListIsEmpty();
edit.insert('q');
verify.completionListIsEmpty();
verifyIncompleteImportName();
goTo.marker('2');
edit.insert(" = ");
verifyIncompleteImportName();
goTo.marker("2");
edit.moveRight(" = ".length);
edit.insert("a.");
verifyIncompleteImportName();
function verifyIncompleteImportName() {
goTo.marker('1');
verify.completionListIsEmpty();
verify.quickInfoIs("import q");
} | Test now covers completion entry at name of the import when there is no name and there is name | Test now covers completion entry at name of the import when there is no name and there is name
| TypeScript | apache-2.0 | Raynos/TypeScript,ionux/TypeScript,donaldpipowitch/TypeScript,synaptek/TypeScript,msynk/TypeScript,yortus/TypeScript,blakeembrey/TypeScript,mcanthony/TypeScript,nycdotnet/TypeScript,MartyIX/TypeScript,Microsoft/TypeScript,hoanhtien/TypeScript,Mqgh2013/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,jwbay/TypeScript,kingland/TypeScript,AbubakerB/TypeScript,msynk/TypeScript,thr0w/Thr0wScript,kpreisser/TypeScript,vilic/TypeScript,JohnZ622/TypeScript,chuckjaz/TypeScript,RReverser/TypeScript,samuelhorwitz/typescript,SmallAiTT/TypeScript,Mqgh2013/TypeScript,synaptek/TypeScript,yortus/TypeScript,jwbay/TypeScript,kitsonk/TypeScript,ziacik/TypeScript,microsoft/TypeScript,suto/TypeScript,weswigham/TypeScript,moander/TypeScript,nycdotnet/TypeScript,matthewjh/TypeScript,bpowers/TypeScript,OlegDokuka/TypeScript,kingland/TypeScript,ropik/TypeScript,chuckjaz/TypeScript,germ13/TypeScript,blakeembrey/TypeScript,MartyIX/TypeScript,erikmcc/TypeScript,erikmcc/TypeScript,mauricionr/TypeScript,shanexu/TypeScript,mcanthony/TypeScript,shanexu/TypeScript,SimoneGianni/TypeScript,pcan/TypeScript,samuelhorwitz/typescript,AbubakerB/TypeScript,Viromo/TypeScript,yortus/TypeScript,mauricionr/TypeScript,evgrud/TypeScript,evgrud/TypeScript,RyanCavanaugh/TypeScript,thr0w/Thr0wScript,tempbottle/TypeScript,Eyas/TypeScript,impinball/TypeScript,hoanhtien/TypeScript,Viromo/TypeScript,jwbay/TypeScript,gonifade/TypeScript,hoanhtien/TypeScript,matthewjh/TypeScript,thr0w/Thr0wScript,jbondc/TypeScript,jdavidberger/TypeScript,Eyas/TypeScript,OlegDokuka/TypeScript,mcanthony/TypeScript,chuckjaz/TypeScript,plantain-00/TypeScript,synaptek/TypeScript,abbasmhd/TypeScript,mihailik/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,shovon/TypeScript,Microsoft/TypeScript,yazeng/TypeScript,fdecampredon/jsx-typescript,donaldpipowitch/TypeScript,suto/TypeScript,mmoskal/TypeScript,tinganho/TypeScript,Mqgh2013/TypeScript,rgbkrk/TypeScript,ziacik/TypeScript,ropik/TypeScript,JohnZ622/TypeScript,ropik/TypeScript,fabioparra/TypeScript,ionux/TypeScript,plantain-00/TypeScript,jbondc/TypeScript,vilic/TypeScript,ZLJASON/TypeScript,tempbottle/TypeScript,webhost/TypeScript,SmallAiTT/TypeScript,sassson/TypeScript,TukekeSoft/TypeScript,ziacik/TypeScript,weswigham/TypeScript,DanielRosenwasser/TypeScript,pcan/TypeScript,minestarks/TypeScript,DLehenbauer/TypeScript,mihailik/TypeScript,MartyIX/TypeScript,minestarks/TypeScript,SimoneGianni/TypeScript,fdecampredon/jsx-typescript,jbondc/TypeScript,chocolatechipui/TypeScript,hitesh97/TypeScript,jdavidberger/TypeScript,mauricionr/TypeScript,ziacik/TypeScript,basarat/TypeScript,rgbkrk/TypeScript,enginekit/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,progre/TypeScript,gdi2290/TypeScript,jamesrmccallum/TypeScript,moander/TypeScript,TukekeSoft/TypeScript,germ13/TypeScript,Eyas/TypeScript,fdecampredon/jsx-typescript,nagyistoce/TypeScript,DLehenbauer/TypeScript,samuelhorwitz/typescript,shanexu/TypeScript,shiftkey/TypeScript,basarat/TypeScript,RReverser/TypeScript,synaptek/TypeScript,AbubakerB/TypeScript,SmallAiTT/TypeScript,progre/TypeScript,jteplitz602/TypeScript,suto/TypeScript,DLehenbauer/TypeScript,Viromo/TypeScript,shiftkey/TypeScript,alexeagle/TypeScript,OlegDokuka/TypeScript,kitsonk/TypeScript,shanexu/TypeScript,yortus/TypeScript,weswigham/TypeScript,evgrud/TypeScript,erikmcc/TypeScript,mmoskal/TypeScript,mmoskal/TypeScript,yukulele/TypeScript,kpreisser/TypeScript,MartyIX/TypeScript,moander/TypeScript,nojvek/TypeScript,mszczepaniak/TypeScript,zhengbli/TypeScript,fabioparra/TypeScript,donaldpipowitch/TypeScript,nycdotnet/TypeScript,impinball/TypeScript,jamesrmccallum/TypeScript,enginekit/TypeScript,rodrigues-daniel/TypeScript,zmaruo/TypeScript,thr0w/Thr0wScript,ionux/TypeScript,JohnZ622/TypeScript,chuckjaz/TypeScript,Raynos/TypeScript,DanielRosenwasser/TypeScript,tempbottle/TypeScript,zhengbli/TypeScript,zhengbli/TypeScript,erikmcc/TypeScript,nojvek/TypeScript,kumikumi/TypeScript,mszczepaniak/TypeScript,impinball/TypeScript,rodrigues-daniel/TypeScript,kingland/TypeScript,kumikumi/TypeScript,shovon/TypeScript,progre/TypeScript,kimamula/TypeScript,kpreisser/TypeScript,shiftkey/TypeScript,HereSinceres/TypeScript,ZLJASON/TypeScript,TukekeSoft/TypeScript,plantain-00/TypeScript,fdecampredon/jsx-typescript,yukulele/TypeScript,abbasmhd/TypeScript,jeremyepling/TypeScript,germ13/TypeScript,gonifade/TypeScript,hitesh97/TypeScript,mauricionr/TypeScript,RyanCavanaugh/TypeScript,rodrigues-daniel/TypeScript,kimamula/TypeScript,nagyistoce/TypeScript,nycdotnet/TypeScript,Microsoft/TypeScript,DanielRosenwasser/TypeScript,RReverser/TypeScript,basarat/TypeScript,DanielRosenwasser/TypeScript,samuelhorwitz/typescript,zmaruo/TypeScript,SaschaNaz/TypeScript,evgrud/TypeScript,enginekit/TypeScript,Raynos/TypeScript,fabioparra/TypeScript,jamesrmccallum/TypeScript,chocolatechipui/TypeScript,mihailik/TypeScript,Raynos/TypeScript,HereSinceres/TypeScript,webhost/TypeScript,zmaruo/TypeScript,mmoskal/TypeScript,jdavidberger/TypeScript,jeremyepling/TypeScript,microsoft/TypeScript,basarat/TypeScript,nagyistoce/TypeScript,kimamula/TypeScript,DLehenbauer/TypeScript,plantain-00/TypeScript,jeremyepling/TypeScript,fearthecowboy/TypeScript,mcanthony/TypeScript,moander/TypeScript,matthewjh/TypeScript,Eyas/TypeScript,mihailik/TypeScript,bpowers/TypeScript,jwbay/TypeScript,shovon/TypeScript,yazeng/TypeScript,mszczepaniak/TypeScript,tinganho/TypeScript,JohnZ622/TypeScript,sassson/TypeScript,SaschaNaz/TypeScript,SimoneGianni/TypeScript,Viromo/TypeScript,alexeagle/TypeScript,jteplitz602/TypeScript,yazeng/TypeScript,blakeembrey/TypeScript,gonifade/TypeScript,yukulele/TypeScript,keir-rex/TypeScript,abbasmhd/TypeScript,keir-rex/TypeScript,vilic/TypeScript,billti/TypeScript,HereSinceres/TypeScript,minestarks/TypeScript,billti/TypeScript,alexeagle/TypeScript,kumikumi/TypeScript,fabioparra/TypeScript,rodrigues-daniel/TypeScript,bpowers/TypeScript,ZLJASON/TypeScript,kimamula/TypeScript,SaschaNaz/TypeScript,AbubakerB/TypeScript,fearthecowboy/TypeScript,chocolatechipui/TypeScript,hitesh97/TypeScript,pcan/TypeScript,tinganho/TypeScript,rgbkrk/TypeScript,billti/TypeScript,nojvek/TypeScript,blakeembrey/TypeScript,ropik/TypeScript,fearthecowboy/TypeScript,keir-rex/TypeScript,sassson/TypeScript,msynk/TypeScript,ionux/TypeScript,jteplitz602/TypeScript,webhost/TypeScript | ---
+++
@@ -1,13 +1,23 @@
///<reference path="fourslash.ts" />
-////import /*1*/q = /*2*/
+////import /*1*/ /*2*/
-verifyIncompleteImport();
+goTo.marker('1');
+verify.completionListIsEmpty();
+edit.insert('q');
+verify.completionListIsEmpty();
+verifyIncompleteImportName();
+
goTo.marker('2');
+edit.insert(" = ");
+verifyIncompleteImportName();
+
+goTo.marker("2");
+edit.moveRight(" = ".length);
edit.insert("a.");
-verifyIncompleteImport();
+verifyIncompleteImportName();
-function verifyIncompleteImport() {
+function verifyIncompleteImportName() {
goTo.marker('1');
verify.completionListIsEmpty();
verify.quickInfoIs("import q"); |
0e06c091916b0d78edfb543e029999601d68ae16 | src/app/catalog/plugins/ubuntu/ubuntu.component.ts | src/app/catalog/plugins/ubuntu/ubuntu.component.ts | import { Component, Input } from '@angular/core';
import {
FormBuilder,
FormGroupDirective } from '@angular/forms';
import { BasePluginComponent } from '../base-plugin.component';
@Component({
selector: 'ubuntu-config',
template: ``,
inputs: ['cloud', 'initialConfig']
})
export class UbuntuConfigComponent extends BasePluginComponent {
constructor(fb: FormBuilder, parentContainer: FormGroupDirective) {
super(fb, parentContainer);
}
get configName(): string {
return "config_ubuntu";
}
}
| import { Component, Input } from '@angular/core';
import {
FormBuilder,
FormGroup,
FormGroupDirective } from '@angular/forms';
import { BasePluginComponent } from '../base-plugin.component';
@Component({
selector: 'ubuntu-config',
template: ``,
inputs: ['cloud', 'initialConfig']
})
export class UbuntuConfigComponent extends BasePluginComponent {
ubuntuLaunchForm: FormGroup;
constructor(fb: FormBuilder, parentContainer: FormGroupDirective) {
super(fb, parentContainer);
this.ubuntuLaunchForm = fb.group({});
}
get form(): FormGroup {
return this.ubuntuLaunchForm;
}
get configName(): string {
return "config_ubuntu";
}
}
| Implement `get form` for UbuntuConfigComponent | Implement `get form` for UbuntuConfigComponent
| TypeScript | mit | galaxyproject/cloudlaunch-ui,galaxyproject/cloudlaunch-ui,galaxyproject/cloudlaunch-ui | ---
+++
@@ -1,6 +1,7 @@
import { Component, Input } from '@angular/core';
import {
FormBuilder,
+ FormGroup,
FormGroupDirective } from '@angular/forms';
import { BasePluginComponent } from '../base-plugin.component';
@@ -11,9 +12,15 @@
inputs: ['cloud', 'initialConfig']
})
export class UbuntuConfigComponent extends BasePluginComponent {
+ ubuntuLaunchForm: FormGroup;
constructor(fb: FormBuilder, parentContainer: FormGroupDirective) {
super(fb, parentContainer);
+ this.ubuntuLaunchForm = fb.group({});
+ }
+
+ get form(): FormGroup {
+ return this.ubuntuLaunchForm;
}
get configName(): string { |
3a79e8faf3ea612fb49b9e7ec8c2b604a767b38c | src/gui/storage.ts | src/gui/storage.ts | class WebStorage {
private storageObj: Storage;
public constructor(storageObj: Storage) {
this.storageObj = storageObj;
}
public get(key: string): string {
if (!this.isCompatible()) { return; }
return this.storageObj.getItem(key);
}
public getObj(key: string): any {
if (!this.isCompatible()) { return; }
try {
return JSON.parse(this.get(key));
} catch (e) {
console.log('Invalid JSON: ' + e.message);
}
}
public set(key: string, value: string): void {
if (!this.isCompatible()) { return; }
this.storageObj.setItem(key, value);
}
public setObj(key: string, value: Object): void {
if (!this.isCompatible()) { return; }
try {
this.set(key, JSON.stringify(value));
} catch (e) {
console.log('Invalid JSON: ' + e.message);
}
}
private isCompatible(): boolean {
if (typeof(Storage) !== 'undefined') {
return true;
} else {
console.log('Your browser does not support Web Storage.');
return false;
}
}
}
| class WebStorage {
private storageObj: Storage;
public constructor(storageObj: Storage) {
this.storageObj = storageObj;
}
public getStorageObj(): Storage {
return this.storageObj;
}
public get(key: string): string {
if (!this.isCompatible()) {return;}
return this.storageObj.getItem(key);
}
public getObj(key: string): any {
if (!this.isCompatible()) {return;}
try {
return JSON.parse(this.get(key));
} catch (e) {
console.log('Invalid JSON: ' + e.message);
}
}
public set(key: string, value: string): void {
if (!this.isCompatible()) {return;}
this.storageObj.setItem(key, value);
}
public setObj(key: string, value: Object): void {
if (!this.isCompatible()) {return;}
try {
this.set(key, JSON.stringify(value));
} catch (e) {
console.log('Invalid JSON: ' + e.message);
}
}
public delete(key: string): void {
if (!this.isCompatible()) {return;}
this.storageObj.removeItem(key);
}
private isCompatible(): boolean {
if (typeof(Storage) !== 'undefined') {
return true;
} else {
console.log('Your browser does not support Web Storage.');
return false;
}
}
}
| Add getStorageObj() and delete(key) methods | Add getStorageObj() and delete(key) methods
| TypeScript | mit | CAAL/CAAL,CAAL/CAAL,CAAL/CAAL,CAAL/CAAL | ---
+++
@@ -5,14 +5,18 @@
this.storageObj = storageObj;
}
+ public getStorageObj(): Storage {
+ return this.storageObj;
+ }
+
public get(key: string): string {
- if (!this.isCompatible()) { return; }
+ if (!this.isCompatible()) {return;}
return this.storageObj.getItem(key);
}
public getObj(key: string): any {
- if (!this.isCompatible()) { return; }
+ if (!this.isCompatible()) {return;}
try {
return JSON.parse(this.get(key));
@@ -22,19 +26,25 @@
}
public set(key: string, value: string): void {
- if (!this.isCompatible()) { return; }
+ if (!this.isCompatible()) {return;}
this.storageObj.setItem(key, value);
}
public setObj(key: string, value: Object): void {
- if (!this.isCompatible()) { return; }
+ if (!this.isCompatible()) {return;}
try {
this.set(key, JSON.stringify(value));
} catch (e) {
console.log('Invalid JSON: ' + e.message);
}
+ }
+
+ public delete(key: string): void {
+ if (!this.isCompatible()) {return;}
+
+ this.storageObj.removeItem(key);
}
private isCompatible(): boolean { |
79fd19fba597ad01a07107a36ac469cc51aaa9d6 | packages/@glimmer/syntax/lib/errors/syntax-error.ts | packages/@glimmer/syntax/lib/errors/syntax-error.ts | import * as AST from '../types/nodes';
/*
* Subclass of `Error` with additional information
* about location of incorrect markup.
*/
class SyntaxError {
message: string;
stack: string;
location: AST.SourceLocation;
constructor(message: string, location: AST.SourceLocation) {
let error = Error.call(this, message);
this.message = message;
this.stack = error.stack;
this.location = location;
}
}
SyntaxError.prototype = Object.create(Error.prototype);
export default SyntaxError;
| import * as AST from '../types/nodes';
export interface SyntaxError extends Error {
location: AST.SourceLocation;
constructor: SyntaxErrorConstructor;
}
export interface SyntaxErrorConstructor {
new (message: string, location: AST.SourceLocation): SyntaxError;
readonly prototype: SyntaxError;
}
/**
* Subclass of `Error` with additional information
* about location of incorrect markup.
*/
const SyntaxError: SyntaxErrorConstructor = (function () {
SyntaxError.prototype = Object.create(Error.prototype);
SyntaxError.prototype.constructor = SyntaxError;
function SyntaxError(this: SyntaxError, message: string, location: AST.SourceLocation) {
let error = Error.call(this, message);
this.message = message;
this.stack = error.stack;
this.location = location;
}
return SyntaxError as any;
}());
export default SyntaxError;
| Convert SyntaxError class to ES5 syntax | Convert SyntaxError class to ES5 syntax
The `prototype` property on classes is readonly.
| TypeScript | mit | lbdm44/glimmer-vm,tildeio/glimmer,glimmerjs/glimmer-vm,glimmerjs/glimmer-vm,tildeio/glimmer,lbdm44/glimmer-vm,glimmerjs/glimmer-vm,lbdm44/glimmer-vm,tildeio/glimmer | ---
+++
@@ -1,23 +1,32 @@
import * as AST from '../types/nodes';
-/*
+export interface SyntaxError extends Error {
+ location: AST.SourceLocation;
+ constructor: SyntaxErrorConstructor;
+}
+
+export interface SyntaxErrorConstructor {
+ new (message: string, location: AST.SourceLocation): SyntaxError;
+ readonly prototype: SyntaxError;
+}
+
+/**
* Subclass of `Error` with additional information
* about location of incorrect markup.
*/
-class SyntaxError {
- message: string;
- stack: string;
- location: AST.SourceLocation;
+const SyntaxError: SyntaxErrorConstructor = (function () {
+ SyntaxError.prototype = Object.create(Error.prototype);
+ SyntaxError.prototype.constructor = SyntaxError;
- constructor(message: string, location: AST.SourceLocation) {
+ function SyntaxError(this: SyntaxError, message: string, location: AST.SourceLocation) {
let error = Error.call(this, message);
this.message = message;
this.stack = error.stack;
this.location = location;
}
-}
-SyntaxError.prototype = Object.create(Error.prototype);
+ return SyntaxError as any;
+}());
export default SyntaxError; |
c451b16a551ae1fab9795bd65b136e854f841eec | packages/app/app/containers/ErrorBoundary/index.tsx | packages/app/app/containers/ErrorBoundary/index.tsx | import logger from 'electron-timber';
import React from 'react';
import { withRouter } from 'react-router';
import { History } from 'history';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as ToastActions from '../../actions/toasts';
type ErrorBoundaryProps = {
onError: typeof ToastActions.error;
settings: { [key: string]: unknown };
history: History;
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
componentDidCatch(error) {
logger.error(error.message ? error.message : error);
this.props.onError(
'Uncaught error',
error.message,
undefined,
this.props.settings
);
this.props.history.goBack();
}
render() {
return this.props.children;
}
}
function mapStateToProps(state) {
return {
settings: state.settings
};
}
function mapDispatchToProps(dispatch) {
return {
onError: bindActionCreators(ToastActions.error, dispatch)
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ErrorBoundary));
| import logger from 'electron-timber';
import React from 'react';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as ToastActions from '../../actions/toasts';
type ErrorBoundaryProps = {
onError: typeof ToastActions.error;
settings: { [key: string]: unknown };
history: {
goBack: () => void;
};
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> {
componentDidCatch(error) {
logger.error(error.message ? error.message : error);
this.props.onError(
'Uncaught error',
error.message,
undefined,
this.props.settings
);
this.props.history.goBack();
}
render() {
return this.props.children;
}
}
function mapStateToProps(state) {
return {
settings: state.settings
};
}
function mapDispatchToProps(dispatch) {
return {
onError: bindActionCreators(ToastActions.error, dispatch)
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ErrorBoundary));
| Add a constructor to error boundary | Add a constructor to error boundary
| TypeScript | agpl-3.0 | nukeop/nuclear,nukeop/nuclear,nukeop/nuclear,nukeop/nuclear | ---
+++
@@ -1,7 +1,6 @@
import logger from 'electron-timber';
import React from 'react';
import { withRouter } from 'react-router';
-import { History } from 'history';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
@@ -10,7 +9,9 @@
type ErrorBoundaryProps = {
onError: typeof ToastActions.error;
settings: { [key: string]: unknown };
- history: History;
+ history: {
+ goBack: () => void;
+ };
}
class ErrorBoundary extends React.Component<ErrorBoundaryProps> { |
4515bdf2b4c16129dbe08040a40b5213414a88f1 | packages/boxel/addon/components/boxel/tab-bar/index.ts | packages/boxel/addon/components/boxel/tab-bar/index.ts | import Component from '@glimmer/component';
import { Link } from 'ember-link';
import { MenuItem } from '@cardstack/boxel/helpers/menu-item';
import '@cardstack/boxel/styles/global.css';
import './index.css';
interface TabBarArgs {
items: MenuItem[];
}
export default class TabBar extends Component<TabBarArgs> {
get linkItems() {
return this.args.items.filter((item) => item.action instanceof Link);
}
}
| import Component from '@glimmer/component';
import { Link } from 'ember-link';
import { MenuItem } from '@cardstack/boxel/helpers/menu-item';
import '@cardstack/boxel/styles/global.css';
import './index.css';
interface TabBarArgs {
items: MenuItem[];
}
export default class TabBar extends Component<TabBarArgs> {
get linkItems(): MenuItem[] {
return this.args.items.filter((item) => item.action instanceof Link);
}
}
| Fix missing return type lint error in TabBar component | Fix missing return type lint error in TabBar component
| TypeScript | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack | ---
+++
@@ -9,7 +9,7 @@
}
export default class TabBar extends Component<TabBarArgs> {
- get linkItems() {
+ get linkItems(): MenuItem[] {
return this.args.items.filter((item) => item.action instanceof Link);
}
} |
ccb7b673fa64a948cb8a44672631e891ef06181f | lib/cli/src/generators/REACT_SCRIPTS/index.ts | lib/cli/src/generators/REACT_SCRIPTS/index.ts | import path from 'path';
import fs from 'fs';
import { baseGenerator, Generator } from '../baseGenerator';
const generator: Generator = async (packageManager, npmOptions, options) => {
const extraMain = options.linkable
? {
webpackFinal: `%%(config) => {
// add monorepo root as a valid directory to import modules from
config.resolve.plugins.forEach((p) => {
if (Array.isArray(p.appSrcs)) {
p.appSrcs.push(path.join(__dirname, '..', '..', '..'));
}
});
return config;
}
%%`,
}
: {};
await baseGenerator(packageManager, npmOptions, options, 'react', {
extraAddons: ['@storybook/preset-create-react-app'],
// `@storybook/preset-create-react-app` has `@storybook/node-logger` as peerDep
extraPackages: ['@storybook/node-logger'],
staticDir: fs.existsSync(path.resolve('./public')) ? 'public' : undefined,
addBabel: false,
addESLint: true,
extraMain,
});
};
export default generator;
| import path from 'path';
import fs from 'fs';
import { baseGenerator, Generator } from '../baseGenerator';
const generator: Generator = async (packageManager, npmOptions, options) => {
const extraMain = options.linkable
? {
webpackFinal: `%%(config) => {
const path = require('path');
// add monorepo root as a valid directory to import modules from
config.resolve.plugins.forEach((p) => {
if (Array.isArray(p.appSrcs)) {
p.appSrcs.push(path.join(__dirname, '..', '..', '..', 'storybook'));
}
});
return config;
}
%%`,
}
: {};
await baseGenerator(packageManager, npmOptions, options, 'react', {
extraAddons: ['@storybook/preset-create-react-app'],
// `@storybook/preset-create-react-app` has `@storybook/node-logger` as peerDep
extraPackages: ['@storybook/node-logger'],
staticDir: fs.existsSync(path.resolve('./public')) ? 'public' : undefined,
addBabel: false,
addESLint: true,
extraMain,
});
};
export default generator;
| Fix CRA linking to match ../storybook-repros structure | Fix CRA linking to match ../storybook-repros structure
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -7,10 +7,11 @@
const extraMain = options.linkable
? {
webpackFinal: `%%(config) => {
+ const path = require('path');
// add monorepo root as a valid directory to import modules from
config.resolve.plugins.forEach((p) => {
if (Array.isArray(p.appSrcs)) {
- p.appSrcs.push(path.join(__dirname, '..', '..', '..'));
+ p.appSrcs.push(path.join(__dirname, '..', '..', '..', 'storybook'));
}
});
return config; |
c928d659f1d2d770e696b7ebbf4eb692ebf07855 | src/app/duels/duel-week.ts | src/app/duels/duel-week.ts | import { Game } from './game';
import { Player } from './player';
export class DuelWeek {
games = new Array<Game>();
constructor(
public _id: string,
public duelId: string,
public weekNum: number,
public betAmount: number,
public picker: Player,
public players: Player[],
public record: { wins: number, losses: number, pushes: number },
games: Game[], ) {
}
}
| import { Game } from './game';
import { Player } from './player';
export class DuelWeek {
games = new Array<Game>();
constructor(
public _id: string,
public duelId: string,
public year: number,
public weekNum: number,
public betAmount: number,
public picker: Player,
public players: Player[],
public record: { wins: number, losses: number, pushes: number },
games: Game[], ) {
}
}
| Add year to DuelWeek NG model | Add year to DuelWeek NG model
| TypeScript | mit | lentz/buddyduel,lentz/buddyduel,lentz/buddyduel | ---
+++
@@ -7,6 +7,7 @@
constructor(
public _id: string,
public duelId: string,
+ public year: number,
public weekNum: number,
public betAmount: number,
public picker: Player, |
0f358e1f21a623ae7423fab7af955f1b2bf47336 | src/background-script/quick-and-dirty-migrations.ts | src/background-script/quick-and-dirty-migrations.ts | import Dexie from 'dexie'
export interface Migrations {
[storageKey: string]: (db: Dexie) => Promise<void>
}
export const migrations: Migrations = {
/**
* If lastEdited is undefined, then set it to createdWhen value.
*/
'annots-created-when-to-last-edited': async db => {
await db
.table('annotations')
.toCollection()
.filter(
annot =>
annot.lastEdited == null ||
(Object.keys(annot.lastEdited).length === 0 &&
annot.lastEdited.constructor === Object),
)
.modify(annot => {
annot.lastEdited = annot.createdWhen
})
},
}
| import Dexie from 'dexie'
import normalize from 'src/util/encode-url-for-id'
export interface Migrations {
[storageKey: string]: (db: Dexie) => Promise<void>
}
export const migrations: Migrations = {
/**
* If pageUrl is undefined, then re-derive it from url field.
*/
'annots-undefined-pageUrl-field': async db => {
await db
.table('annotations')
.toCollection()
.filter(annot => annot.pageUrl === undefined)
.modify(annot => {
annot.pageUrl = normalize(annot.url)
})
},
/**
* If lastEdited is undefined, then set it to createdWhen value.
*/
'annots-created-when-to-last-edited': async db => {
await db
.table('annotations')
.toCollection()
.filter(
annot =>
annot.lastEdited == null ||
(Object.keys(annot.lastEdited).length === 0 &&
annot.lastEdited.constructor === Object),
)
.modify(annot => {
annot.lastEdited = annot.createdWhen
})
},
}
| Add "quick-and-dirty" migration to rederive missing annot `pageUrl` fields | Add "quick-and-dirty" migration to rederive missing annot `pageUrl` fields
- due to the update issue, users may have annots data with `pageUrl` fields set to `undefined`
- annots search will crash with data like this as it assumes `pageUrl` field is always available
- "quick-and-dirty" migrations already set up to run once on the next update (unless user manually removes flag from local storage)
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -1,10 +1,23 @@
import Dexie from 'dexie'
+import normalize from 'src/util/encode-url-for-id'
export interface Migrations {
[storageKey: string]: (db: Dexie) => Promise<void>
}
export const migrations: Migrations = {
+ /**
+ * If pageUrl is undefined, then re-derive it from url field.
+ */
+ 'annots-undefined-pageUrl-field': async db => {
+ await db
+ .table('annotations')
+ .toCollection()
+ .filter(annot => annot.pageUrl === undefined)
+ .modify(annot => {
+ annot.pageUrl = normalize(annot.url)
+ })
+ },
/**
* If lastEdited is undefined, then set it to createdWhen value.
*/ |
196a208a83edb2f4a88c42116a20631ca8bcb1fa | packages/@ember/-internals/utils/lib/cache.ts | packages/@ember/-internals/utils/lib/cache.ts | export default class Cache<T, V> {
public size = 0;
public misses = 0;
public hits = 0;
constructor(private limit: number, private func: (obj: T) => V, private store?: any) {
this.store = store || new Map();
}
get(key: T): V {
let value = this.store.get(key);
if (this.store.has(key)) {
this.hits++;
return this.store.get(key);
} else {
this.misses++;
value = this.set(key, this.func(key));
}
return value;
}
set(key: T, value: V) {
if (this.limit > this.size) {
this.size++;
this.store.set(key, value);
}
return value;
}
purge() {
this.store.clear();
this.size = 0;
this.hits = 0;
this.misses = 0;
}
}
| export default class Cache<T, V> {
public size = 0;
public misses = 0;
public hits = 0;
constructor(private limit: number, private func: (obj: T) => V, private store?: any) {
this.store = store || new Map();
}
get(key: T): V {
let value;
if (this.store.has(key)) {
this.hits++;
value = this.store.get(key);
} else {
this.misses++;
value = this.set(key, this.func(key));
}
return value;
}
set(key: T, value: V) {
if (this.limit > this.size) {
this.size++;
this.store.set(key, value);
}
return value;
}
purge() {
this.store.clear();
this.size = 0;
this.hits = 0;
this.misses = 0;
}
}
| Change logic to remove variable that is never read | Change logic to remove variable that is never read
| TypeScript | mit | qaiken/ember.js,miguelcobain/ember.js,tildeio/ember.js,sly7-7/ember.js,asakusuma/ember.js,cibernox/ember.js,miguelcobain/ember.js,qaiken/ember.js,givanse/ember.js,cibernox/ember.js,Turbo87/ember.js,cibernox/ember.js,mfeckie/ember.js,elwayman02/ember.js,elwayman02/ember.js,fpauser/ember.js,asakusuma/ember.js,cibernox/ember.js,givanse/ember.js,sandstrom/ember.js,Turbo87/ember.js,tildeio/ember.js,fpauser/ember.js,emberjs/ember.js,intercom/ember.js,kellyselden/ember.js,mixonic/ember.js,miguelcobain/ember.js,Turbo87/ember.js,emberjs/ember.js,GavinJoyce/ember.js,fpauser/ember.js,mfeckie/ember.js,bekzod/ember.js,sandstrom/ember.js,tildeio/ember.js,miguelcobain/ember.js,elwayman02/ember.js,stefanpenner/ember.js,kellyselden/ember.js,mfeckie/ember.js,knownasilya/ember.js,asakusuma/ember.js,fpauser/ember.js,qaiken/ember.js,mixonic/ember.js,kellyselden/ember.js,givanse/ember.js,sandstrom/ember.js,jaswilli/ember.js,stefanpenner/ember.js,mfeckie/ember.js,givanse/ember.js,bekzod/ember.js,jaswilli/ember.js,mixonic/ember.js,emberjs/ember.js,jaswilli/ember.js,bekzod/ember.js,bekzod/ember.js,sly7-7/ember.js,knownasilya/ember.js,stefanpenner/ember.js,intercom/ember.js,GavinJoyce/ember.js,GavinJoyce/ember.js,asakusuma/ember.js,kellyselden/ember.js,Turbo87/ember.js,sly7-7/ember.js,jaswilli/ember.js,intercom/ember.js,qaiken/ember.js,knownasilya/ember.js,intercom/ember.js,GavinJoyce/ember.js,elwayman02/ember.js | ---
+++
@@ -8,11 +8,11 @@
}
get(key: T): V {
- let value = this.store.get(key);
+ let value;
if (this.store.has(key)) {
this.hits++;
- return this.store.get(key);
+ value = this.store.get(key);
} else {
this.misses++;
value = this.set(key, this.func(key)); |
42d018a93e36e0aa41806d3276591c0fe4c14a16 | packages/@ember/-internals/browser-environment/index.ts | packages/@ember/-internals/browser-environment/index.ts | import hasDom from './lib/has-dom';
declare const chrome: unknown;
declare const opera: unknown;
declare const MSInputMethodContext: unknown;
declare const documentMode: unknown;
export { default as hasDOM } from './lib/has-dom';
export const window = hasDom ? self : null;
export const location = hasDom ? self.location : null;
export const history = hasDom ? self.history : null;
export const userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
export const isChrome = hasDom ? typeof chrome === 'object' && !(typeof opera === 'object') : false;
export const isFirefox = hasDom ? /Firefox|FxiOS/.test(userAgent) : false;
export const isIE = hasDom
? typeof MSInputMethodContext !== 'undefined' && typeof documentMode !== 'undefined'
: false;
| import hasDom from './lib/has-dom';
declare const chrome: unknown;
declare const opera: unknown;
export { default as hasDOM } from './lib/has-dom';
export const window = hasDom ? self : null;
export const location = hasDom ? self.location : null;
export const history = hasDom ? self.history : null;
export const userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
export const isChrome = hasDom ? typeof chrome === 'object' && !(typeof opera === 'object') : false;
export const isFirefox = hasDom ? /Firefox|FxiOS/.test(userAgent) : false;
| Remove browser detection for IE | Remove browser detection for IE
| TypeScript | mit | sly7-7/ember.js,emberjs/ember.js,sly7-7/ember.js,tildeio/ember.js,sly7-7/ember.js,emberjs/ember.js,emberjs/ember.js,tildeio/ember.js,tildeio/ember.js | ---
+++
@@ -2,8 +2,6 @@
declare const chrome: unknown;
declare const opera: unknown;
-declare const MSInputMethodContext: unknown;
-declare const documentMode: unknown;
export { default as hasDOM } from './lib/has-dom';
export const window = hasDom ? self : null;
@@ -12,6 +10,3 @@
export const userAgent = hasDom ? self.navigator.userAgent : 'Lynx (textmode)';
export const isChrome = hasDom ? typeof chrome === 'object' && !(typeof opera === 'object') : false;
export const isFirefox = hasDom ? /Firefox|FxiOS/.test(userAgent) : false;
-export const isIE = hasDom
- ? typeof MSInputMethodContext !== 'undefined' && typeof documentMode !== 'undefined'
- : false; |
76f989f66542cf75cf69c8d8271bc86676e174b2 | source/api/graphql/api.ts | source/api/graphql/api.ts | import { fetch } from "../../api/fetch"
export const graphqlAPI = (url: string, query: string) =>
fetch(`${url}/api/graphql`, {
method: "POST",
body: JSON.stringify({ query }),
headers: { "Content-Type": "application/json", Accept: "application/json" },
})
.then(res => {
if (res.ok) {
return res.json()
} else {
throw new Error("HTTP error\n" + JSON.stringify(res, null, " "))
}
})
.then(body => {
if (body.errors) {
// tslint:disable-next-line:no-console
console.log("Received errors from the GraphQL API")
// tslint:disable-next-line:no-console
console.log(body.errors)
}
return body
})
| import { fetch } from "../../api/fetch"
export const graphqlAPI = (url: string, query: string) =>
fetch(`${url}/api/graphql`, {
method: "POST",
body: JSON.stringify({ query }),
headers: { "Content-Type": "application/json", Accept: "application/json" },
})
.then(res => {
if (res.ok) {
return res.json()
} else {
throw new Error("GraphQL API HTTP error\n> " + res.statusText + "\n")
}
})
.then(body => {
if (body.errors) {
// tslint:disable-next-line:no-console
console.log("Received errors from the GraphQL API")
// tslint:disable-next-line:no-console
console.log(body.errors)
}
return body
})
| Improve local graphql error logging | Improve local graphql error logging
| TypeScript | mit | danger/peril,danger/peril,danger/peril,danger/peril,danger/peril | ---
+++
@@ -10,7 +10,7 @@
if (res.ok) {
return res.json()
} else {
- throw new Error("HTTP error\n" + JSON.stringify(res, null, " "))
+ throw new Error("GraphQL API HTTP error\n> " + res.statusText + "\n")
}
})
.then(body => { |
e66634334a437276bcf97e2a188b6c1ec6c6c2e8 | 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');
});
});
}
}
| 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);
});
}
}
| Add method to get lands with most color identities | Add method to get lands with most color identities
| TypeScript | mit | christianhg/magicalc,christianhg/magicalc,christianhg/magicalc | ---
+++
@@ -17,4 +17,16 @@
});
});
}
+
+ 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);
+ });
+ }
} |
fcc0118d9e80073d8d453007a3aab00a8c4cf0ef | client/app/accounts/services/account.service.ts | client/app/accounts/services/account.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { environment } from '../../../environments/environment';
@Injectable()
export class AccountService {
private url = `${environment.backend.url}/accounts`;
constructor(private http: Http) {
}
register(email: string, password: string): Promise<void> {
const data = { email, password };
return this.http
.post(this.url, data)
.toPromise()
.then(response => {});
}
}
| import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { environment } from '../../../environments/environment';
@Injectable()
export class AccountService {
private url = `${environment.backend.url}/accounts`;
constructor(private http: Http) {
}
register(email: string, password: string): Promise<void> {
const data = { email, password };
return this.http
.post(this.url, data)
.toPromise()
.then(response => {});
}
createToken(email: string, password: string): Promise<string> {
const data = { email, password };
return this.http
.post(`${this.url}/token`, data)
.toPromise()
.then(response => response.json().access_token);
}
}
| Add the create token method | Add the create token method
| TypeScript | mit | fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training | ---
+++
@@ -18,4 +18,13 @@
.toPromise()
.then(response => {});
}
+
+ createToken(email: string, password: string): Promise<string> {
+ const data = { email, password };
+
+ return this.http
+ .post(`${this.url}/token`, data)
+ .toPromise()
+ .then(response => response.json().access_token);
+ }
} |
90024bedb75ce751a488e26b3e9af418f1d991ae | src/CollectionHelpers.ts | src/CollectionHelpers.ts | // Returns the last item from `items`.
export function last<T>(items: T[]): T {
return items[items.length - 1]
}
// Returns a single flattened array containing every item from every array in `collections`.
// The items' order is preserved.
export function concat<T>(collections: T[][]): T[] {
return [].concat(...collections)
}
// Returns a reversed shallow copy of `items`.
export function reversed<T>(items: T[]): T[] {
return items.slice().reverse()
}
// Removes the last instance of `itemToRemove` from `items`.
export function remove<T>(items: T[], itemToRemove: T): void {
for (let i = items.length - 1; i >= 0; i--) {
if (items[i] === itemToRemove) {
items.splice(i, 1)
return
}
}
}
// Returns the distinct items from `items` in their original order
export function distinct<T>(items: T[]): T[] {
return items.reduce((distinctItems, item) =>
(distinctItems.indexOf(item) !== -1)
? distinctItems
: distinctItems.concat([item])
, [])
}
// Returns the first non-null value in `values`, if one exists. Otherwise, returns null.
export function coalesce<T>(...values: T[]): T {
for (const value of values) {
if (value != null) {
return value
}
}
return null
} | // Returns the last item from `collection`.
export function last<T>(collection: T[]): T {
return collection[collection.length - 1]
}
// Returns a single flattened array containing every item from every array in `collections`.
// The items' order is preserved.
export function concat<T>(collections: T[][]): T[] {
return [].concat(...collections)
}
// Returns a reversed shallow copy of `collection`.
export function reversed<T>(collection: T[]): T[] {
return collection.slice().reverse()
}
// Removes the last instance of `itemToRemove` from `collection`.
export function remove<T>(collection: T[], itemToRemove: T): void {
for (let i = collection.length - 1; i >= 0; i--) {
if (collection[i] === itemToRemove) {
collection.splice(i, 1)
return
}
}
}
// Returns the distinct items from `items`. The items' order is preserved.
export function distinct<T>(collection: T[]): T[] {
return collection.reduce((distinctItems, item) =>
(distinctItems.indexOf(item) !== -1)
? distinctItems
: distinctItems.concat([item])
, [])
}
// Returns the first non-null value in `values`, if one exists. Otherwise, returns null.
export function coalesce<T>(...values: T[]): T {
for (const value of values) {
if (value != null) {
return value
}
}
return null
}
| Improve argument names in collection helpers | Improve argument names in collection helpers
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,6 +1,6 @@
-// Returns the last item from `items`.
-export function last<T>(items: T[]): T {
- return items[items.length - 1]
+// Returns the last item from `collection`.
+export function last<T>(collection: T[]): T {
+ return collection[collection.length - 1]
}
// Returns a single flattened array containing every item from every array in `collections`.
@@ -9,30 +9,29 @@
return [].concat(...collections)
}
-// Returns a reversed shallow copy of `items`.
-export function reversed<T>(items: T[]): T[] {
- return items.slice().reverse()
+// Returns a reversed shallow copy of `collection`.
+export function reversed<T>(collection: T[]): T[] {
+ return collection.slice().reverse()
}
-// Removes the last instance of `itemToRemove` from `items`.
-export function remove<T>(items: T[], itemToRemove: T): void {
- for (let i = items.length - 1; i >= 0; i--) {
- if (items[i] === itemToRemove) {
- items.splice(i, 1)
+// Removes the last instance of `itemToRemove` from `collection`.
+export function remove<T>(collection: T[], itemToRemove: T): void {
+ for (let i = collection.length - 1; i >= 0; i--) {
+ if (collection[i] === itemToRemove) {
+ collection.splice(i, 1)
return
}
}
}
-// Returns the distinct items from `items` in their original order
-export function distinct<T>(items: T[]): T[] {
- return items.reduce((distinctItems, item) =>
+// Returns the distinct items from `items`. The items' order is preserved.
+export function distinct<T>(collection: T[]): T[] {
+ return collection.reduce((distinctItems, item) =>
(distinctItems.indexOf(item) !== -1)
? distinctItems
: distinctItems.concat([item])
, [])
}
-
// Returns the first non-null value in `values`, if one exists. Otherwise, returns null.
export function coalesce<T>(...values: T[]): T { |
013d34001c10d291978a78f3d597c5711c43132a | ui/src/tempVars/components/TemplatePreviewListItem.tsx | ui/src/tempVars/components/TemplatePreviewListItem.tsx | import React, {PureComponent} from 'react'
import {TemplateValue} from 'src/types'
interface Props {
item: TemplateValue
onClick: (item: TemplateValue) => void
style: {
height: string
marginBottom: string
}
}
class TemplatePreviewListItem extends PureComponent<Props> {
public render() {
const {item, style} = this.props
return (
<li onClick={this.handleClick} style={style}>
{item.value}
</li>
)
}
private handleClick = (): void => {
this.props.onClick(this.props.item)
}
}
export default TemplatePreviewListItem
| import React, {PureComponent} from 'react'
import classNames from 'classnames'
import {TemplateValue} from 'src/types'
interface Props {
item: TemplateValue
onClick: (item: TemplateValue) => void
style: {
height: string
marginBottom: string
}
}
class TemplatePreviewListItem extends PureComponent<Props> {
public render() {
const {item, style} = this.props
return (
<li
onClick={this.handleClick}
style={style}
className={classNames('temp-builder-results--list-item', {
active: this.isSelected,
})}
>
{item.value}
</li>
)
}
private get isSelected() {
return this.props.item.selected
}
private handleClick = (): void => {
this.props.onClick(this.props.item)
}
}
export default TemplatePreviewListItem
| Add active class name on selected temp list item | Add active class name on selected temp list item
| TypeScript | mit | mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb,influxdata/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -1,4 +1,5 @@
import React, {PureComponent} from 'react'
+import classNames from 'classnames'
import {TemplateValue} from 'src/types'
@@ -16,10 +17,20 @@
const {item, style} = this.props
return (
- <li onClick={this.handleClick} style={style}>
+ <li
+ onClick={this.handleClick}
+ style={style}
+ className={classNames('temp-builder-results--list-item', {
+ active: this.isSelected,
+ })}
+ >
{item.value}
</li>
)
+ }
+
+ private get isSelected() {
+ return this.props.item.selected
}
private handleClick = (): void => { |
9f2de4e8f534574c8f288ae082f0d0d4d8ed0acb | src/locales/en/parsers/ENTimeUnitAgoFormatParser.ts | src/locales/en/parsers/ENTimeUnitAgoFormatParser.ts | import {Parser, ParsingContext} from "../../../chrono";
import {
parseTimeUnits,
TIME_UNITS_PATTERN
} from "../constants";
import {ParsingComponents} from "../../../results";
import {AbstractParserWithWordBoundaryChecking} from "../../../common/parsers/AbstractParserWithWordBoundary";
const PATTERN = new RegExp('' +
'(?:within\\s*)?' +
'(' + TIME_UNITS_PATTERN + ')' +
'(?:ago|before|earlier)(?=(?:\\W|$))', 'i');
const STRICT_PATTERN = new RegExp('' +
'(?<=\\W|^)' +
'(?:within\\s*)?' +
'(' + TIME_UNITS_PATTERN + ')' +
'ago(?=(?:\\W|$))', 'i');
export default class ENTimeUnitAgoFormatParser extends AbstractParserWithWordBoundaryChecking {
constructor(private strictMode: boolean) {
super();
}
innerPattern(): RegExp { return this.strictMode ? STRICT_PATTERN : PATTERN; }
innerExtract(context: ParsingContext, match: RegExpMatchArray) {
const fragments = parseTimeUnits(match[1]);
for (const key in fragments) {
fragments[key] = -fragments[key];
}
return ParsingComponents.createRelativeFromRefDate(context.refDate, fragments);
}
}
| import {Parser, ParsingContext} from "../../../chrono";
import {
parseTimeUnits,
TIME_UNITS_PATTERN
} from "../constants";
import {ParsingComponents} from "../../../results";
import {AbstractParserWithWordBoundaryChecking} from "../../../common/parsers/AbstractParserWithWordBoundary";
const PATTERN = new RegExp('' +
'(?:within\\s*)?' +
'(' + TIME_UNITS_PATTERN + ')' +
'(?:ago|before|earlier)(?=(?:\\W|$))', 'i');
const STRICT_PATTERN = new RegExp('' +
'(?:within\\s*)?' +
'(' + TIME_UNITS_PATTERN + ')' +
'ago(?=(?:\\W|$))', 'i');
export default class ENTimeUnitAgoFormatParser extends AbstractParserWithWordBoundaryChecking {
constructor(private strictMode: boolean) {
super();
}
innerPattern(): RegExp { return this.strictMode ? STRICT_PATTERN : PATTERN; }
innerExtract(context: ParsingContext, match: RegExpMatchArray) {
const fragments = parseTimeUnits(match[1]);
for (const key in fragments) {
fragments[key] = -fragments[key];
}
return ParsingComponents.createRelativeFromRefDate(context.refDate, fragments);
}
}
| Remove the remaining lookbehind usage | Remove the remaining lookbehind usage
| TypeScript | mit | wanasit/chrono,wanasit/chrono | ---
+++
@@ -13,7 +13,6 @@
'(?:ago|before|earlier)(?=(?:\\W|$))', 'i');
const STRICT_PATTERN = new RegExp('' +
- '(?<=\\W|^)' +
'(?:within\\s*)?' +
'(' + TIME_UNITS_PATTERN + ')' +
'ago(?=(?:\\W|$))', 'i'); |
35631899c33d51fac1081830cedf09614be044bf | applications/desktop/__mocks__/enchannel-zmq-backend.ts | applications/desktop/__mocks__/enchannel-zmq-backend.ts | import { createMainChannelFromSockets } from "enchannel-zmq-backend/src";
const EventEmitter = require("events");
// Mock a jmp socket
class HokeySocket extends EventEmitter {
constructor() {
super();
this.send = jest.fn();
}
send() {}
}
module.exports = {
async createMainChannel() {
const shellSocket = new HokeySocket();
const iopubSocket = new HokeySocket();
const sockets = {
shell: shellSocket,
iopub: iopubSocket
};
const channels = await createMainChannelFromSockets(sockets, {
session: "spinning",
username: "dj"
});
return channels;
}
};
| import { createMainChannelFromSockets } from "enchannel-zmq-backend";
const EventEmitter = require("events");
// Mock a jmp socket
class HokeySocket extends EventEmitter {
constructor() {
super();
this.send = jest.fn();
}
send() {}
}
module.exports = {
async createMainChannel() {
const shellSocket = new HokeySocket();
const iopubSocket = new HokeySocket();
const sockets = {
shell: shellSocket,
iopub: iopubSocket
};
const channels = await createMainChannelFromSockets(sockets, {
session: "spinning",
username: "dj"
});
return channels;
}
};
| Fix import of external dependency | Fix import of external dependency
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition,nteract/composition | ---
+++
@@ -1,4 +1,4 @@
-import { createMainChannelFromSockets } from "enchannel-zmq-backend/src";
+import { createMainChannelFromSockets } from "enchannel-zmq-backend";
const EventEmitter = require("events");
|
cda4b8e4b9bf5042c6f0e22a056ce899c31d79a2 | src/immutable-map-type.ts | src/immutable-map-type.ts | class ImmutableMapType {
cons: any;
constructor () {
this.cons = Object;
}
add (obj, data: Array<any>) {
if (!Array.isArray(data)) { data = [data]; }
var i, flag = false;
var newobj = Object.create(obj);
for (i = 0; i < data.length; i++) {
if (newobj[data[i]._id]) {
newobj[data[i]._id] = data[i];
flag = true;
}
}
if (flag) { return newobj; }
else { return obj; }
}
};
| class ImmutableMapType {
cons: any;
constructor () {
this.cons = Object;
}
add (obj, data: Array<any>) {
if (!Array.isArray(data)) { data = [data]; }
var i, flag = false;
var newobj = Object.create(obj);
for (i = 0; i < data.length; i++) {
if (newobj[data[i]._id]) {
newobj[data[i]._id] = data[i];
flag = true;
}
}
if (flag) { return newobj; }
//no change
else { return obj; }
}
};
| Add comment for no change stat in immutable obj type | Add comment for no change stat in immutable obj type
| TypeScript | mit | othree/immutable-quadtree-js,othree/immutable-quadtree-js,othree/immutable-quadtree-js | ---
+++
@@ -16,6 +16,7 @@
}
}
if (flag) { return newobj; }
+ //no change
else { return obj; }
}
}; |
845105912274f9fa0ba3a223c850b076d60a7716 | src/client/src/rt-interop/intents/responseMapper.ts | src/client/src/rt-interop/intents/responseMapper.ts | import { DetectIntentResponse } from 'dialogflow'
import { MARKET_INFO_INTENT, SPOT_QUOTE_INTENT, TRADES_INFO_INTENT } from './intents'
export const mapIntent = (response: DetectIntentResponse): string => {
let result = ''
if (!response) {
return result
}
switch (response.queryResult.intent.displayName) {
case SPOT_QUOTE_INTENT:
const currencyPair = response.queryResult.parameters.fields.CurrencyPairs.stringValue
result = `Open ${currencyPair}`
break
case MARKET_INFO_INTENT:
return `Open market view`
case TRADES_INFO_INTENT:
return `Open blotter`
default:
}
return result
}
export const isSpotQuoteIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === SPOT_QUOTE_INTENT
}
export const isTradeIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === TRADES_INFO_INTENT
}
export const isMarketIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === MARKET_INFO_INTENT
}
| import { DetectIntentResponse } from 'dialogflow'
import { MARKET_INFO_INTENT, SPOT_QUOTE_INTENT, TRADES_INFO_INTENT } from './intents'
export const mapIntent = (response: DetectIntentResponse): string => {
let result = ''
if (!response) {
return result
}
switch (response.queryResult.intent.displayName) {
case SPOT_QUOTE_INTENT:
const currencyPair = response.queryResult.parameters.fields.CurrencyPairs.stringValue
result = `Open ${currencyPair} Tile`
break
case MARKET_INFO_INTENT:
return `Open Live Rates`
case TRADES_INFO_INTENT:
return `Open Trades`
default:
}
return result
}
export const isSpotQuoteIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === SPOT_QUOTE_INTENT
}
export const isTradeIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === TRADES_INFO_INTENT
}
export const isMarketIntent = (response: DetectIntentResponse) => {
return response && response.queryResult.intent.displayName === MARKET_INFO_INTENT
}
| Fix launcher button labels to spec | fix(launcher): Fix launcher button labels to spec
| TypeScript | apache-2.0 | AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud | ---
+++
@@ -10,12 +10,12 @@
switch (response.queryResult.intent.displayName) {
case SPOT_QUOTE_INTENT:
const currencyPair = response.queryResult.parameters.fields.CurrencyPairs.stringValue
- result = `Open ${currencyPair}`
+ result = `Open ${currencyPair} Tile`
break
case MARKET_INFO_INTENT:
- return `Open market view`
+ return `Open Live Rates`
case TRADES_INFO_INTENT:
- return `Open blotter`
+ return `Open Trades`
default:
}
|
a0bbc5e0363c51927012b62b68524415acec23a7 | src/views/codeSnippetTextDocumentContentProvider.ts | src/views/codeSnippetTextDocumentContentProvider.ts | "use strict";
import { Uri, extensions } from 'vscode';
import { BaseTextDocumentContentProvider } from './baseTextDocumentContentProvider';
import * as Constants from '../constants';
import * as path from 'path';
const hljs = require('highlight.js');
const codeHighlightLinenums = require('code-highlight-linenums');
export class CodeSnippetTextDocumentContentProvider extends BaseTextDocumentContentProvider {
private static cssFilePath: string = path.join(extensions.getExtension(Constants.ExtensionId).extensionPath, Constants.CSSFolderName, Constants.CSSFileName);
public constructor(public convertResult: string, public lang: string) {
super();
}
public provideTextDocumentContent(uri: Uri): string {
if (this.convertResult) {
return `
<head>
<link rel="stylesheet" href="${CodeSnippetTextDocumentContentProvider.cssFilePath}">
</head>
<body>
<div>
<pre><code>${codeHighlightLinenums(this.convertResult, { hljs: hljs, lang: this.getHighlightJsLanguageAlias(), start: 1 })}</code></pre>
<a id="scroll-to-top" role="button" aria-label="scroll to top" onclick="scroll(0,0)"><span class="icon"></span></a>
</div>
</body>`;
}
}
private getHighlightJsLanguageAlias() {
if (!this.lang || this.lang === 'bash') {
return 'bash';
}
if (this.lang === 'node') {
return 'javascript';
}
return this.lang;
}
} | "use strict";
import { Uri, extensions } from 'vscode';
import { BaseTextDocumentContentProvider } from './baseTextDocumentContentProvider';
import * as Constants from '../constants';
import * as path from 'path';
const hljs = require('highlight.js');
const codeHighlightLinenums = require('code-highlight-linenums');
export class CodeSnippetTextDocumentContentProvider extends BaseTextDocumentContentProvider {
private static cssFilePath: string = path.join(extensions.getExtension(Constants.ExtensionId).extensionPath, Constants.CSSFolderName, Constants.CSSFileName);
public constructor(public convertResult: string, public lang: string) {
super();
}
public provideTextDocumentContent(uri: Uri): string {
if (this.convertResult) {
return `
<head>
<link rel="stylesheet" href="${CodeSnippetTextDocumentContentProvider.cssFilePath}">
</head>
<body>
<div>
<pre><code>${codeHighlightLinenums(this.convertResult, { hljs: hljs, lang: this.getHighlightJsLanguageAlias(), start: 1 })}</code></pre>
<a id="scroll-to-top" role="button" aria-label="scroll to top" onclick="scroll(0,0)"><span class="icon"></span></a>
</div>
</body>`;
}
}
private getHighlightJsLanguageAlias() {
if (!this.lang || this.lang === 'shell') {
return 'bash';
}
if (this.lang === 'node') {
return 'javascript';
}
return this.lang;
}
} | Use bash instead of shell to code snippet highlight | Use bash instead of shell to code snippet highlight
| TypeScript | mit | Huachao/vscode-restclient,Huachao/vscode-restclient | ---
+++
@@ -31,7 +31,7 @@
}
private getHighlightJsLanguageAlias() {
- if (!this.lang || this.lang === 'bash') {
+ if (!this.lang || this.lang === 'shell') {
return 'bash';
}
|
8ec40f898d97a4c32e91e90ab06bf2957b3e5323 | src/app/states/devices/abstract-device.service.ts | src/app/states/devices/abstract-device.service.ts | import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Measure, Step } from '../measures/measure';
import { AbstractDevice } from './abstract-device';
export abstract class AbstractDeviceService<T extends AbstractDevice> {
protected textDecoder = new TextDecoder('utf8');
constructor(protected store: Store) {}
abstract getDeviceInfo(device: T): Observable<Partial<T>>;
abstract saveDeviceParams(device: T): Observable<any>;
abstract startMeasureScan(device: T, stopSignal: Observable<any>): Observable<Step>;
computeRadiationValue(measure: Measure): number {
if (measure.endTime && measure.hitsNumber) {
const duration = (measure.endTime - measure.startTime) / 1000;
const hitsNumberPerSec = measure.hitsNumber / duration;
return this.convertHitsNumberPerSec(hitsNumberPerSec);
} else {
throw new Error('Incorrect measure : missing endTime or hitsNumber');
}
}
protected abstract convertHitsNumberPerSec(hitsNumberPerSec: number): number;
abstract connectDevice(device: T): Observable<any>;
abstract disconnectDevice(device: T): Observable<any>;
protected abstract decodeDataPackage(buffer: ArrayBuffer | ArrayBuffer[]): Step | null;
}
| import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Measure, Step } from '../measures/measure';
import { AbstractDevice } from './abstract-device';
export abstract class AbstractDeviceService<T extends AbstractDevice> {
protected textDecoder = new TextDecoder('utf8');
constructor(protected store: Store) {}
abstract getDeviceInfo(device: T): Observable<Partial<T>>;
abstract saveDeviceParams(device: T): Observable<any>;
abstract startMeasureScan(device: T, stopSignal: Observable<any>): Observable<Step>;
computeRadiationValue(measure: Measure): number {
if (measure.endTime && measure.hitsNumber !== undefined) {
const duration = (measure.endTime - measure.startTime) / 1000;
const hitsNumberPerSec = measure.hitsNumber / duration;
return this.convertHitsNumberPerSec(hitsNumberPerSec);
} else {
throw new Error('Incorrect measure : missing endTime or hitsNumber');
}
}
protected abstract convertHitsNumberPerSec(hitsNumberPerSec: number): number;
abstract connectDevice(device: T): Observable<any>;
abstract disconnectDevice(device: T): Observable<any>;
protected abstract decodeDataPackage(buffer: ArrayBuffer | ArrayBuffer[]): Step | null;
}
| Fix computeRadiationValue for scan measures | Fix computeRadiationValue for scan measures
| TypeScript | apache-2.0 | openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile | ---
+++
@@ -15,7 +15,7 @@
abstract startMeasureScan(device: T, stopSignal: Observable<any>): Observable<Step>;
computeRadiationValue(measure: Measure): number {
- if (measure.endTime && measure.hitsNumber) {
+ if (measure.endTime && measure.hitsNumber !== undefined) {
const duration = (measure.endTime - measure.startTime) / 1000;
const hitsNumberPerSec = measure.hitsNumber / duration;
return this.convertHitsNumberPerSec(hitsNumberPerSec); |
2b74720866923af5a406c24d99cbd1955a8cfadd | client/Settings/components/CustomCSSEditor.tsx | client/Settings/components/CustomCSSEditor.tsx | import * as React from "react";
import { ChangeEvent } from "react";
import { ColorResult, SketchPicker } from "react-color";
import { PlayerViewCustomStyles } from "../../../common/PlayerViewSettings";
import { StylesChooser } from "./StylesChooser";
export interface CustomCSSEditorProps {
currentCSS: string;
currentStyles: PlayerViewCustomStyles;
updateCSS: (css: string) => void;
updateStyle: (name: keyof PlayerViewCustomStyles, value: string) => void;
}
interface State {
manualCSS: string;
}
export class CustomCSSEditor extends React.Component<CustomCSSEditorProps, State> {
constructor(props: CustomCSSEditorProps) {
super(props);
this.state = {
manualCSS: this.props.currentCSS
};
}
private updateCSS = (event: ChangeEvent<HTMLTextAreaElement>) => {
this.setState({ manualCSS: event.target.value });
this.props.updateCSS(event.target.value);
}
public render() {
return <div className="custom-css-editor">
<p>Epic Initiative is enabled.</p>
<StylesChooser currentStyles={this.props.currentStyles} updateStyle={this.props.updateStyle} />
<h4>Additional CSS</h4>
<textarea rows={10} onChange={this.updateCSS} value={this.props.currentCSS} />
</div>;
}
}
| import * as React from "react";
import { ChangeEvent } from "react";
import { ColorResult, SketchPicker } from "react-color";
import { PlayerViewCustomStyles } from "../../../common/PlayerViewSettings";
import { StylesChooser } from "./StylesChooser";
export interface CustomCSSEditorProps {
currentCSS: string;
currentStyles: PlayerViewCustomStyles;
updateCSS: (css: string) => void;
updateStyle: (name: keyof PlayerViewCustomStyles, value: string) => void;
}
interface State {
manualCSS: string;
}
export class CustomCSSEditor extends React.Component<CustomCSSEditorProps, State> {
constructor(props: CustomCSSEditorProps) {
super(props);
this.state = {
manualCSS: this.props.currentCSS
};
}
private updateCSS = (event: ChangeEvent<HTMLTextAreaElement>) => {
this.setState({ manualCSS: event.target.value });
this.props.updateCSS(event.target.value);
}
public render() {
return <div className="custom-css-editor">
<p>Epic Initiative is enabled.</p>
<StylesChooser currentStyles={this.props.currentStyles} updateStyle={this.props.updateStyle} />
<h4>Additional CSS</h4>
<textarea rows={10} onChange={this.updateCSS} value={this.state.manualCSS} />
</div>;
}
}
| Allow text to be entered into custom css editor | Allow text to be entered into custom css editor
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -33,7 +33,7 @@
<p>Epic Initiative is enabled.</p>
<StylesChooser currentStyles={this.props.currentStyles} updateStyle={this.props.updateStyle} />
<h4>Additional CSS</h4>
- <textarea rows={10} onChange={this.updateCSS} value={this.props.currentCSS} />
+ <textarea rows={10} onChange={this.updateCSS} value={this.state.manualCSS} />
</div>;
}
} |
9ce9120c618c3075bf1165f215bb6fc67da4dd4a | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList
];
}
return chain(ruleList);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: Rule = (tree, context) => tree;
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile
];
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/ng-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids | ---
+++
@@ -4,6 +4,8 @@
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
+
+export const _mergeModuleIntoComponentFile: Rule = (tree, context) => tree;
export function scam(options: ScamOptions): Rule {
@@ -18,7 +20,8 @@
if (!options.separateModule) {
ruleList = [
- ...ruleList
+ ...ruleList,
+ _mergeModuleIntoComponentFile
];
}
|
9fa9229ce668e0fa5bded410e23df473e962d00d | src/pipeline/Paginate.ts | src/pipeline/Paginate.ts | import { PipelineAbstract, option, description } from '../serafin/pipeline/Abstract'
import * as Promise from 'bluebird'
@description("Provides pagination over the read results")
export class Paginate<T,
ReadQuery = {},
ReadOptions = { offset?: number, count?: number },
ReadWrapper = { count: number, results: {}[] }>
extends PipelineAbstract<T, ReadQuery, ReadOptions, ReadWrapper> {
@description("Reads a limited count of results")
@option('offset', { type: "integer" }, false)
@option('count', { type: "integer" }, false)
@option('page', { type: "integer" }, false)
read(query?: ReadQuery): Promise<ReadWrapper> {
return this.parent.read(query).then((resources) => {
let count = resources.results.length;
return Promise.resolve({ ...resources, count: count });
});
}
} | import { PipelineAbstract, option, description } from '../serafin/pipeline/Abstract'
import * as Promise from 'bluebird'
@description("Provides pagination over the read results")
export class Paginate<T,
ReadQuery = {},
ReadOptions = { offset?: number, count?: number },
ReadWrapper = { count: number, results: {}[] }>
extends PipelineAbstract<T, ReadQuery, ReadOptions, ReadWrapper> {
@description("Reads a limited count of results")
@option('offset', { type: "integer" }, false)
@option('count', { type: "integer" }, false)
@option('page', { type: "integer" }, false)
read(query?: ReadQuery, options?: ReadOptions): Promise<ReadWrapper> {
return this.parent.read(query, options).then((resources) => {
let offset = 0;
if (options) {
if (options['offset']) {
offset = options['offset'];
} else if (options['page'] && options['count']) {
offset = (resources.length / options['count']) * options['page'];
}
if (options['count']) {
if (offset > resources.length) {
throw new Error("Offset higher than the number of resources");
}
resources = resources.slice(offset, offset + options['count']);
}
}
return Promise.resolve({ ...resources, count: resources.length });
});
}
} | Add operations to the Pager Pipeline | Add operations to the Pager Pipeline
| TypeScript | mit | serafin-framework/serafin,serafin-framework/serafin | ---
+++
@@ -12,10 +12,27 @@
@option('offset', { type: "integer" }, false)
@option('count', { type: "integer" }, false)
@option('page', { type: "integer" }, false)
- read(query?: ReadQuery): Promise<ReadWrapper> {
- return this.parent.read(query).then((resources) => {
- let count = resources.results.length;
- return Promise.resolve({ ...resources, count: count });
+ read(query?: ReadQuery, options?: ReadOptions): Promise<ReadWrapper> {
+ return this.parent.read(query, options).then((resources) => {
+ let offset = 0;
+
+ if (options) {
+ if (options['offset']) {
+ offset = options['offset'];
+ } else if (options['page'] && options['count']) {
+ offset = (resources.length / options['count']) * options['page'];
+ }
+
+ if (options['count']) {
+ if (offset > resources.length) {
+ throw new Error("Offset higher than the number of resources");
+ }
+
+ resources = resources.slice(offset, offset + options['count']);
+ }
+ }
+
+ return Promise.resolve({ ...resources, count: resources.length });
});
}
} |
0f11d837d986588a52d0c7083f76b2f3531cbfb1 | frontend/src/app/Services/data-subject.service.ts | frontend/src/app/Services/data-subject.service.ts | import { environment } from '../../environments/environment'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { catchError, map } from 'rxjs/operators'
@Injectable({
providedIn: 'root'
})
export class DataSubjectService {
private hostServer = environment.hostServer
private host = this.hostServer + '/api/user'
constructor (private http: HttpClient) { }
deactivate () {
return this.http.get(this.host + '/erasure-request').pipe(
map((response: any) => response),
catchError(error => { throw error })
)
}
}
| import { environment } from '../../environments/environment'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { catchError, map } from 'rxjs/operators'
@Injectable({
providedIn: 'root'
})
export class DataSubjectService {
private hostServer = environment.hostServer
private host = this.hostServer + '/rest/user'
constructor (private http: HttpClient) { }
deactivate () {
return this.http.get(this.host + '/erasure-request').pipe(
map((response: any) => response),
catchError(error => { throw error })
)
}
}
| Fix endpoint name for data erasure request API | Fix endpoint name for data erasure request API
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -10,7 +10,7 @@
export class DataSubjectService {
private hostServer = environment.hostServer
- private host = this.hostServer + '/api/user'
+ private host = this.hostServer + '/rest/user'
constructor (private http: HttpClient) { }
|
6c4a99732dbe67316348be6b5c13b8ced3c6f214 | src/index.ts | src/index.ts | export {
DEFAULT_BRANCH_NAME,
StateProps,
DispatchProps,
Props,
UIStateBranch,
DefaultStoreState,
Id,
TransformPropsFunction,
defaultUIStateBranchSelector,
uiStateSelector,
setUIStateSelector
} from './utils';
export {
SET_UI_STATE,
setUIState,
} from './actions';
export { createReducer } from './reducer';
export { defaultConnectUIState, createConnectUIState } from './connectUIState';
| export {
IdFunction,
Id,
idIsString,
idIsFunction,
getStringFromId,
DefaultStoreState,
UIStateBranch,
StateProps,
DispatchProps,
Props,
AbstractWrappedComponent,
WrappedComponentWithoutTransform,
WrappedComponentWithTransform,
UIStateBranchSelector,
UIStateIdProps,
SetUIStateFunction,
TransformPropsFunction,
DEFAULT_BRANCH_NAME,
stateSelector,
propsSelector,
defaultUIStateBranchSelector,
UIStateBranchSelectorSelectorProps,
uiStateBranchSelectorSelector,
uiStateBranchSelector,
idSelector,
uiStateSelector,
setUIStateSelector
} from './utils';
export {
ModifyUIStateActionPayload,
ModifyUIStateAction,
SET_UI_STATE,
setUIState,
} from './actions';
export { createReducer } from './reducer';
export { createConnectUIState, defaultConnectUIState } from './connectUIState';
| Add all util exports to export aggregator | Add all util exports to export aggregator
| TypeScript | mit | jamiecopeland/redux-ui-state,jamiecopeland/redux-ui-state | ---
+++
@@ -1,21 +1,39 @@
export {
- DEFAULT_BRANCH_NAME,
+ IdFunction,
+ Id,
+ idIsString,
+ idIsFunction,
+ getStringFromId,
+ DefaultStoreState,
+ UIStateBranch,
StateProps,
DispatchProps,
Props,
- UIStateBranch,
- DefaultStoreState,
- Id,
+ AbstractWrappedComponent,
+ WrappedComponentWithoutTransform,
+ WrappedComponentWithTransform,
+ UIStateBranchSelector,
+ UIStateIdProps,
+ SetUIStateFunction,
TransformPropsFunction,
+ DEFAULT_BRANCH_NAME,
+ stateSelector,
+ propsSelector,
defaultUIStateBranchSelector,
+ UIStateBranchSelectorSelectorProps,
+ uiStateBranchSelectorSelector,
+ uiStateBranchSelector,
+ idSelector,
uiStateSelector,
setUIStateSelector
} from './utils';
export {
+ ModifyUIStateActionPayload,
+ ModifyUIStateAction,
SET_UI_STATE,
setUIState,
} from './actions';
export { createReducer } from './reducer';
-export { defaultConnectUIState, createConnectUIState } from './connectUIState';
+export { createConnectUIState, defaultConnectUIState } from './connectUIState'; |
015bf6ceb01e7feb62706fe72a918d00f91a84a1 | helpers/coreInterfaces.ts | helpers/coreInterfaces.ts | /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: String
password: String
loginDetails?: Object
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
export interface ConnectionMap {
[name: string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectOptions(options?: any): ConnectOptions {
let defaults: ConnectOptions = {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
let opts = options || {};
return angular.extend(defaults, opts);
}
}
| /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: string
password: string
loginDetails?: any
token?: string
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
export interface ConnectionMap {
[name: string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectOptions(options?: any): ConnectOptions {
let defaults: ConnectOptions = {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
let opts = options || {};
return angular.extend(defaults, opts);
}
}
| Add optional 'token' property to UserDetails | Add optional 'token' property to UserDetails
| TypeScript | apache-2.0 | hawtio/hawtio-utilities,hawtio/hawtio-utilities,hawtio/hawtio-utilities | ---
+++
@@ -6,9 +6,10 @@
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
- username: String
- password: String
- loginDetails?: Object
+ username: string
+ password: string
+ loginDetails?: any
+ token?: string
}
/** |
0cbcc12abf09c58ff08ee044a4cef641eab63cd9 | app/services/instagram.ts | app/services/instagram.ts | import {XHR} from '../libs/xhr';
let ENDPOINT = 'api.instagram.com'
let API_VERSION = 'v1'
let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
endpoint: string;
protocol: string;
token: string;
xhr: XHR;
constructor() {
this.protocol = 'https://'
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){
let url = '/tags/' + tag + '/media/recent';
return this.xhr.get(this.protocol + this.endpoint + url).then(console.log.bind(console))
}
} | import {XHR} from '../libs/xhr';
let ENDPOINT = 'api.instagram.com'
let API_VERSION = 'v1'
let ACCESS_TOKEN = '31003280.5c1de8f.3e76027eeefe429ba5cc90f0e64ccda0'
let CLIENT_ID = '5c1de8fe2653445489b480a72803a44c'
export class InstagramClient {
endpoint: string;
protocol: string;
token: string;
xhr: XHR;
constructor() {
this.protocol = 'https://'
this.xhr = new XHR();
this.endpoint = [this.protocol, ENDPOINT, API_VERSION].join('/')
}
getMedias(tag){
let ref = `/tags/${tag}/media/recent?access_token=${ACCESS_TOKEN}`
return this.xhr.get(this.endpoint + ref).then(console.log.bind(console))
}
} | Use template string with ACCESS_TOKEN | Use template string with ACCESS_TOKEN
| TypeScript | mit | yadomi/lastagram,yadomi/lastagram,yadomi/lastagram | ---
+++
@@ -21,8 +21,8 @@
}
getMedias(tag){
- let url = '/tags/' + tag + '/media/recent';
- return this.xhr.get(this.protocol + this.endpoint + url).then(console.log.bind(console))
+ let ref = `/tags/${tag}/media/recent?access_token=${ACCESS_TOKEN}`
+ return this.xhr.get(this.endpoint + ref).then(console.log.bind(console))
}
|
7a2dc10944359b2c9a53cce48b2b83191c2b54d8 | app/core/import/native-jsonl-parser.ts | app/core/import/native-jsonl-parser.ts | import {Observable} from 'rxjs/Observable';
import {Document} from 'idai-components-2/core';
import {M} from '../../m';
import {AbstractParser} from './abstract-parser';
import {Observer} from 'rxjs/Observer';
/**
* @author Sebastian Cuy
* @author Jan G. Wieners
*/
export class NativeJsonlParser extends AbstractParser {
public parse(content: string): Observable<Document> {
this.warnings = [];
return Observable.create((observer: Observer<any>) => {
NativeJsonlParser.parseContent(content, observer, NativeJsonlParser.makeDoc);
observer.complete();
});
}
private static makeDoc(line: string) {
let resource = JSON.parse(line);
if (!resource.relations) resource.relations = {};
return { resource: resource };
}
private static parseContent(content: string, observer: any, makeDocFun: Function) {
let lines = content.split('\n');
let len = lines.length;
for (let i = 0; i < len; i++) {
try {
if (lines[i].length > 0) observer.next(makeDocFun(lines[i]));
} catch (e) {
console.error('parse content error. reason: ', e);
observer.error([M.IMPORT_FAILURE_INVALIDJSONL, i + 1]);
break;
}
}
}
} | import {Observable} from 'rxjs/Observable';
import {Document} from 'idai-components-2/core';
import {M} from '../../m';
import {AbstractParser} from './abstract-parser';
import {Observer} from 'rxjs/Observer';
/**
* @author Sebastian Cuy
* @author Jan G. Wieners
*/
export class NativeJsonlParser extends AbstractParser {
public parse(content: string): Observable<Document> {
this.warnings = [];
return Observable.create((observer: Observer<any>) => {
NativeJsonlParser.parseContent(content, observer, NativeJsonlParser.makeDoc);
observer.complete();
});
}
private static makeDoc(line: string) {
const resource = JSON.parse(line);
if (!resource.relations) resource.relations = {};
return { resource: resource };
}
private static parseContent(content: string, observer: any, makeDocFun: Function) {
const lines = content.split('\n');
const len = lines.length;
for (let i = 0; i < len; i++) {
try {
if (lines[i].length > 0) observer.next(makeDocFun(lines[i]));
} catch (e) {
console.error('parse content error. reason: ', e);
observer.error([M.IMPORT_FAILURE_INVALIDJSONL, i + 1]);
break;
}
}
}
} | Use const instead of let | Use const instead of let
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -23,7 +23,7 @@
private static makeDoc(line: string) {
- let resource = JSON.parse(line);
+ const resource = JSON.parse(line);
if (!resource.relations) resource.relations = {};
return { resource: resource };
@@ -32,8 +32,8 @@
private static parseContent(content: string, observer: any, makeDocFun: Function) {
- let lines = content.split('\n');
- let len = lines.length;
+ const lines = content.split('\n');
+ const len = lines.length;
for (let i = 0; i < len; i++) {
|
a4acbb6e2a92805dbf6819484ae261eb675ef6fe | ts/Tracker.ts | ts/Tracker.ts | /// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/knockout/knockout.d.ts" />
/// <reference path="../typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="../typings/mousetrap/mousetrap.d.ts" />
/// <reference path="../typings/socket.io-client/socket.io-client.d.ts" />
/// <reference path="../typings/FileSaver/FileSaver.d.ts" />
module ImprovedInitiative {
$(() => {
RegisterComponents();
if ($('#tracker').length) {
var viewModel = new TrackerViewModel();
ko.applyBindings(viewModel, document.body);
$.ajax("../creatures/").done(viewModel.Library.AddCreaturesFromServer);
}
if ($('#playerview').length) {
var encounterId = $('html')[0].getAttribute('encounterId');
var playerViewModel = new PlayerViewModel();
playerViewModel.LoadEncounterFromServer(encounterId);
ko.applyBindings(playerViewModel, document.body);
}
if ($('#launcher').length) {
var launcherViewModel = new LauncherViewModel();
ko.applyBindings(launcherViewModel, document.body);
}
});
} | /// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/knockout/knockout.d.ts" />
/// <reference path="../typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="../typings/mousetrap/mousetrap.d.ts" />
/// <reference path="../typings/socket.io-client/socket.io-client.d.ts" />
/// <reference path="../typings/FileSaver/FileSaver.d.ts" />
module ImprovedInitiative {
$(() => {
RegisterComponents();
if ($('#tracker').length) {
var viewModel = new TrackerViewModel();
ko.applyBindings(viewModel, document.body);
$.ajax("../creatures/").done(viewModel.Library.AddCreaturesFromServer);
}
if ($('#playerview').length) {
var encounterId = $('html')[0].getAttribute('encounterId');
var playerViewModel = new PlayerViewModel();
playerViewModel.LoadEncounterFromServer(encounterId);
ko.applyBindings(playerViewModel, document.body);
}
if ($('#landing').length) {
var launcherViewModel = new LauncherViewModel();
ko.applyBindings(launcherViewModel, document.body);
}
});
} | Correct ID for launcher binding | Correct ID for launcher binding
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -19,7 +19,7 @@
playerViewModel.LoadEncounterFromServer(encounterId);
ko.applyBindings(playerViewModel, document.body);
}
- if ($('#launcher').length) {
+ if ($('#landing').length) {
var launcherViewModel = new LauncherViewModel();
ko.applyBindings(launcherViewModel, document.body);
} |
3a201597b5c1d75fbd157ee993ab9f7b838c3416 | packages/language-server-ruby/src/CapabilityCalculator.ts | packages/language-server-ruby/src/CapabilityCalculator.ts | /**
* CapabilityCalculator
*/
import {
ClientCapabilities,
ServerCapabilities,
TextDocumentSyncKind,
} from 'vscode-languageserver';
export class CapabilityCalculator {
public clientCapabilities: ClientCapabilities;
public capabilities: ServerCapabilities;
constructor(clientCapabilities: ClientCapabilities) {
this.clientCapabilities = clientCapabilities;
this.calculateCapabilities();
}
private calculateCapabilities(): void {
this.capabilities = {
// Perform incremental syncs
// Incremental sync is disabled for now due to not being able to get the
// old text
// textDocumentSync: TextDocumentSyncKind.Incremental,
textDocumentSync: TextDocumentSyncKind.Full,
documentFormattingProvider: true,
documentRangeFormattingProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
foldingRangeProvider: true,
};
if (this.clientCapabilities.workspace && this.clientCapabilities.workspace.workspaceFolders) {
this.capabilities.workspace = {
workspaceFolders: {
supported: true,
changeNotifications: true,
},
};
}
}
}
| /**
* CapabilityCalculator
*/
import {
ClientCapabilities,
ServerCapabilities,
TextDocumentSyncKind,
} from 'vscode-languageserver';
export class CapabilityCalculator {
public clientCapabilities: ClientCapabilities;
public capabilities: ServerCapabilities;
constructor(clientCapabilities: ClientCapabilities) {
this.clientCapabilities = clientCapabilities;
this.calculateCapabilities();
}
get supportsWorkspaceFolders(): boolean {
return (
this.clientCapabilities.workspace && !!this.clientCapabilities.workspace.workspaceFolders
);
}
get supportsWorkspaceConfiguration(): boolean {
return this.clientCapabilities.workspace && !!this.clientCapabilities.workspace.configuration;
}
private calculateCapabilities(): void {
this.capabilities = {
// Perform incremental syncs
// Incremental sync is disabled for now due to not being able to get the
// old text
// textDocumentSync: TextDocumentSyncKind.Incremental,
textDocumentSync: TextDocumentSyncKind.Full,
documentFormattingProvider: true,
documentRangeFormattingProvider: true,
documentHighlightProvider: true,
documentSymbolProvider: true,
foldingRangeProvider: true,
};
if (this.clientCapabilities.workspace && this.clientCapabilities.workspace.workspaceFolders) {
this.capabilities.workspace = {
workspaceFolders: {
supported: true,
changeNotifications: true,
},
};
}
}
}
| Add getters for workspace folder and configuration support to capability calculator | Add getters for workspace folder and configuration support to capability calculator
| TypeScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -15,6 +15,16 @@
constructor(clientCapabilities: ClientCapabilities) {
this.clientCapabilities = clientCapabilities;
this.calculateCapabilities();
+ }
+
+ get supportsWorkspaceFolders(): boolean {
+ return (
+ this.clientCapabilities.workspace && !!this.clientCapabilities.workspace.workspaceFolders
+ );
+ }
+
+ get supportsWorkspaceConfiguration(): boolean {
+ return this.clientCapabilities.workspace && !!this.clientCapabilities.workspace.configuration;
}
private calculateCapabilities(): void { |
8860130daf8e216d674d072497c0136954af20f9 | src/utils/key-bindings.ts | src/utils/key-bindings.ts | import fs from 'fs';
import Mousetrap from 'mousetrap';
import { Commands, defaultPaths } from '../defaults';
import { KeyBinding } from '../interfaces';
import { getPath } from './paths';
const defaultKeyBindings = require('../../static/defaults/key-bindings.json');
export const bindKeys = (bindings: KeyBinding[], reset = true) => {
Mousetrap.reset();
for (let i = 0; i < bindings.length; i++) {
const binding = bindings[i];
const digitIndex = binding.key.indexOf('digit');
if (digitIndex === -1) {
Mousetrap.bind(binding.key, Commands[binding.command]);
} else {
const firstPart = binding.key.substring(0, digitIndex);
for (let x = 0; x <= 9; x++) {
Mousetrap.bind(firstPart + x, Commands[binding.command]);
}
}
}
};
export const getKeyBindings = async () => {
const list: KeyBinding[] = [];
const data = fs.readFileSync(getPath(defaultPaths.keyBindings), 'utf8');
const userBindings = JSON.parse(data);
for (const binding of defaultKeyBindings as KeyBinding[]) {
const userBinding: KeyBinding = userBindings.filter(
(r: any) => r.command === binding.command,
)[0];
if (userBinding != null) binding.key = userBinding.key;
binding.isChanged = userBinding != null;
list.push(binding as KeyBinding);
}
return list;
};
| import fs from 'fs';
import Mousetrap from 'mousetrap';
import { Commands, defaultPaths } from '../defaults';
import { KeyBinding } from '../interfaces';
import { getPath } from './paths';
const defaultKeyBindings = require('../../static/defaults/key-bindings.json');
export const bindKeys = (bindings: KeyBinding[]) => {
for (const binding of bindings) {
if (!binding.key.includes('digit')) {
Mousetrap.bind(binding.key, Commands[binding.command]);
} else {
for (let i = 0; i <= 9; i++) {
Mousetrap.bind(
binding.key.replace('digit', i),
Commands[binding.command],
);
}
}
}
};
export const getKeyBindings = async () => {
const list: KeyBinding[] = [];
const data = fs.readFileSync(getPath(defaultPaths.keyBindings), 'utf8');
const userBindings = JSON.parse(data);
for (const binding of defaultKeyBindings as KeyBinding[]) {
const userBinding: KeyBinding = userBindings.filter(
(r: any) => r.command === binding.command,
)[0];
if (userBinding != null) binding.key = userBinding.key;
binding.isChanged = userBinding != null;
list.push(binding as KeyBinding);
}
return list;
};
| Rewrite bindKeys function in utils | Rewrite bindKeys function in utils
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -7,20 +7,16 @@
const defaultKeyBindings = require('../../static/defaults/key-bindings.json');
-export const bindKeys = (bindings: KeyBinding[], reset = true) => {
- Mousetrap.reset();
-
- for (let i = 0; i < bindings.length; i++) {
- const binding = bindings[i];
- const digitIndex = binding.key.indexOf('digit');
-
- if (digitIndex === -1) {
+export const bindKeys = (bindings: KeyBinding[]) => {
+ for (const binding of bindings) {
+ if (!binding.key.includes('digit')) {
Mousetrap.bind(binding.key, Commands[binding.command]);
} else {
- const firstPart = binding.key.substring(0, digitIndex);
-
- for (let x = 0; x <= 9; x++) {
- Mousetrap.bind(firstPart + x, Commands[binding.command]);
+ for (let i = 0; i <= 9; i++) {
+ Mousetrap.bind(
+ binding.key.replace('digit', i),
+ Commands[binding.command],
+ );
}
}
} |
65793e16b9e98d891a7d217b96a5391b00e1ed82 | packages/components/components/orderableTable/OrderableTableRow.tsx | packages/components/components/orderableTable/OrderableTableRow.tsx | import { ReactNode } from 'react';
import Icon from '../icon/Icon';
import { TableRow } from '../table';
import { OrderableElement, OrderableHandle } from '../orderable';
interface Props {
index: number;
className?: string;
cells?: ReactNode[];
}
const OrderableTableRow = ({ index, cells = [], className, ...rest }: Props) => (
<OrderableElement index={index}>
<TableRow
cells={[
<OrderableHandle key="icon">
<span className="flex" data-testid="table:order-icon">
<Icon className="mtauto mbauto cursor-row-resize" name="align-justify" />
</span>
</OrderableHandle>,
...cells,
]}
className={className}
{...rest}
/>
</OrderableElement>
);
export default OrderableTableRow;
| import { ReactNode } from 'react';
import Icon from '../icon/Icon';
import { TableRow } from '../table';
import { OrderableElement, OrderableHandle } from '../orderable';
interface Props {
index: number;
className?: string;
cells?: ReactNode[];
disableSort?: boolean;
}
const OrderableTableRow = ({ index, cells = [], className, disableSort, ...rest }: Props) => {
if (disableSort) {
return <TableRow cells={['', ...cells]} className={className} {...rest} />;
}
return (
<OrderableElement index={index}>
<TableRow
cells={[
<OrderableHandle key="icon">
<span className="flex" data-testid="table:order-icon">
<Icon className="mtauto mbauto cursor-row-resize" name="align-justify" />
</span>
</OrderableHandle>,
...cells,
]}
className={className}
{...rest}
/>
</OrderableElement>
);
};
export default OrderableTableRow;
| Add ability to disable rows from being sorted | Add ability to disable rows from being sorted
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -7,23 +7,30 @@
index: number;
className?: string;
cells?: ReactNode[];
+ disableSort?: boolean;
}
-const OrderableTableRow = ({ index, cells = [], className, ...rest }: Props) => (
- <OrderableElement index={index}>
- <TableRow
- cells={[
- <OrderableHandle key="icon">
- <span className="flex" data-testid="table:order-icon">
- <Icon className="mtauto mbauto cursor-row-resize" name="align-justify" />
- </span>
- </OrderableHandle>,
- ...cells,
- ]}
- className={className}
- {...rest}
- />
- </OrderableElement>
-);
+const OrderableTableRow = ({ index, cells = [], className, disableSort, ...rest }: Props) => {
+ if (disableSort) {
+ return <TableRow cells={['', ...cells]} className={className} {...rest} />;
+ }
+
+ return (
+ <OrderableElement index={index}>
+ <TableRow
+ cells={[
+ <OrderableHandle key="icon">
+ <span className="flex" data-testid="table:order-icon">
+ <Icon className="mtauto mbauto cursor-row-resize" name="align-justify" />
+ </span>
+ </OrderableHandle>,
+ ...cells,
+ ]}
+ className={className}
+ {...rest}
+ />
+ </OrderableElement>
+ );
+};
export default OrderableTableRow; |
9a9467d9de7626017bbaba35c31f32aafc392887 | src/DiplomContentSystem/ClientApp/app/app.module.ts | src/DiplomContentSystem/ClientApp/app/app.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './app.component'
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { AppRoutesModule } from './app-route.module';
import { SharedModule } from './shared/shared.module';
import { TeacherService } from './teacher/teacher.service';
import { TeachersModule } from './teacher/teacher.module';
import { SignInComponent } from './login/components/sign-in.component';
import { StudentsModule } from './student/student.module';
import { DiplomWorksModule } from './diplomWorks/diplom-works.module';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
CounterComponent,
FetchDataComponent,
HomeComponent,
SignInComponent
],
imports: [
UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
AppRoutesModule,
SharedModule,
TeachersModule,
StudentsModule,
DiplomWorksModule
],
})
export class AppModule {
}
| import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './app.component'
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { AppRoutesModule } from './app-route.module';
import { SharedModule } from './shared/shared.module';
import { TeacherService } from './teacher/teacher.service';
import { TeachersModule } from './teacher/teacher.module';
import { SignInComponent } from './login/components/sign-in.component';
import { StudentsModule } from './student/student.module';
import { DiplomWorksModule } from './diplomWorks/diplom-works.module';
import { GroupModule } from './group/group.module';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
CounterComponent,
FetchDataComponent,
HomeComponent,
SignInComponent
],
imports: [
UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
AppRoutesModule,
SharedModule,
TeachersModule,
StudentsModule,
DiplomWorksModule,
GroupModule
],
})
export class AppModule {
}
| Use Group Module inside AppModule | DCS-30: Use Group Module inside AppModule
| TypeScript | apache-2.0 | denismaster/DiplomContentSystem,denismaster/DiplomContentSystem,denismaster/DiplomContentSystem,denismaster/DiplomContentSystem | ---
+++
@@ -12,6 +12,7 @@
import { SignInComponent } from './login/components/sign-in.component';
import { StudentsModule } from './student/student.module';
import { DiplomWorksModule } from './diplomWorks/diplom-works.module';
+import { GroupModule } from './group/group.module';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
@@ -27,7 +28,8 @@
SharedModule,
TeachersModule,
StudentsModule,
- DiplomWorksModule
+ DiplomWorksModule,
+ GroupModule
],
})
export class AppModule { |
4a3a2653ba13237f119742c559ffcbf91bb34877 | src/app/components/client/local-db/local-db.service.ts | src/app/components/client/local-db/local-db.service.ts | import { LocalDbGame } from './game/game.model';
import { LocalDbPackage } from './package/package.model';
import * as path from 'path';
import { Collection } from './collection';
export class LocalDb {
readonly games: Collection<LocalDbGame>;
readonly packages: Collection<LocalDbPackage>;
private static _instance: Promise<LocalDb> | null = null;
private constructor() {
const dataPath = nw.App.dataPath;
this.games = new Collection<LocalDbGame>(1, path.join(dataPath, 'games.wttf'), LocalDbGame);
this.packages = new Collection<LocalDbPackage>(
1,
path.join(dataPath, 'packages.wttf'),
LocalDbPackage
);
this.packages.defineGroup('game_id');
}
static instance() {
if (!this._instance) {
console.log('new localdb');
const db = new LocalDb();
this._instance = Promise.all([db.games.load()]).then(() => db);
}
return this._instance;
}
}
| import { LocalDbGame } from './game/game.model';
import { LocalDbPackage } from './package/package.model';
import * as path from 'path';
import { Collection } from './collection';
export class LocalDb {
readonly games: Collection<LocalDbGame>;
readonly packages: Collection<LocalDbPackage>;
private static _instance: Promise<LocalDb> | null = null;
private constructor() {
const dataPath = nw.App.dataPath;
this.games = new Collection<LocalDbGame>(1, path.join(dataPath, 'games.wttf'), LocalDbGame);
this.packages = new Collection<LocalDbPackage>(
1,
path.join(dataPath, 'packages.wttf'),
LocalDbPackage
);
this.packages.defineGroup('game_id');
}
static instance() {
if (!this._instance) {
console.log('new localdb');
const db = new LocalDb();
this._instance = Promise.all([db.games.load(), db.packages.load()]).then(() => db);
}
return this._instance;
}
}
| Make localdb manage packages again | Make localdb manage packages again
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -25,7 +25,7 @@
if (!this._instance) {
console.log('new localdb');
const db = new LocalDb();
- this._instance = Promise.all([db.games.load()]).then(() => db);
+ this._instance = Promise.all([db.games.load(), db.packages.load()]).then(() => db);
}
return this._instance; |
8c450dc81dd08c12c2dc55ec3ad16e3021599a14 | src/cmds/start/storybook.cmd.ts | src/cmds/start/storybook.cmd.ts | import {
constants,
execAsync,
fs,
fsPath,
printTitle,
} from '../../common';
export const group = 'start';
export const name = 'storybook';
export const alias = 'ui';
export const description = 'Starts React Storybook.';
export async function cmd() {
printTitle('StoryBook: Client Module');
const path = fsPath.join(constants.LIBS_DIR, 'client');
cleanDebugLog(path);
await execAsync(`cd ${ path } && npm run ui`);
}
function cleanDebugLog(folder: string) {
fs
.readdirSync(folder)
.filter(name => name.startsWith('npm-debug.log'))
.map(name => fsPath.join(folder, name))
.forEach(path => fs.removeSync(path));
}
| import { fetchToken } from '../../common/fetch-auth-token';
import { execaCommand, IExecOptions } from '../../common/util';
import {
constants,
execAsync,
fs,
fsPath,
printTitle,
log,
} from '../../common';
export const group = 'start';
export const name = 'storybook';
export const alias = 'ui';
export const description = 'Starts React Storybook.';
export async function cmd(args: {
options: {
noAuth: boolean,
},
}) {
printTitle('StoryBook: Client Module');
const path = fsPath.join(constants.LIBS_DIR, 'client');
cleanDebugLog(path);
let authToken: string | null | undefined;
if (!args.options.noAuth) {
authToken = await fetchToken();
}
let cmd: string = '';
if (authToken) { cmd += `export STORYBOOK_ID_TOKEN=${authToken} && `; }
cmd += `cd ${path} && yarn run ui`;
log.info.green(cmd);
await execAsync(cmd);
}
function cleanDebugLog(folder: string) {
fs
.readdirSync(folder)
.filter((name) => name.startsWith('npm-debug.log'))
.map((name) => fsPath.join(folder, name))
.forEach((path) => fs.removeSync(path));
}
| Make storybook load a token before starting | Make storybook load a token before starting
| TypeScript | mit | frederickfogerty/js-cli,frederickfogerty/js-cli,frederickfogerty/js-cli | ---
+++
@@ -1,29 +1,47 @@
+import { fetchToken } from '../../common/fetch-auth-token';
+import { execaCommand, IExecOptions } from '../../common/util';
import {
- constants,
- execAsync,
- fs,
- fsPath,
- printTitle,
+ constants,
+ execAsync,
+ fs,
+ fsPath,
+ printTitle,
+ log,
} from '../../common';
-
export const group = 'start';
export const name = 'storybook';
export const alias = 'ui';
export const description = 'Starts React Storybook.';
-export async function cmd() {
- printTitle('StoryBook: Client Module');
- const path = fsPath.join(constants.LIBS_DIR, 'client');
- cleanDebugLog(path);
- await execAsync(`cd ${ path } && npm run ui`);
+export async function cmd(args: {
+ options: {
+ noAuth: boolean,
+ },
+}) {
+ printTitle('StoryBook: Client Module');
+ const path = fsPath.join(constants.LIBS_DIR, 'client');
+ cleanDebugLog(path);
+
+ let authToken: string | null | undefined;
+ if (!args.options.noAuth) {
+ authToken = await fetchToken();
+ }
+
+ let cmd: string = '';
+ if (authToken) { cmd += `export STORYBOOK_ID_TOKEN=${authToken} && `; }
+ cmd += `cd ${path} && yarn run ui`;
+
+ log.info.green(cmd);
+
+ await execAsync(cmd);
}
function cleanDebugLog(folder: string) {
- fs
- .readdirSync(folder)
- .filter(name => name.startsWith('npm-debug.log'))
- .map(name => fsPath.join(folder, name))
- .forEach(path => fs.removeSync(path));
+ fs
+ .readdirSync(folder)
+ .filter((name) => name.startsWith('npm-debug.log'))
+ .map((name) => fsPath.join(folder, name))
+ .forEach((path) => fs.removeSync(path));
} |
8f67bd93a01eb0a5aa263f7e4cd9ab6460e5f5b4 | app/desktop/electron.ts | app/desktop/electron.ts | const electron = (<any>window).require('electron');
export const {BrowserWindowProxy} = electron;
export const {desktopCapturer} = electron;
export const {ipcRenderer} = electron;
export const {remote} = electron;
export const {webFrame} = electron;
export const {NativeImage} = electron; | const electron = (<any>window).require('electron');
export const {BrowserWindowProxy} = electron;
export const {desktopCapturer} = electron;
export const {ipcRenderer} = electron;
export const {remote} = electron;
export const {webFrame} = electron;
export const {nativeImage} = electron | Fix runtime error preventing img upload. | Fix runtime error preventing img upload.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -5,4 +5,4 @@
export const {ipcRenderer} = electron;
export const {remote} = electron;
export const {webFrame} = electron;
-export const {NativeImage} = electron;
+export const {nativeImage} = electron |
066c9a820e6a25c5f9f4f22a9e76ba05079d0dd6 | src/builders/database-builder.ts | src/builders/database-builder.ts | import { AuthMode, default as Apps } from '../apps';
import DatabaseDeltaSnapshot from '../database/delta-snapshot';
import { Event } from '../event';
import { FunctionBuilder, TriggerDefinition, CloudFunction } from '../builder';
import { normalizePath } from '../utils';
import { FirebaseEnv } from '../env';
export interface DatabaseTriggerDefinition extends TriggerDefinition {
path: string;
}
export interface DatabaseEventData {
data: any;
delta: any;
}
export interface DatabaseEvent extends Event<DatabaseEventData> {
auth: AuthMode;
}
export default class DatabaseBuilder extends FunctionBuilder {
private _path: string;
private _apps: Apps;
constructor(env: FirebaseEnv, apps: Apps) {
super(env);
this._apps = apps;
}
path(path: string): DatabaseBuilder {
this._path = this._path || '';
this._path += normalizePath(path);
return this;
}
onWrite(
handler: (event: Event<DatabaseDeltaSnapshot>) => PromiseLike<any> | any
): CloudFunction {
if (!this._path) {
throw new Error('Must call .path(pathValue) before .on() for database function definitions.');
}
return this._makeHandler(handler, 'data.write');
}
protected _toTrigger(event?: string): DatabaseTriggerDefinition {
return {
service: 'firebase.database',
event: 'write',
path: this._path,
};
}
protected _dataConstructor(payload: any): DatabaseDeltaSnapshot {
return new DatabaseDeltaSnapshot(this._apps, payload);
}
}
| import { AuthMode, default as Apps } from '../apps';
import DatabaseDeltaSnapshot from '../database/delta-snapshot';
import { Event } from '../event';
import { FunctionBuilder, TriggerDefinition, CloudFunction } from '../builder';
import { normalizePath } from '../utils';
import { FirebaseEnv } from '../env';
export interface DatabaseTriggerDefinition extends TriggerDefinition {
path: string;
}
export interface DatabaseEventData {
data: any;
delta: any;
}
export interface DatabaseEvent extends Event<DatabaseEventData> {
auth: AuthMode;
}
export default class DatabaseBuilder extends FunctionBuilder {
private _path: string;
private _apps: Apps;
constructor(env: FirebaseEnv, apps: Apps) {
super(env);
this._apps = apps;
}
path(path: string): DatabaseBuilder {
this._path = this._path || '';
this._path += normalizePath(path);
return this;
}
onWrite(
handler: (event: Event<DatabaseDeltaSnapshot>) => PromiseLike<any> | any
): CloudFunction {
if (!this._path) {
throw new Error('Must call .path(pathValue) before .onWrite() for database function definitions.');
}
return this._makeHandler(handler, 'data.write');
}
protected _toTrigger(event?: string): DatabaseTriggerDefinition {
return {
service: 'firebase.database',
event: 'write',
path: this._path,
};
}
protected _dataConstructor(payload: any): DatabaseDeltaSnapshot {
return new DatabaseDeltaSnapshot(this._apps, payload);
}
}
| Fix a stale error message: users now use .onWrite() rather than .on() | Fix a stale error message: users now use .onWrite() rather than .on()
| TypeScript | mit | firebase/firebase-functions,firebase/firebase-functions,firebase/firebase-functions | ---
+++
@@ -37,7 +37,7 @@
handler: (event: Event<DatabaseDeltaSnapshot>) => PromiseLike<any> | any
): CloudFunction {
if (!this._path) {
- throw new Error('Must call .path(pathValue) before .on() for database function definitions.');
+ throw new Error('Must call .path(pathValue) before .onWrite() for database function definitions.');
}
return this._makeHandler(handler, 'data.write');
} |
971220a874bcd496ca6c7b1f3002747ead450932 | src/views/css/functions.ts | src/views/css/functions.ts | const tinyColor: any = require("tinycolor2");
export function lighten(color: string, percent: number) {
return tinyColor(color).lighten(percent).toHexString();
}
export function darken(color: string, percent: number) {
return tinyColor(color).darken(percent).toHexString();
}
export function alpha(color: string, percent: number) {
return tinyColor(color).setAlpha(percent).toRgbString();
}
export function failurize(color: string) {
return tinyColor(color).spin(140).saturate(20).toHexString();
}
export function toDOMString(pixels: number) {
return `${pixels}px`;
}
| const tinyColor: any = require("tinycolor2");
export function lighten(color: string, percent: number) {
return tinyColor(color).lighten(percent).toHexString();
}
export function darken(color: string, percent: number) {
return tinyColor(color).darken(percent).toHexString();
}
export function alpha(color: string, percent: number) {
return tinyColor(color).setAlpha(percent).toRgbString();
}
export function failurize(color: string) {
return tinyColor(color).spin(140).saturate(15).toHexString();
}
export function toDOMString(pixels: number) {
return `${pixels}px`;
}
| Make failurized color less bright. | Make failurized color less bright.
| TypeScript | mit | vshatskyi/black-screen,railsware/upterm,vshatskyi/black-screen,vshatskyi/black-screen,j-allard/black-screen,shockone/black-screen,j-allard/black-screen,black-screen/black-screen,black-screen/black-screen,drew-gross/black-screen,shockone/black-screen,j-allard/black-screen,black-screen/black-screen,drew-gross/black-screen,drew-gross/black-screen,railsware/upterm,drew-gross/black-screen,vshatskyi/black-screen | ---
+++
@@ -13,7 +13,7 @@
}
export function failurize(color: string) {
- return tinyColor(color).spin(140).saturate(20).toHexString();
+ return tinyColor(color).spin(140).saturate(15).toHexString();
}
export function toDOMString(pixels: number) { |
4e6f4be6cce7e9b99cc894fbce4b23869dc5ebe3 | src/common/EventEmitter2.ts | src/common/EventEmitter2.ts | /**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { IDisposable } from './Types';
type Listener<T> = (e: T) => void;
export interface IEvent<T> {
(listener: (e: T) => any): IDisposable;
}
export class EventEmitter2<T> {
private _listeners: Listener<T>[] = [];
private _event?: IEvent<T>;
public get event(): IEvent<T> {
if (!this._event) {
this._event = (listener: (e: T) => any) => {
this._listeners.push(listener);
const disposable = {
dispose: () => {
for (let i = 0; i < this._listeners.length; i++) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
return;
}
}
}
};
return disposable;
};
}
return this._event;
}
public fire(data: T): void {
const queue: Listener<T>[] = [];
for (let i = 0; i < this._listeners.length; i++) {
queue.push(this._listeners[i]);
}
for (let i = 0; i < queue.length; i++) {
queue[i].call(undefined, data);
}
}
}
| /**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { IDisposable } from './Types';
interface IListener<T> {
(e: T): void;
}
export interface IEvent<T> {
(listener: (e: T) => any): IDisposable;
}
export class EventEmitter2<T> {
private _listeners: IListener<T>[] = [];
private _event?: IEvent<T>;
public get event(): IEvent<T> {
if (!this._event) {
this._event = (listener: (e: T) => any) => {
this._listeners.push(listener);
const disposable = {
dispose: () => {
for (let i = 0; i < this._listeners.length; i++) {
if (this._listeners[i] === listener) {
this._listeners.splice(i, 1);
return;
}
}
}
};
return disposable;
};
}
return this._event;
}
public fire(data: T): void {
const queue: IListener<T>[] = [];
for (let i = 0; i < this._listeners.length; i++) {
queue.push(this._listeners[i]);
}
for (let i = 0; i < queue.length; i++) {
queue[i].call(undefined, data);
}
}
}
| Convert Listener to an interface | Convert Listener to an interface
| TypeScript | mit | sourcelair/xterm.js,xtermjs/xterm.js,xtermjs/xterm.js,xtermjs/xterm.js,sourcelair/xterm.js,Tyriar/xterm.js,Tyriar/xterm.js,Tyriar/xterm.js,xtermjs/xterm.js,Tyriar/xterm.js,sourcelair/xterm.js,Tyriar/xterm.js,xtermjs/xterm.js,sourcelair/xterm.js | ---
+++
@@ -5,14 +5,16 @@
import { IDisposable } from './Types';
-type Listener<T> = (e: T) => void;
+interface IListener<T> {
+ (e: T): void;
+}
export interface IEvent<T> {
(listener: (e: T) => any): IDisposable;
}
export class EventEmitter2<T> {
- private _listeners: Listener<T>[] = [];
+ private _listeners: IListener<T>[] = [];
private _event?: IEvent<T>;
public get event(): IEvent<T> {
@@ -36,7 +38,7 @@
}
public fire(data: T): void {
- const queue: Listener<T>[] = [];
+ const queue: IListener<T>[] = [];
for (let i = 0; i < this._listeners.length; i++) {
queue.push(this._listeners[i]);
} |
d3c7fb65015343cc37b1a9dfbf90b6ed591a47f1 | lib/request.ts | lib/request.ts | import express = require('express');
import querystring = require('querystring');
class Request {
private req: express.Request;
constructor(req: express.Request) {
this.req = req;
}
get bodyAsText(): string {
if (this.contentType === 'application/x-www-form-urlencoded') {
return querystring.stringify(this.req.body);
} else {
return JSON.stringify(this.req.body);
}
}
get bodyAsFormUrlEncoded(): any {
return this.req.body;
}
get bodyAsJsonString(): string {
return JSON.stringify(this.req.body);
}
get bodyAsJson(): any {
return this.req.body;
}
get method(): string {
return this.req.method;
}
get uri(): string {
let tokens = this.req.path.substring(1).split('/');
tokens.splice(1, 1);
return '/' + tokens.join('/');
}
get contentType(): string {
return this.req.get('content-type');
}
get secure(): boolean {
return this.req.secure;
}
get headers(): Dict<string> {
return this.req.headers;
}
}
export = Request;
| import express = require('express');
import querystring = require('querystring');
class Request {
private req: express.Request;
constructor(req: express.Request) {
this.req = req;
}
get param(): any {
if (this.method === 'GET') {
return this.req.query;
}
return this.req.body;
}
get bodyAsText(): string {
if (this.contentType === 'application/x-www-form-urlencoded') {
return querystring.stringify(this.param);
} else {
return JSON.stringify(this.param);
}
}
get bodyAsFormUrlEncoded(): any {
return this.param;
}
get bodyAsJsonString(): string {
return JSON.stringify(this.param);
}
get bodyAsJson(): any {
return this.param;
}
get method(): string {
return this.req.method;
}
get uri(): string {
let tokens = this.req.path.substring(1).split('/');
tokens.splice(1, 1);
return '/' + tokens.join('/');
}
get contentType(): string {
return this.req.get('content-type');
}
get secure(): boolean {
return this.req.secure;
}
get headers(): Dict<string> {
return this.req.headers;
}
}
export = Request;
| Use query for GET method. | Use query for GET method.
| TypeScript | apache-2.0 | SollmoStudio/beyond.ts,noraesae/beyond.ts,sgkim126/beyond.ts,SollmoStudio/beyond.ts,sgkim126/beyond.ts,murmur76/beyond.ts,murmur76/beyond.ts,noraesae/beyond.ts | ---
+++
@@ -8,24 +8,32 @@
this.req = req;
}
+ get param(): any {
+ if (this.method === 'GET') {
+ return this.req.query;
+ }
+
+ return this.req.body;
+ }
+
get bodyAsText(): string {
if (this.contentType === 'application/x-www-form-urlencoded') {
- return querystring.stringify(this.req.body);
+ return querystring.stringify(this.param);
} else {
- return JSON.stringify(this.req.body);
+ return JSON.stringify(this.param);
}
}
get bodyAsFormUrlEncoded(): any {
- return this.req.body;
+ return this.param;
}
get bodyAsJsonString(): string {
- return JSON.stringify(this.req.body);
+ return JSON.stringify(this.param);
}
get bodyAsJson(): any {
- return this.req.body;
+ return this.param;
}
get method(): string { |
47f70d2715b13971140b86cfc0d107faee1e8919 | source/platform/module/bootstrap.ts | source/platform/module/bootstrap.ts | import 'zone.js/dist/zone-node';
import {
NgModuleFactory,
NgModuleRef,
Type
} from '@angular/core/index';
import {PlatformImpl} from '../platform';
import {browserModuleToServerModule} from '../module';
import {platformNode} from '../factory';
export type ModuleExecute<M, R> = (moduleRef: NgModuleRef<M>) => R | Promise<R>;
const platform = <PlatformImpl> platformNode();
declare const Zone;
export const forkZone = <R>(documentTemplate: string, requestUri: string, execute: () => R): R => {
const zone = Zone.current.fork({
name: requestUri,
properties: {
documentTemplate,
requestUri,
}
});
return zone.run(execute);
}
export const compileModule = async <M>(moduleType: Type<M>): Promise<NgModuleFactory<M>> => {
return await platform.compileModule(browserModuleToServerModule(moduleType), []);
};
export const bootstrapModuleFactory = async <M, R>(moduleFactory: NgModuleFactory<M>, execute: ModuleExecute<M, R>): Promise<R> => {
const moduleRef = await platform.bootstrapModuleFactory<M>(moduleFactory);
try {
const result = await Promise.resolve(execute(moduleRef));
moduleRef.destroy();
return result;
}
catch (exception) {
moduleRef.destroy();
throw exception;
}
}; | import 'zone.js/dist/zone-node';
import {
NgModuleFactory,
NgModuleRef,
Type
} from '@angular/core/index';
import {PlatformImpl} from '../platform';
import {browserModuleToServerModule} from '../module';
import {platformNode} from '../factory';
export type ModuleExecute<M, R> = (moduleRef: NgModuleRef<M>) => R | Promise<R>;
const platform = <PlatformImpl> platformNode();
declare const Zone;
export const forkZone = <R>(documentTemplate: string, requestUri: string, execute: () => R): R => {
const zone = Zone.current.fork({
name: requestUri,
properties: {
documentTemplate,
requestUri,
}
});
return zone.run(execute);
}
export const compileModule = async <M>(moduleType: Type<M>): Promise<NgModuleFactory<M>> => {
return await platform.compileModule(browserModuleToServerModule(moduleType), []);
};
export const bootstrapModuleFactory = async <M, R>(moduleFactory: NgModuleFactory<M>, execute: ModuleExecute<M, R>): Promise<R> => {
const moduleRef = await platform.bootstrapModuleFactory<M>(moduleFactory);
try {
return await Promise.resolve(execute(moduleRef));
}
finally {
moduleRef.destroy();
}
}; | Clean up the destroy pattern for NgModuleRef instances | Clean up the destroy pattern for NgModuleRef instances
| TypeScript | bsd-2-clause | clbond/angular-ssr,clbond/angular-ssr,clbond/angular-ssr,clbond/angular-ssr | ---
+++
@@ -35,12 +35,9 @@
export const bootstrapModuleFactory = async <M, R>(moduleFactory: NgModuleFactory<M>, execute: ModuleExecute<M, R>): Promise<R> => {
const moduleRef = await platform.bootstrapModuleFactory<M>(moduleFactory);
try {
- const result = await Promise.resolve(execute(moduleRef));
+ return await Promise.resolve(execute(moduleRef));
+ }
+ finally {
moduleRef.destroy();
- return result;
- }
- catch (exception) {
- moduleRef.destroy();
- throw exception;
}
}; |
17fce4a232f055f8a65081e367d2094328a8e3c3 | modules/tinymce/src/core/demo/ts/demo/TinyMceDemo.ts | modules/tinymce/src/core/demo/ts/demo/TinyMceDemo.ts | import { document } from '@ephox/dom-globals';
declare let tinymce: any;
export default function () {
const textarea = document.createElement('textarea');
textarea.innerHTML = '<p>Bolt</p>';
textarea.classList.add('tinymce');
document.querySelector('#ephox-ui').appendChild(textarea);
tinymce.init({
// imagetools_cors_hosts: ["moxiecode.cachefly.net"],
// imagetools_proxy: "proxy.php",
// imagetools_api_key: '123',
// images_upload_url: 'postAcceptor.php',
// images_upload_base_path: 'base/path',
// images_upload_credentials: true,
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
ed.ui.registry.addButton('demoButton', {
type: 'button',
text: 'Demo',
onAction() {
ed.insertContent('Hello world!');
}
});
},
selector: 'textarea.tinymce',
toolbar1: 'demoButton bold italic',
menubar: false
});
}
| import { document } from '@ephox/dom-globals';
declare let tinymce: any;
export default function () {
const textarea = document.createElement('textarea');
textarea.innerHTML = '<p>Bolt</p>';
textarea.classList.add('tinymce');
document.querySelector('#ephox-ui').appendChild(textarea);
tinymce.init({
// imagetools_cors_hosts: ["moxiecode.cachefly.net"],
// imagetools_proxy: "proxy.php",
// imagetools_api_key: '123',
// images_upload_url: 'postAcceptor.php',
// images_upload_base_path: 'base/path',
// images_upload_credentials: true,
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
ed.ui.registry.addButton('demoButton', {
text: 'Demo',
onAction() {
ed.insertContent('Hello world!');
}
});
},
selector: 'textarea.tinymce',
toolbar1: 'demoButton bold italic',
menubar: false
});
}
| Remove setting that no longer does anything. | Remove setting that no longer does anything.
| TypeScript | lgpl-2.1 | FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce,TeamupCom/tinymce,tinymce/tinymce,tinymce/tinymce | ---
+++
@@ -20,7 +20,6 @@
skin_url: '../../../../js/tinymce/skins/ui/oxide',
setup(ed) {
ed.ui.registry.addButton('demoButton', {
- type: 'button',
text: 'Demo',
onAction() {
ed.insertContent('Hello world!'); |
3ea37c4311648fe431b0444afc2e135386e710b9 | test/options/quotes.spec.ts | test/options/quotes.spec.ts | import { newUnibeautify, Beautifier } from "unibeautify";
import beautifier from "../../src";
test(`should successfully beautify JavaScript text with single quotes`, () => {
const unibeautify = newUnibeautify();
unibeautify.loadBeautifier(beautifier);
const quote = "'";
const text = `console.log('hello world');\nconsole.log("hello world");\n`;
const beautifierResult = `console.log(${quote}hello world${quote});\nconsole.log(${quote}hello world${quote});\n`;
return unibeautify
.beautify({
languageName: "JavaScript",
options: {
JavaScript: {
quotes: "single",
},
},
text,
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
test(`should successfully beautify JavaScript text with double quotes`, () => {
const unibeautify = newUnibeautify();
unibeautify.loadBeautifier(beautifier);
const quote = "'";
const text = `console.log('hello world');\nconsole.log("hello world");\n`;
const beautifierResult = `console.log(${quote}hello world${quote});\nconsole.log(${quote}hello world${quote});\n`;
return unibeautify
.beautify({
languageName: "JavaScript",
options: {
JavaScript: {
quotes: "double",
},
},
text,
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
| import { newUnibeautify, Beautifier } from "unibeautify";
import beautifier from "../../src";
test(`should successfully beautify JavaScript text with single quotes`, () => {
const unibeautify = newUnibeautify();
unibeautify.loadBeautifier(beautifier);
const quote = "'";
const text = `console.log('hello world');\nconsole.log("hello world");\n`;
const beautifierResult = `console.log(${quote}hello world${quote});\nconsole.log(${quote}hello world${quote});\n`;
return unibeautify
.beautify({
languageName: "JavaScript",
options: {
JavaScript: {
quotes: "single",
},
},
text,
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
test(`should successfully beautify JavaScript text with double quotes`, () => {
const unibeautify = newUnibeautify();
unibeautify.loadBeautifier(beautifier);
const quote = '"';
const text = `console.log('hello world');\nconsole.log("hello world");\n`;
const beautifierResult = `console.log(${quote}hello world${quote});\nconsole.log(${quote}hello world${quote});\n`;
return unibeautify
.beautify({
languageName: "JavaScript",
options: {
JavaScript: {
quotes: "double",
},
},
text,
})
.then(results => {
expect(results).toBe(beautifierResult);
});
});
| Fix double quote issue with Unibeautify CI | Fix double quote issue with Unibeautify CI
| TypeScript | mit | Unibeautify/beautifier-prettydiff,Unibeautify/beautifier-prettydiff | ---
+++
@@ -23,7 +23,7 @@
test(`should successfully beautify JavaScript text with double quotes`, () => {
const unibeautify = newUnibeautify();
unibeautify.loadBeautifier(beautifier);
- const quote = "'";
+ const quote = '"';
const text = `console.log('hello world');\nconsole.log("hello world");\n`;
const beautifierResult = `console.log(${quote}hello world${quote});\nconsole.log(${quote}hello world${quote});\n`;
return unibeautify |
944b432560c944aaf6a2d5e79444ec8647d03a16 | packages/cbioportal-clinical-timeline/src/configureTracks.ts | packages/cbioportal-clinical-timeline/src/configureTracks.ts | import React from 'react';
import {
ITimelineConfig,
ITrackEventConfig,
TimelineEvent,
TimelineTrackSpecification,
} from './types';
import _ from 'lodash';
export const configureTracks = function(
tracks: TimelineTrackSpecification[],
timelineConfig: ITimelineConfig,
parentConf?: ITrackEventConfig
) {
tracks.forEach(track => {
const conf = timelineConfig.trackEventRenderers.find(conf =>
conf.trackTypeMatch.test(track.type)
);
// add top level config to each track for later reference
track.timelineConfig = timelineConfig;
// if we have a conf, attach it to the track for later use
// otherwise, attach parentConf //
if (conf) {
track.trackConf = conf;
conf.configureTrack(track);
} else if (parentConf) {
track.trackConf = parentConf;
}
if (track.tracks && track.tracks.length) {
configureTracks(track.tracks, timelineConfig, conf || parentConf);
}
});
};
| import React from 'react';
import {
ITimelineConfig,
ITrackEventConfig,
TimelineEvent,
TimelineTrackSpecification,
} from './types';
import _ from 'lodash';
export const configureTracks = function(
tracks: TimelineTrackSpecification[],
timelineConfig: ITimelineConfig,
parentConf?: ITrackEventConfig
) {
tracks.forEach(track => {
const conf = timelineConfig.trackEventRenderers
? timelineConfig.trackEventRenderers.find(conf =>
conf.trackTypeMatch.test(track.type)
)
: undefined;
// add top level config to each track for later reference
track.timelineConfig = timelineConfig;
// if we have a conf, attach it to the track for later use
// otherwise, attach parentConf //
if (conf) {
track.trackConf = conf;
conf.configureTrack(track);
} else if (parentConf) {
track.trackConf = parentConf;
}
if (track.tracks && track.tracks.length) {
configureTracks(track.tracks, timelineConfig, conf || parentConf);
}
});
};
| Fix bug where no trackEventRenderers | Fix bug where no trackEventRenderers
Former-commit-id: 371cb9b264f32661702633739bda9d8ba178a99a | TypeScript | agpl-3.0 | cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend | ---
+++
@@ -13,9 +13,11 @@
parentConf?: ITrackEventConfig
) {
tracks.forEach(track => {
- const conf = timelineConfig.trackEventRenderers.find(conf =>
- conf.trackTypeMatch.test(track.type)
- );
+ const conf = timelineConfig.trackEventRenderers
+ ? timelineConfig.trackEventRenderers.find(conf =>
+ conf.trackTypeMatch.test(track.type)
+ )
+ : undefined;
// add top level config to each track for later reference
track.timelineConfig = timelineConfig; |
83dab92a0a15cc0b8fc1c2c0ca9a52bf4ea17286 | src/components/Renderer/types.ts | src/components/Renderer/types.ts | import { FormatValidator, FormatDefinition } from 'ajv';
import { UiSchema as rjsfUiSchema } from '@rjsf/core';
import { Widget } from './widgets/widget-util';
export { JSONSchema7 as JSONSchema } from 'json-schema';
export const JsonTypes = {
array: 'array',
object: 'object',
number: 'number',
integer: 'integer',
string: 'string',
boolean: 'boolean',
null: 'null',
} as const;
export interface JsonTypesTypeMap {
array: unknown[];
object: {};
number: number;
integer: number;
string: string;
boolean: boolean;
null: null;
}
export type DefinedValue =
| number
| string
| boolean
| { [key: string]: any }
| any[];
export type Value = DefinedValue | null;
export interface UiSchema
extends Pick<rjsfUiSchema, 'ui:options' | 'ui:order'> {
'ui:widget'?: string;
'ui:title'?: string;
'ui:description'?: string;
'ui:value'?: Value;
}
export interface Format {
name: string;
format: FormatValidator | FormatDefinition;
widget?: Widget;
}
| import { FormatValidator, FormatDefinition } from 'ajv';
import { UiSchema as rjsfUiSchema } from '@rjsf/core';
import { Widget } from './widgets/widget-util';
export type { JSONSchema7 as JSONSchema } from 'json-schema';
export const JsonTypes = {
array: 'array',
object: 'object',
number: 'number',
integer: 'integer',
string: 'string',
boolean: 'boolean',
null: 'null',
} as const;
export interface JsonTypesTypeMap {
array: unknown[];
object: {};
number: number;
integer: number;
string: string;
boolean: boolean;
null: null;
}
export type DefinedValue =
| number
| string
| boolean
| { [key: string]: any }
| any[];
export type Value = DefinedValue | null;
export interface UiSchema
extends Pick<rjsfUiSchema, 'ui:options' | 'ui:order'> {
'ui:widget'?: string;
'ui:title'?: string;
'ui:description'?: string;
'ui:value'?: Value;
}
export interface Format {
name: string;
format: FormatValidator | FormatDefinition;
widget?: Widget;
}
| Fix storybook issue trying to import type only json-schema package | Fix storybook issue trying to import type only json-schema package
Change-type: patch
See: https://www.flowdock.com/app/rulemotion/f-rendition/threads/vX8HYnTNYCHgAWMbkVOUFR0oA_e
Signed-off-by: Thodoris Greasidis <5791bdc4541e79bd43d586e3c3eff1e39c16665f@balena.io> | TypeScript | mit | resin-io-modules/resin-components,resin-io-modules/resin-components,resin-io-modules/resin-components | ---
+++
@@ -1,7 +1,7 @@
import { FormatValidator, FormatDefinition } from 'ajv';
import { UiSchema as rjsfUiSchema } from '@rjsf/core';
import { Widget } from './widgets/widget-util';
-export { JSONSchema7 as JSONSchema } from 'json-schema';
+export type { JSONSchema7 as JSONSchema } from 'json-schema';
export const JsonTypes = {
array: 'array', |
165ef87f9fd4f11f4d37505990b531d1b3dee428 | source/kepo.ts | source/kepo.ts | // The currently-pressed key codes from oldest to newest
const pressedKeyCodes: number[] = []
export const pressedKeyCodesFromOldestToNewest =
pressedKeyCodes as ReadonlyArray<number>
export function isKeyPressed(keyCode: number): boolean {
return pressedKeyCodes.includes(keyCode)
}
export function areAllKeysPressed(...keyCodes: number[]): boolean {
return keyCodes.every(k => isKeyPressed(k))
}
export function mostRecentlyPressedKey(...keyCodes: number[]): number | undefined {
return last(
keyCodes.length
? pressedKeyCodes.filter(p => keyCodes.includes(p))
: pressedKeyCodes
)
}
document.addEventListener('keydown', event => {
if (!isKeyPressed(event.keyCode)) {
pressedKeyCodes.push(event.keyCode)
}
})
document.addEventListener('keyup', event => {
if (isKeyPressed(event.keyCode)) {
pressedKeyCodes.splice(pressedKeyCodes.indexOf(event.keyCode), 1)
}
})
function last<T>(items: ReadonlyArray<T>): T | undefined {
return items[items.length - 1];
}
| // The currently-pressed key codes from oldest to newest
const pressedKeyCodes: number[] = []
export const pressedKeyCodesFromOldestToNewest =
pressedKeyCodes as ReadonlyArray<number>
export function isKeyPressed(keyCode: number): boolean {
return pressedKeyCodes.includes(keyCode)
}
export function areAllKeysPressed(...keyCodes: number[]): boolean {
return keyCodes.every(k => isKeyPressed(k))
}
export function mostRecentlyPressedKey(...keyCodes: number[]): number | undefined {
return last(
keyCodes.length
? pressedKeyCodes.filter(p => keyCodes.includes(p))
: pressedKeyCodes
)
}
document.addEventListener('keydown', event => {
if (!isKeyPressed(event.keyCode)) {
pressedKeyCodes.push(event.keyCode)
}
})
document.addEventListener('keyup', event => {
if (isKeyPressed(event.keyCode)) {
pressedKeyCodes.splice(pressedKeyCodes.indexOf(event.keyCode), 1)
}
})
window.addEventListener('blur', () => {
pressedKeyCodes.splice(0)
})
function last<T>(items: ReadonlyArray<T>): T | undefined {
return items[items.length - 1];
}
| Clear all pressed keys when tab loses focus | Clear all pressed keys when tab loses focus
| TypeScript | mit | start/kepo,start/kepo,start/kepo | ---
+++
@@ -32,6 +32,10 @@
}
})
+window.addEventListener('blur', () => {
+ pressedKeyCodes.splice(0)
+})
+
function last<T>(items: ReadonlyArray<T>): T | undefined {
return items[items.length - 1];
} |
79c06bb442e63ac536a524fdc9cd17d6d37e7f03 | src/app/components/page-header/page-header-directive.ts | src/app/components/page-header/page-header-directive.ts | import { Component, Inject, Input } from 'ng-metadata/core';
@Component({
selector: 'gj-page-header',
templateUrl: '/app/components/page-header/page-header.html',
legacy: {
transclude: {
coverButtons: '?gjPageHeaderCoverButtons',
content: 'gjPageHeaderContent',
spotlight: '?gjPageHeaderSpotlight',
nav: '?gjPageHeaderNav',
controls: '?gjPageHeaderControls',
}
},
})
export class PageHeaderComponent
{
@Input( '<?' ) coverMediaItem: any;
@Input( '<?' ) shouldAffixNav: boolean;
constructor(
@Inject( 'Screen' ) private screen: any
)
{
}
}
| import { Component, Inject, Input } from 'ng-metadata/core';
import template from './page-header.html';
@Component({
selector: 'gj-page-header',
templateUrl: template,
legacy: {
transclude: {
coverButtons: '?gjPageHeaderCoverButtons',
content: 'gjPageHeaderContent',
spotlight: '?gjPageHeaderSpotlight',
nav: '?gjPageHeaderNav',
controls: '?gjPageHeaderControls',
}
},
})
export class PageHeaderComponent
{
@Input( '<?' ) coverMediaItem: any;
@Input( '<?' ) shouldAffixNav: boolean;
constructor(
@Inject( 'Screen' ) private screen: any
)
{
}
}
| Change the page-header component to import template. | Change the page-header component to import template.
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -1,8 +1,9 @@
import { Component, Inject, Input } from 'ng-metadata/core';
+import template from './page-header.html';
@Component({
selector: 'gj-page-header',
- templateUrl: '/app/components/page-header/page-header.html',
+ templateUrl: template,
legacy: {
transclude: {
coverButtons: '?gjPageHeaderCoverButtons', |
15a65ff2952900c113ffc6876351fdf376e43199 | src/MCM.KidsIdApp/www/scripts/controllers/LoginController.ts | src/MCM.KidsIdApp/www/scripts/controllers/LoginController.ts |
/// <reference path="../Definitions/angular.d.ts" />
/// <reference path="../Definitions/AzureMobileServicesClient.d.ts" />
/// <reference path="../Services/UserService.ts" />
module MCM {
export class LoginController {
public static $inject = ['$scope', '$state', 'UserService'];
public scope:any;
public state:any;
public userService:UserService;
constructor($scope:ng.IScope, $state:any, userService:MCM.UserService) {
this.scope = $scope;
this.userService = userService;
this.state = $state;
console.log('args length', arguments.length);
console.log('userService', userService);
this.scope.signIn = this.signIn.bind(this);
}
public signIn (service) {
const that = this;
var mobileService = new WindowsAzure.MobileServiceClient(
"http://mobilekidsidapp.azurewebsites.net",
null
);
mobileService.login(service).done(
function success(user) {
that.userService.someMethod('foo')
.then( function (param) {
console.log('in .then with param=' + param);
that.state.go('landing');
});
}, function error(error) {
console.error('Failed to login: ', error);
});
}
}
}
angular.module('mcmapp').controller('loginController', MCM.LoginController); |
/// <reference path="../Definitions/angular.d.ts" />
/// <reference path="../Definitions/AzureMobileServicesClient.d.ts" />
/// <reference path="../Services/UserService.ts" />
module MCM {
export class LoginController {
public static $inject = ['$scope', '$state', 'UserService'];
public scope:any;
public state:any;
public userService:UserService;
constructor($scope:ng.IScope, $state:any, userService:MCM.UserService) {
this.scope = $scope;
this.userService = userService;
this.state = $state;
console.log('args length', arguments.length);
console.log('userService', userService);
this.scope.signIn = this.signIn.bind(this);
}
public signIn (service) {
const that = this;
if (service == 'test') {
that.state.go('landing');
} else {
var mobileService = new WindowsAzure.MobileServiceClient(
"http://mobilekidsidapp.azurewebsites.net",
null
);
mobileService.login(service).done(
function success(user) {
that.userService.someMethod('foo')
.then(function (param) {
console.log('in .then with param=' + param);
that.state.go('landing');
});
}, function error(error) {
console.error('Failed to login: ', error);
});
}
}
}
}
angular.module('mcmapp').controller('loginController', MCM.LoginController); | Add 'bypass login' functionality back in (got lost in code move). | Add 'bypass login' functionality back in (got lost in code move).
| TypeScript | apache-2.0 | rockfordlhotka/MobileKidsIdApp,bseebacher/MobileKidsIdApp,HTBox/MobileKidsIdApp,bseebacher/MobileKidsIdApp,HTBox/MobileKidsIdApp,bseebacher/MobileKidsIdApp,bseebacher/MobileKidsIdApp,HTBox/MobileKidsIdApp,HTBox/MobileKidsIdApp,rockfordlhotka/MobileKidsIdApp | ---
+++
@@ -25,20 +25,24 @@
public signIn (service) {
const that = this;
- var mobileService = new WindowsAzure.MobileServiceClient(
- "http://mobilekidsidapp.azurewebsites.net",
- null
- );
- mobileService.login(service).done(
- function success(user) {
- that.userService.someMethod('foo')
- .then( function (param) {
- console.log('in .then with param=' + param);
- that.state.go('landing');
- });
- }, function error(error) {
- console.error('Failed to login: ', error);
- });
+ if (service == 'test') {
+ that.state.go('landing');
+ } else {
+ var mobileService = new WindowsAzure.MobileServiceClient(
+ "http://mobilekidsidapp.azurewebsites.net",
+ null
+ );
+ mobileService.login(service).done(
+ function success(user) {
+ that.userService.someMethod('foo')
+ .then(function (param) {
+ console.log('in .then with param=' + param);
+ that.state.go('landing');
+ });
+ }, function error(error) {
+ console.error('Failed to login: ', error);
+ });
+ }
}
}
} |
e8bf862b4d12595dfc53472ac497c39ac16324fe | client/src/constants/api.ts | client/src/constants/api.ts | export const BASE_URL = location.origin + "/api/v1";
| let baseUrl;
if (process.env.NODE_ENV !== 'production') {
baseUrl = "http://localhost:8000/api/v1";
}
else {
baseUrl = location.origin + "/api/v1";
}
export const BASE_URL = baseUrl;
| Update base url handling for dev | Update base url handling for dev
| TypeScript | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -1 +1,9 @@
-export const BASE_URL = location.origin + "/api/v1";
+let baseUrl;
+if (process.env.NODE_ENV !== 'production') {
+ baseUrl = "http://localhost:8000/api/v1";
+}
+else {
+ baseUrl = location.origin + "/api/v1";
+}
+
+export const BASE_URL = baseUrl; |
ba4aa77122fc0b744d8b8a4a4a40f1dae822731a | src/lib/api.ts | src/lib/api.ts | import User from '../user'
const Octokat = require('octokat')
export interface Repo {
cloneUrl: string,
htmlUrl: string,
name: string
owner: {
avatarUrl: string,
login: string
type: 'user' | 'org'
},
private: boolean,
stargazersCount: number
}
export default class API {
private client: any
public constructor(user: User) {
// TODO: Use the user's endpoint
this.client = new Octokat({token: user.getToken()})
}
public async fetchRepos(): Promise<Repo[]> {
const results: Repo[] = []
let nextPage = this.client.user.repos
while (nextPage) {
const request = await nextPage.fetch()
results.push(...request.items)
nextPage = request.nextPage
}
return results
}
}
| import User from '../user'
const Octokat = require('octokat')
export interface Repo {
cloneUrl: string,
htmlUrl: string,
name: string
owner: {
avatarUrl: string,
login: string
type: 'user' | 'org'
},
private: boolean,
stargazersCount: number
}
export default class API {
private client: any
public constructor(user: User) {
this.client = new Octokat({token: user.getToken(), rootURL: user.getEndpoint()})
}
public async fetchRepos(): Promise<Repo[]> {
const results: Repo[] = []
let nextPage = this.client.user.repos
while (nextPage) {
const request = await nextPage.fetch()
results.push(...request.items)
nextPage = request.nextPage
}
return results
}
}
| Use the user's endpoint when creating an API | Use the user's endpoint when creating an API
| TypeScript | mit | say25/desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,gengjiawen/desktop,gengjiawen/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,BugTesterTest/desktops,shiftkey/desktop,kactus-io/kactus,hjobrien/desktop,desktop/desktop,hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,gengjiawen/desktop,desktop/desktop,desktop/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,BugTesterTest/desktops,BugTesterTest/desktops,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,hjobrien/desktop,hjobrien/desktop | ---
+++
@@ -19,8 +19,7 @@
private client: any
public constructor(user: User) {
- // TODO: Use the user's endpoint
- this.client = new Octokat({token: user.getToken()})
+ this.client = new Octokat({token: user.getToken(), rootURL: user.getEndpoint()})
}
public async fetchRepos(): Promise<Repo[]> { |
2ee75ab297d920141398a030f825e4943eb16ad5 | src/ui/actions/editor/projectFile/layer/moveLayer.ts | src/ui/actions/editor/projectFile/layer/moveLayer.ts | import { ApplicationState } from '../../../../../shared/models/applicationState';
import { Point } from '../../../../../shared/models/point';
import { moveElement } from '../../../../../shared/utils/arrays';
import { defineAction } from '../../../../reduxWithLessSux/action';
interface MoveLayerPayload {
layerIndex: number;
toIndex: number;
}
export const moveLayer = defineAction(
'moveLayer', (state: ApplicationState, payload: MoveLayerPayload) => {
const editors = state.editors.map((editor, editorIndex) => {
if (editorIndex === state.activeEditorIndex) {
const projectFile = editor.projectFile;
let layers = [...projectFile.layers];
layers = moveElement(layers, payload.layerIndex, payload.toIndex);
return {
...editor,
projectFile: {
...projectFile,
layers
}
};
}
return editor;
});
return {
...state,
editors
};
}
).getDispatcher();
| import { ApplicationState } from '../../../../../shared/models/applicationState';
import { Point } from '../../../../../shared/models/point';
import { moveElement } from '../../../../../shared/utils/arrays';
import { defineAction } from '../../../../reduxWithLessSux/action';
interface MoveLayerPayload {
layerIndex: number;
toIndex: number;
}
export const moveLayer = defineAction(
'moveLayer', (state: ApplicationState, payload: MoveLayerPayload) => {
const editors = state.editors.map((editor, editorIndex) => {
if (editorIndex === state.activeEditorIndex) {
const projectFile = editor.projectFile;
let layers = [...projectFile.layers];
if (payload.toIndex < 0 || payload.toIndex >= layers.length) {
return editor;
}
layers = moveElement(layers, payload.layerIndex, payload.toIndex);
const selectedLayerIndex = (
editor.selectedLayerIndex === payload.layerIndex ?
payload.toIndex :
editor.selectedLayerIndex
);
return {
...editor,
projectFile: {
...projectFile,
layers
},
selectedLayerIndex
};
}
return editor;
});
return {
...state,
editors
};
}
).getDispatcher();
| Fix bug where moving selected layer would select different layer | Fix bug where moving selected layer would select different layer
| TypeScript | mit | codeandcats/Polygen | ---
+++
@@ -14,14 +14,25 @@
if (editorIndex === state.activeEditorIndex) {
const projectFile = editor.projectFile;
let layers = [...projectFile.layers];
+
+ if (payload.toIndex < 0 || payload.toIndex >= layers.length) {
+ return editor;
+ }
+
layers = moveElement(layers, payload.layerIndex, payload.toIndex);
+ const selectedLayerIndex = (
+ editor.selectedLayerIndex === payload.layerIndex ?
+ payload.toIndex :
+ editor.selectedLayerIndex
+ );
return {
...editor,
projectFile: {
...projectFile,
layers
- }
+ },
+ selectedLayerIndex
};
}
return editor; |
d2561e6e7355c153434f782c223eb97339b3401c | types/chai-jest-snapshot/chai-jest-snapshot-tests.ts | types/chai-jest-snapshot/chai-jest-snapshot-tests.ts | import chaiJestSnapshot from 'chai-jest-snapshot';
import { expect } from 'chai';
chai.use(chaiJestSnapshot);
expect({}).to.matchSnapshot();
expect({}).to.matchSnapshot(true);
expect({}).to.matchSnapshot("filename");
expect({}).to.matchSnapshot("filename", "snapshotname");
expect({}).to.matchSnapshot("filename", "snapshotname", false);
const mockContext: Mocha.IBeforeAndAfterContext = <any> {
currentTest: {
file: 'testfile',
fullTitle: () => 'fullTitle'
}
};
chaiJestSnapshot.setFileName("filename");
chaiJestSnapshot.setTestName("testname");
chaiJestSnapshot.configureUsingMochaContext(mockContext);
chaiJestSnapshot.resetSnapshotRegistry();
chaiJestSnapshot.addSerializer({});
| import chaiJestSnapshot from 'chai-jest-snapshot';
import { expect } from 'chai';
chai.use(chaiJestSnapshot);
expect({}).to.matchSnapshot();
expect({}).to.matchSnapshot(true);
expect({}).to.matchSnapshot("filename");
expect({}).to.matchSnapshot("filename", "snapshotname");
expect({}).to.matchSnapshot("filename", "snapshotname", false);
const mockContext: Mocha.IBeforeAndAfterContext = <any> {
currentTest: {
file: 'testfile',
fullTitle: () => 'fullTitle'
}
};
chaiJestSnapshot.setFilename("filename");
chaiJestSnapshot.setTestName("testname");
chaiJestSnapshot.configureUsingMochaContext(mockContext);
chaiJestSnapshot.resetSnapshotRegistry();
chaiJestSnapshot.addSerializer({});
| Fix chai-jest-snapshot tests for setFilename | Fix chai-jest-snapshot tests for setFilename | TypeScript | mit | dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,benliddicott/DefinitelyTyped,chrootsu/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,dsebastien/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,borisyankov/DefinitelyTyped,chrootsu/DefinitelyTyped,markogresak/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,rolandzwaga/DefinitelyTyped,one-pieces/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,aciccarello/DefinitelyTyped,mcliment/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,georgemarshall/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,alexdresko/DefinitelyTyped | ---
+++
@@ -16,7 +16,7 @@
}
};
-chaiJestSnapshot.setFileName("filename");
+chaiJestSnapshot.setFilename("filename");
chaiJestSnapshot.setTestName("testname");
chaiJestSnapshot.configureUsingMochaContext(mockContext);
chaiJestSnapshot.resetSnapshotRegistry(); |
89efe65f1848d312988880f2a5f754e2d0b32c1b | src/installer/bin.ts | src/installer/bin.ts | import * as isCI from 'is-ci'
import * as path from 'path'
import { install, uninstall } from './'
// Just for testing
if (process.env.HUSKY_DEBUG) {
console.log(`husky:debug INIT_CWD=${process.env.INIT_CWD}`)
}
// Action can be "install" or "uninstall"
// huskyDir is ONLY used in dev, don't use this arguments
const [, , action, huskyDir = path.join(__dirname, '../..')] = process.argv
// Find Git dir
try {
// Run installer
if (action === 'install') {
install(huskyDir, undefined, isCI)
} else {
uninstall(huskyDir)
}
} catch (error) {
console.log(`husky > failed to ${action}`)
console.log(error.message)
}
| import * as isCI from 'is-ci'
import * as path from 'path'
import { install, uninstall } from './'
// Just for testing
if (process.env.HUSKY_DEBUG === 'true') {
console.log(`husky:debug INIT_CWD=${process.env.INIT_CWD}`)
}
// Action can be "install" or "uninstall"
// huskyDir is ONLY used in dev, don't use this arguments
const [, , action, huskyDir = path.join(__dirname, '../..')] = process.argv
// Find Git dir
try {
// Run installer
if (action === 'install') {
install(huskyDir, undefined, isCI)
} else {
uninstall(huskyDir)
}
} catch (error) {
console.log(`husky > failed to ${action}`)
console.log(error.message)
}
| Check that HUSKY_DEBUG equals "true" | Check that HUSKY_DEBUG equals "true"
| TypeScript | mit | typicode/husky,typicode/husky | ---
+++
@@ -3,7 +3,7 @@
import { install, uninstall } from './'
// Just for testing
-if (process.env.HUSKY_DEBUG) {
+if (process.env.HUSKY_DEBUG === 'true') {
console.log(`husky:debug INIT_CWD=${process.env.INIT_CWD}`)
}
|
f36f15e8cb10005abaf553591efa2db1d932c373 | src/app/components/module-options/module-options.component.ts | src/app/components/module-options/module-options.component.ts | import { Component, Input, Output, EventEmitter } from '@angular/core';
import { modules, getDefaultOptions } from '../modules/modules-main';
import { OptionsConfig, Options } from '../modules/modules-config';
@Component({
selector: 'mymicds-module-options',
templateUrl: './module-options.component.html',
styleUrls: ['./module-options.component.scss']
})
export class ModuleOptionsComponent {
@Input()
set type(name: string) {
if (!modules[name]) {
return;
}
this.optionsConfig = modules[name].options;
this.optionKeys = Object.keys(this.optionsConfig);
// Fall back to default options if none are provided
if (!this.options) {
this.options = getDefaultOptions(name);
}
}
@Input() options: Options;
@Output() optionsChange = new EventEmitter<Options>();
optionKeys: string[];
optionsConfig: OptionsConfig;
constructor() { }
valueChanged() {
this.optionsChange.emit(JSON.parse(JSON.stringify(this.options)));
}
}
| import { Component, Input, Output, EventEmitter } from '@angular/core';
import { contains } from '../../common/utils';
import { modules, getDefaultOptions } from '../modules/modules-main';
import { OptionsConfig, Options } from '../modules/modules-config';
@Component({
selector: 'mymicds-module-options',
templateUrl: './module-options.component.html',
styleUrls: ['./module-options.component.scss']
})
export class ModuleOptionsComponent {
@Input()
get type() {
return this._type;
}
set type(name: string) {
if (!modules[name] || name === this.type) {
return;
}
this._type = name;
this.optionsConfig = modules[name].options;
this.optionKeys = Object.keys(this.optionsConfig);
console.log('set type', name, getDefaultOptions(name));
// Fall back to default options if none are provided
this.options = {};
}
private _type: string = null;
@Input()
get options() {
return this._options;
}
set options(newOptions: Options) {
// Instead of replacing options, just override default options
this._options = Object.assign({}, getDefaultOptions(this.type), this.options, newOptions);
}
private _options: Options = {};
@Output() optionsChange = new EventEmitter<Options>();
optionKeys: string[];
optionsConfig: OptionsConfig;
constructor() { }
valueChanged() {
// Loop through all options and only emit ones valid
const validOptions = {};
for (const optionKey of Object.keys(this.options)) {
if (contains(this.optionKeys, optionKey)) {
validOptions[optionKey] = this.options[optionKey];
}
}
this.optionsChange.emit(validOptions);
}
}
| Fix module options in case not all options are returned from back-end | Fix module options in case not all options are returned from back-end
| TypeScript | mit | michaelgira23/MyMICDS-v2-Angular,MyMICDS/MyMICDS-v2-Angular,MyMICDS/MyMICDS-v2-Angular,michaelgira23/MyMICDS-v2-Angular,michaelgira23/MyMICDS-v2-Angular,MyMICDS/MyMICDS-v2-Angular | ---
+++
@@ -1,4 +1,5 @@
import { Component, Input, Output, EventEmitter } from '@angular/core';
+import { contains } from '../../common/utils';
import { modules, getDefaultOptions } from '../modules/modules-main';
import { OptionsConfig, Options } from '../modules/modules-config';
@@ -10,20 +11,34 @@
export class ModuleOptionsComponent {
@Input()
+ get type() {
+ return this._type;
+ }
set type(name: string) {
- if (!modules[name]) {
+ if (!modules[name] || name === this.type) {
return;
}
+ this._type = name;
this.optionsConfig = modules[name].options;
this.optionKeys = Object.keys(this.optionsConfig);
+ console.log('set type', name, getDefaultOptions(name));
+
// Fall back to default options if none are provided
- if (!this.options) {
- this.options = getDefaultOptions(name);
- }
+ this.options = {};
}
+ private _type: string = null;
- @Input() options: Options;
+ @Input()
+ get options() {
+ return this._options;
+ }
+ set options(newOptions: Options) {
+ // Instead of replacing options, just override default options
+ this._options = Object.assign({}, getDefaultOptions(this.type), this.options, newOptions);
+ }
+ private _options: Options = {};
+
@Output() optionsChange = new EventEmitter<Options>();
optionKeys: string[];
@@ -32,7 +47,15 @@
constructor() { }
valueChanged() {
- this.optionsChange.emit(JSON.parse(JSON.stringify(this.options)));
+ // Loop through all options and only emit ones valid
+ const validOptions = {};
+ for (const optionKey of Object.keys(this.options)) {
+ if (contains(this.optionKeys, optionKey)) {
+ validOptions[optionKey] = this.options[optionKey];
+ }
+ }
+
+ this.optionsChange.emit(validOptions);
}
} |
ddef37f7e6fc75b314fdf64ec74929f3e305390b | developer/js/tests/test-compile-trie.ts | developer/js/tests/test-compile-trie.ts | import LexicalModelCompiler from '../';
import {assert} from 'chai';
import 'mocha';
import {makePathToFixture, compileModelSourceCode} from './helpers';
describe('LexicalModelCompiler', function () {
describe('#generateLexicalModelCode', function () {
const MODEL_ID = 'example.qaa.trivial';
const PATH = makePathToFixture(MODEL_ID);
it('should compile a trivial word list', function () {
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
sources: ['wordlist.tsv']
}, PATH) as string;
let result = compileModelSourceCode(code);
assert.isFalse(result.hasSyntaxError);
assert.isNotNull(result.exportedModel);
assert.equal(result.modelConstructorName, 'TrieModel');
// Sanity check: the word list has three total unweighted words, with a
// total weight of 3!
assert.match(code, /\btotalWeight\b["']?:\s*3\b/);
});
})
});
| import LexicalModelCompiler from '../';
import {assert} from 'chai';
import 'mocha';
import {makePathToFixture, compileModelSourceCode} from './helpers';
describe('LexicalModelCompiler', function () {
describe('#generateLexicalModelCode', function () {
it('should compile a trivial word list', function () {
const MODEL_ID = 'example.qaa.trivial';
const PATH = makePathToFixture(MODEL_ID);
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
sources: ['wordlist.tsv']
}, PATH) as string;
let result = compileModelSourceCode(code);
assert.isFalse(result.hasSyntaxError);
assert.isNotNull(result.exportedModel);
assert.equal(result.modelConstructorName, 'TrieModel');
// Sanity check: the word list has three total unweighted words, with a
// total weight of 3!
assert.match(code, /\btotalWeight\b["']?:\s*3\b/);
});
it('should compile a word list exported by Microsoft Excel', function () {
const MODEL_ID = 'example.qaa.utf16le';
const PATH = makePathToFixture(MODEL_ID);
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
sources: ['wordlist.txt']
}, PATH) as string;
let result = compileModelSourceCode(code);
assert.isFalse(result.hasSyntaxError);
assert.isNotNull(result.exportedModel);
assert.equal(result.modelConstructorName, 'TrieModel');
// Sanity check: the word list has three total unweighted words, with a
// total weight of 44,103!
assert.match(code, /\btotalWeight\b["']?:\s*44103\b/);
});
})
});
| Test a UTF-16LE file compiles properly. | Test a UTF-16LE file compiles properly.
| TypeScript | apache-2.0 | tavultesoft/keymanweb,tavultesoft/keymanweb | ---
+++
@@ -7,10 +7,10 @@
describe('LexicalModelCompiler', function () {
describe('#generateLexicalModelCode', function () {
- const MODEL_ID = 'example.qaa.trivial';
- const PATH = makePathToFixture(MODEL_ID);
+ it('should compile a trivial word list', function () {
+ const MODEL_ID = 'example.qaa.trivial';
+ const PATH = makePathToFixture(MODEL_ID);
- it('should compile a trivial word list', function () {
let compiler = new LexicalModelCompiler;
let code = compiler.generateLexicalModelCode(MODEL_ID, {
format: 'trie-1.0',
@@ -26,5 +26,25 @@
// total weight of 3!
assert.match(code, /\btotalWeight\b["']?:\s*3\b/);
});
+
+ it('should compile a word list exported by Microsoft Excel', function () {
+ const MODEL_ID = 'example.qaa.utf16le';
+ const PATH = makePathToFixture(MODEL_ID);
+
+ let compiler = new LexicalModelCompiler;
+ let code = compiler.generateLexicalModelCode(MODEL_ID, {
+ format: 'trie-1.0',
+ sources: ['wordlist.txt']
+ }, PATH) as string;
+
+ let result = compileModelSourceCode(code);
+ assert.isFalse(result.hasSyntaxError);
+ assert.isNotNull(result.exportedModel);
+ assert.equal(result.modelConstructorName, 'TrieModel');
+
+ // Sanity check: the word list has three total unweighted words, with a
+ // total weight of 44,103!
+ assert.match(code, /\btotalWeight\b["']?:\s*44103\b/);
+ });
})
}); |
0f8dac237a668c9efd7804bbdbf25a0c1b299887 | app/app.component.ts | app/app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
})
export class AppComponent {
title = 'Tour of Heroes';
hero: Hero = {
id: 10000,
name: 'Windstorm'
};
}
export class Hero {
id: number;
name: string;
}
| import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div><label>name: </label>{{hero.name}}</div>
})
export class AppComponent {
title = 'Tour of Heroes';
hero: Hero = {
id: 10000,
name: 'Windstorm'
};
}
export class Hero {
id: number;
name: string;
}
| Change template to multi-line. Should not change UI | Change template to multi-line. Should not change UI
| TypeScript | mit | atbtm/Angular2-Pull-Repo,atbtm/Angular2-Pull-Repo,atbtm/Angular2-Pull-Repo | ---
+++
@@ -2,18 +2,18 @@
@Component({
selector: 'my-app',
- template:
- <h1>{{title}}</h1>
- <h2>{{hero.name}} details!</h2>
- <div><label>id: </label>{{hero.id}}</div>
- <div><label>name: </label>{{hero.name}}</div>
+ template:`
+ <h1>{{title}}</h1>
+ <h2>{{hero.name}} details!</h2>
+ <div><label>id: </label>{{hero.id}}</div>
+ <div><label>name: </label>{{hero.name}}</div>
})
export class AppComponent {
- title = 'Tour of Heroes';
- hero: Hero = {
- id: 10000,
- name: 'Windstorm'
-};
+ title = 'Tour of Heroes';
+ hero: Hero = {
+ id: 10000,
+ name: 'Windstorm'
+ };
}
export class Hero {
id: number; |
22fc830f00b925b761d0bd836b3350631de41454 | src/original-template/original-template.directive.spec.ts | src/original-template/original-template.directive.spec.ts | /* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { OriginalTemplateDirective } from './original-template.directive';
describe('Directive: OriginalTemplate', () => {
it('should create an instance', () => {
let directive = new OriginalTemplateDirective();
expect(directive).toBeTruthy();
});
});
| /* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { OriginalTemplateDirective } from './original-template.directive';
describe('Directive: OriginalTemplate', () => {
it('should create an instance', () => {
let directive = new OriginalTemplateDirective(<any>{}, <any>{});
expect(directive).toBeTruthy();
});
});
| Fix test to not brake | test(directive): Fix test to not brake
| TypeScript | mit | gund/ng-original-template,gund/ng-original-template | ---
+++
@@ -5,7 +5,7 @@
describe('Directive: OriginalTemplate', () => {
it('should create an instance', () => {
- let directive = new OriginalTemplateDirective();
+ let directive = new OriginalTemplateDirective(<any>{}, <any>{});
expect(directive).toBeTruthy();
});
}); |
edc3bbe603682c3fb15e12e2799f4a6e69b86b9e | extensions/markdown-language-features/src/features/documentSymbolProvider.ts | extensions/markdown-language-features/src/features/documentSymbolProvider.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { MarkdownEngine } from '../markdownEngine';
import { TableOfContentsProvider } from '../tableOfContentsProvider';
export default class MDDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
constructor(
private readonly engine: MarkdownEngine
) { }
public async provideDocumentSymbols(document: vscode.TextDocument): Promise<vscode.SymbolInformation[]> {
const toc = await new TableOfContentsProvider(this.engine, document).getToc();
return toc.map(entry => {
return new vscode.SymbolInformation('#'.repeat(entry.level) + ' ' + entry.text, vscode.SymbolKind.Namespace, '', entry.location);
});
}
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { MarkdownEngine } from '../markdownEngine';
import { TableOfContentsProvider } from '../tableOfContentsProvider';
export default class MDDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
constructor(
private readonly engine: MarkdownEngine
) { }
public async provideDocumentSymbols(document: vscode.TextDocument): Promise<vscode.SymbolInformation[]> {
const toc = await new TableOfContentsProvider(this.engine, document).getToc();
return toc.map(entry => {
return new vscode.SymbolInformation('#'.repeat(entry.level) + ' ' + entry.text, vscode.SymbolKind.String, '', entry.location);
});
}
} | Use string symbol kind for markdown symbols | Use string symbol kind for markdown symbols
| TypeScript | mit | mjbvz/vscode,the-ress/vscode,eamodio/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,microlv/vscode,microlv/vscode,microsoft/vscode,the-ress/vscode,rishii7/vscode,cleidigh/vscode,Microsoft/vscode,joaomoreno/vscode,hoovercj/vscode,hoovercj/vscode,hoovercj/vscode,hoovercj/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,DustinCampbell/vscode,0xmohit/vscode,hoovercj/vscode,Microsoft/vscode,DustinCampbell/vscode,mjbvz/vscode,landonepps/vscode,the-ress/vscode,rishii7/vscode,microlv/vscode,Microsoft/vscode,rishii7/vscode,microlv/vscode,DustinCampbell/vscode,microsoft/vscode,cleidigh/vscode,joaomoreno/vscode,Microsoft/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,hoovercj/vscode,cleidigh/vscode,the-ress/vscode,DustinCampbell/vscode,landonepps/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,0xmohit/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,the-ress/vscode,0xmohit/vscode,0xmohit/vscode,microsoft/vscode,0xmohit/vscode,eamodio/vscode,cleidigh/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,hoovercj/vscode,cleidigh/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,eamodio/vscode,the-ress/vscode,DustinCampbell/vscode,DustinCampbell/vscode,landonepps/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,DustinCampbell/vscode,microlv/vscode,DustinCampbell/vscode,landonepps/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,0xmohit/vscode,the-ress/vscode,microlv/vscode,Microsoft/vscode,0xmohit/vscode,hoovercj/vscode,joaomoreno/vscode,mjbvz/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,rishii7/vscode,0xmohit/vscode,Microsoft/vscode,joaomoreno/vscode,microlv/vscode,the-ress/vscode,cleidigh/vscode,mjbvz/vscode,cleidigh/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,joaomoreno/vscode,cleidigh/vscode,the-ress/vscode,microsoft/vscode,joaomoreno/vscode,mjbvz/vscode,microsoft/vscode,Microsoft/vscode,the-ress/vscode,mjbvz/vscode,rishii7/vscode,microlv/vscode,eamodio/vscode,mjbvz/vscode,microlv/vscode,eamodio/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,microlv/vscode,Microsoft/vscode,rishii7/vscode,landonepps/vscode,rishii7/vscode,DustinCampbell/vscode,microlv/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,the-ress/vscode,rishii7/vscode,mjbvz/vscode,microsoft/vscode,landonepps/vscode,mjbvz/vscode,microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,DustinCampbell/vscode,joaomoreno/vscode,joaomoreno/vscode,landonepps/vscode,mjbvz/vscode,the-ress/vscode,the-ress/vscode,landonepps/vscode,rishii7/vscode,eamodio/vscode,landonepps/vscode,eamodio/vscode,landonepps/vscode,rishii7/vscode,hoovercj/vscode,cleidigh/vscode,eamodio/vscode,0xmohit/vscode,DustinCampbell/vscode,rishii7/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,microsoft/vscode,microlv/vscode,landonepps/vscode,mjbvz/vscode,landonepps/vscode,DustinCampbell/vscode,mjbvz/vscode,0xmohit/vscode,hoovercj/vscode,microlv/vscode,0xmohit/vscode,eamodio/vscode,joaomoreno/vscode,microsoft/vscode,rishii7/vscode,cleidigh/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,landonepps/vscode,cleidigh/vscode,hoovercj/vscode,joaomoreno/vscode,cleidigh/vscode,mjbvz/vscode,Microsoft/vscode,mjbvz/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,cleidigh/vscode,mjbvz/vscode,mjbvz/vscode,DustinCampbell/vscode,microlv/vscode,microlv/vscode,the-ress/vscode,DustinCampbell/vscode,cleidigh/vscode,0xmohit/vscode,rishii7/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,hoovercj/vscode,eamodio/vscode,DustinCampbell/vscode,landonepps/vscode,rishii7/vscode,landonepps/vscode,DustinCampbell/vscode,landonepps/vscode,eamodio/vscode | ---
+++
@@ -4,9 +4,9 @@
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
-
import { MarkdownEngine } from '../markdownEngine';
import { TableOfContentsProvider } from '../tableOfContentsProvider';
+
export default class MDDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
@@ -17,7 +17,7 @@
public async provideDocumentSymbols(document: vscode.TextDocument): Promise<vscode.SymbolInformation[]> {
const toc = await new TableOfContentsProvider(this.engine, document).getToc();
return toc.map(entry => {
- return new vscode.SymbolInformation('#'.repeat(entry.level) + ' ' + entry.text, vscode.SymbolKind.Namespace, '', entry.location);
+ return new vscode.SymbolInformation('#'.repeat(entry.level) + ' ' + entry.text, vscode.SymbolKind.String, '', entry.location);
});
}
} |
356f1b8955d792074c51ca6e9193ee2ff073e264 | examples/typescript/index.ts | examples/typescript/index.ts | import jsPDF = require('jspdf');
import 'jspdf-autotable';
// This is a hack for typing this plugin. It should be possible to do
// with typescript augmentation feature, but the way jspdf's types are
// defined and the way jspdf is exported makes it hard to implement
// https://stackoverflow.com/q/55328516/827047
type AutoTable = import('jspdf-autotable').autoTable;
// stats from https://en.wikipedia.org/wiki/World_Happiness_Report (2018)
var head = [['ID', 'Country', 'Rank', 'Capital']];
var data = [
[1, 'Finland', 7.632, 'Helsinki'],
[2, 'Norway', 7.594, 'Oslo'],
[3, 'Denmark', 7.555, 'Copenhagen'],
[4, 'Iceland', 7.495, 'Reykjavík'],
[5, 'Switzerland', 7.487, 'Bern'],
[9, 'Sweden', 7.314, 'Stockholm'],
[73, 'Belarus', 5.483, 'Minsk']
];
const doc = new jsPDF();
((doc as any).autoTable as AutoTable)({
head: head,
body: data,
didDrawCell: data => {
console.log(data.column.index)
}
});
doc.save('table.pdf');
| import jsPDF = require('jspdf');
import 'jspdf-autotable';
// This is a hack for typing this plugin. It should be possible to do
// with typescript augmentation feature, but the way jspdf's types are
// defined and the way jspdf is exported makes it hard to implement
// https://stackoverflow.com/q/55328516/827047
import { autoTable as AutoTable } from 'jspdf-autotable';
// stats from https://en.wikipedia.org/wiki/World_Happiness_Report (2018)
var head = [['ID', 'Country', 'Rank', 'Capital']];
var data = [
[1, 'Finland', 7.632, 'Helsinki'],
[2, 'Norway', 7.594, 'Oslo'],
[3, 'Denmark', 7.555, 'Copenhagen'],
[4, 'Iceland', 7.495, 'Reykjavík'],
[5, 'Switzerland', 7.487, 'Bern'],
[9, 'Sweden', 7.314, 'Stockholm'],
[73, 'Belarus', 5.483, 'Minsk']
];
const doc = new jsPDF();
((doc as any).autoTable as AutoTable)({
head: head,
body: data,
didDrawCell: data => {
console.log(data.column.index)
}
});
doc.save('table.pdf');
| Improve typescript example by using import | Improve typescript example by using import
| TypeScript | mit | simonbengtsson/jsPDF-AutoTable,someatoms/jsPDF-AutoTable,simonbengtsson/jsPDF-AutoTable,simonbengtsson/jsPDF-AutoTable | ---
+++
@@ -6,7 +6,7 @@
// defined and the way jspdf is exported makes it hard to implement
// https://stackoverflow.com/q/55328516/827047
-type AutoTable = import('jspdf-autotable').autoTable;
+import { autoTable as AutoTable } from 'jspdf-autotable';
// stats from https://en.wikipedia.org/wiki/World_Happiness_Report (2018)
var head = [['ID', 'Country', 'Rank', 'Capital']]; |
d88128b146afdae227a8c70be9483e7a0eb3e6af | ts/components/conversation/DeliveryIssueNotification.stories.tsx | ts/components/conversation/DeliveryIssueNotification.stories.tsx | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { setup as setupI18n } from '../../../js/modules/i18n';
import enMessages from '../../../_locales/en/messages.json';
import { DeliveryIssueNotification } from './DeliveryIssueNotification';
import { getDefaultConversation } from '../../test-both/helpers/getDefaultConversation';
const i18n = setupI18n('en', enMessages);
const sender = getDefaultConversation();
storiesOf('Components/Conversation/DeliveryIssueNotification', module).add(
'Default',
() => {
return (
<DeliveryIssueNotification
i18n={i18n}
inGroup={false}
learnMoreAboutDeliveryIssue={action('learnMoreAboutDeliveryIssue')}
sender={sender}
/>
);
}
);
storiesOf('Components/Conversation/DeliveryIssueNotification', module).add(
'In Group',
() => {
return (
<DeliveryIssueNotification
i18n={i18n}
inGroup
learnMoreAboutDeliveryIssue={action('learnMoreAboutDeliveryIssue')}
sender={sender}
/>
);
}
);
| // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { setup as setupI18n } from '../../../js/modules/i18n';
import enMessages from '../../../_locales/en/messages.json';
import { DeliveryIssueNotification } from './DeliveryIssueNotification';
import { getDefaultConversation } from '../../test-both/helpers/getDefaultConversation';
const i18n = setupI18n('en', enMessages);
const sender = getDefaultConversation();
storiesOf('Components/Conversation/DeliveryIssueNotification', module).add(
'Default',
() => {
return (
<DeliveryIssueNotification
i18n={i18n}
inGroup={false}
learnMoreAboutDeliveryIssue={action('learnMoreAboutDeliveryIssue')}
sender={sender}
/>
);
}
);
storiesOf('Components/Conversation/DeliveryIssueNotification', module).add(
'In Group',
() => {
return (
<DeliveryIssueNotification
i18n={i18n}
inGroup
learnMoreAboutDeliveryIssue={action('learnMoreAboutDeliveryIssue')}
sender={sender}
/>
);
}
);
| Remove extra license header comment from a story | Remove extra license header comment from a story
| TypeScript | agpl-3.0 | nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop | ---
+++
@@ -1,6 +1,3 @@
-// Copyright 2021 Signal Messenger, LLC
-// SPDX-License-Identifier: AGPL-3.0-only
-
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
|
914925ebd2f590b022a5647f4862d3295d1fcdc0 | modules/searchbar/types.ts | modules/searchbar/types.ts | export type Props = {
getRef?: any
active?: boolean
backButtonAndroid?: 'search' | boolean
backgroundColor?: string
onCancel: () => any
onChange: (data?: string) => any
onFocus: () => any
onSubmit: () => any
placeholder?: string
style?: any
textFieldBackgroundColor?: string
value: string
}
| export type Props = {
getRef?: any
active?: boolean
backButtonAndroid?: 'search' | boolean
backgroundColor?: string
onCancel: () => any
onChange: (data: string) => any
onFocus: () => any
onSubmit: () => any
placeholder?: string
style?: any
textFieldBackgroundColor?: string
value: string
}
| Resolve some TS2769 errors by forcing data to a string | m/searchbar: Resolve some TS2769 errors by forcing data to a string
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
| TypeScript | agpl-3.0 | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | ---
+++
@@ -4,7 +4,7 @@
backButtonAndroid?: 'search' | boolean
backgroundColor?: string
onCancel: () => any
- onChange: (data?: string) => any
+ onChange: (data: string) => any
onFocus: () => any
onSubmit: () => any
placeholder?: string |
d3ff099402bb1e55b9a785f930bcef925a26fa57 | src/Test/Ast/Helpers.ts | src/Test/Ast/Helpers.ts | import { expect } from 'chai'
import Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { InlineSyntaxNode } from '../../SyntaxNodes/InlineSyntaxNode'
export function insideDocumentAndParagraph(nodes: InlineSyntaxNode[]): DocumentNode {
return new DocumentNode([
new ParagraphNode(nodes)
])
}
export function expectEveryCombinationOf(
args: {
firstHalves: string[],
secondHalves: string[],
toProduce: DocumentNode
}) {
const { firstHalves, secondHalves, toProduce } = args
for (const firstHalf of firstHalves) {
for (const secondHalf of secondHalves) {
expect(Up.toAst(firstHalf + secondHalf)).to.be.equal(toProduce)
}
}
}
| import { expect } from 'chai'
import Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { InlineSyntaxNode } from '../../SyntaxNodes/InlineSyntaxNode'
export function insideDocumentAndParagraph(nodes: InlineSyntaxNode[]): DocumentNode {
return new DocumentNode([
new ParagraphNode(nodes)
])
}
export function expectEveryCombinationOf(
args: {
firstHalves: string[],
secondHalves: string[],
toProduce: DocumentNode
}) {
const { firstHalves, secondHalves, toProduce } = args
for (const firstHalf of firstHalves) {
for (const secondHalf of secondHalves) {
expect(Up.toAst(firstHalf + secondHalf)).to.be.eql(toProduce)
}
}
}
| Fix expectEveryCombinationOf; pass 1 test | Fix expectEveryCombinationOf; pass 1 test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -4,6 +4,7 @@
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { InlineSyntaxNode } from '../../SyntaxNodes/InlineSyntaxNode'
+
export function insideDocumentAndParagraph(nodes: InlineSyntaxNode[]): DocumentNode {
return new DocumentNode([
@@ -21,7 +22,7 @@
for (const firstHalf of firstHalves) {
for (const secondHalf of secondHalves) {
- expect(Up.toAst(firstHalf + secondHalf)).to.be.equal(toProduce)
+ expect(Up.toAst(firstHalf + secondHalf)).to.be.eql(toProduce)
}
}
} |
727c60050b127b739742608959f2d17b92d6469b | src/background/index.ts | src/background/index.ts | import {Extension} from './extension';
// Initialize extension
const extension = new Extension();
extension.start();
chrome.runtime.onInstalled.addListener(({reason}) => {
if (reason === 'install') {
// TODO: Show help page.
chrome.tabs.create({url: 'http://darkreader.org/blog/dynamic-theme/'});
extension.news.markAsRead('dynamic-theme');
}
});
declare const __DEBUG__: boolean;
const DEBUG = __DEBUG__;
if (DEBUG) {
// Reload extension on connection
const listen = () => {
const req = new XMLHttpRequest();
req.open('GET', 'http://localhost:8890/', true);
req.overrideMimeType('text/plain');
req.onload = () => {
if (req.status >= 200 && req.status < 300 && req.responseText === 'reload') {
chrome.runtime.reload();
} else {
setTimeout(listen, 2000);
}
};
req.onerror = () => setTimeout(listen, 2000);
req.send();
};
setTimeout(listen, 2000);
}
| import {Extension} from './extension';
// Initialize extension
const extension = new Extension();
extension.start();
chrome.runtime.onInstalled.addListener(({reason}) => {
if (reason === 'install') {
// TODO: Show help page.
chrome.tabs.create({url: 'http://darkreader.org/blog/dynamic-theme/'});
extension.news.markAsRead('dynamic-theme');
}
if (Boolean(localStorage.getItem('darkreader-4-release-notes-shown'))) {
extension.news.markAsRead('dynamic-theme')
.then(() => localStorage.removeItem('darkreader-4-release-notes-shown'));
}
});
declare const __DEBUG__: boolean;
const DEBUG = __DEBUG__;
if (DEBUG) {
// Reload extension on connection
const listen = () => {
const req = new XMLHttpRequest();
req.open('GET', 'http://localhost:8890/', true);
req.overrideMimeType('text/plain');
req.onload = () => {
if (req.status >= 200 && req.status < 300 && req.responseText === 'reload') {
chrome.runtime.reload();
} else {
setTimeout(listen, 2000);
}
};
req.onerror = () => setTimeout(listen, 2000);
req.send();
};
setTimeout(listen, 2000);
}
| Clear localstorage release notes flag | Clear localstorage release notes flag
| TypeScript | mit | alexanderby/darkreader,darkreader/darkreader,darkreader/darkreader,alexanderby/darkreader,darkreader/darkreader,alexanderby/darkreader | ---
+++
@@ -9,6 +9,10 @@
// TODO: Show help page.
chrome.tabs.create({url: 'http://darkreader.org/blog/dynamic-theme/'});
extension.news.markAsRead('dynamic-theme');
+ }
+ if (Boolean(localStorage.getItem('darkreader-4-release-notes-shown'))) {
+ extension.news.markAsRead('dynamic-theme')
+ .then(() => localStorage.removeItem('darkreader-4-release-notes-shown'));
}
});
|
798b5ecaae660d3e9ea672c602ca082283ebbfb7 | src/main/app/proxerapi/wait_login.ts | src/main/app/proxerapi/wait_login.ts | const promiseCallbacks: Function[] = [];
let loggedIn = false;
export function whenLogin(): Promise<void> {
if(loggedIn) {
return Promise.resolve();
} else {
return new Promise<void>(resolve => {
promiseCallbacks.push(resolve);
});
}
}
export function finishLogin() {
this.loggedIn = true;
promiseCallbacks.forEach(callback => callback());
}
| const promiseCallbacks: Function[] = [];
let loggedIn = false;
export function whenLogin(): Promise<void> {
if(loggedIn) {
return Promise.resolve();
} else {
return new Promise<void>(resolve => {
promiseCallbacks.push(resolve);
});
}
}
export function finishLogin() {
loggedIn = true;
promiseCallbacks.forEach(callback => callback());
while(promiseCallbacks.length > 0) {
promiseCallbacks.pop();
}
}
| Fix error on successful login | Fix error on successful login
| TypeScript | mit | kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop | ---
+++
@@ -12,6 +12,9 @@
}
export function finishLogin() {
- this.loggedIn = true;
+ loggedIn = true;
promiseCallbacks.forEach(callback => callback());
+ while(promiseCallbacks.length > 0) {
+ promiseCallbacks.pop();
+ }
} |
0508832ca6cc8a5c862e67a284a4fc203015ecd9 | modules/tinymce/src/plugins/table/main/ts/core/Clipboard.ts | modules/tinymce/src/plugins/table/main/ts/core/Clipboard.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { HTMLTableRowElement } from '@ephox/dom-globals';
import { Cell, Option } from '@ephox/katamari';
import { Element } from '@ephox/sugar';
export interface Clipboard {
getRows: () => Option<Element<HTMLTableRowElement>[]>;
setRows: (rows: Option<Element<HTMLTableRowElement>[]>) => void;
clearRows: () => void;
getColumns: () => Option<Element<HTMLTableRowElement>[]>;
setColumns: (columns: Option<Element<HTMLTableRowElement>[]>) => void;
clearColumns: () => void;
}
export const Clipboard = (): Clipboard => {
const rows = Cell(Option.none<Element<HTMLTableRowElement>[]>());
const cols = Cell(Option.none<Element<HTMLTableRowElement>[]>());
return {
getRows: rows.get,
setRows: rows.set,
clearRows: () => rows.set(Option.none()),
getColumns: cols.get,
setColumns: cols.set,
clearColumns: () => cols.set(Option.none())
};
};
| /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { HTMLTableRowElement } from '@ephox/dom-globals';
import { Cell, Option } from '@ephox/katamari';
import { Element } from '@ephox/sugar';
export interface Clipboard {
getRows: () => Option<Element<HTMLTableRowElement>[]>;
setRows: (rows: Option<Element<HTMLTableRowElement>[]>) => void;
clearRows: () => void;
getColumns: () => Option<Element<HTMLTableRowElement>[]>;
setColumns: (columns: Option<Element<HTMLTableRowElement>[]>) => void;
clearColumns: () => void;
}
export const Clipboard = (): Clipboard => {
const rows = Cell(Option.none<Element<HTMLTableRowElement>[]>());
const cols = Cell(Option.none<Element<HTMLTableRowElement>[]>());
const clearClipboard = (clipboard: Cell<Option<Element<any>[]>>) => {
clipboard.set(Option.none());
};
return {
getRows: rows.get,
setRows: (r: Option<Element<HTMLTableRowElement>[]>) => {
rows.set(r);
clearClipboard(cols);
},
clearRows: () => clearClipboard(rows),
getColumns: cols.get,
setColumns: (c: Option<Element<HTMLTableRowElement>[]>) => {
cols.set(c);
clearClipboard(rows);
},
clearColumns: () => clearClipboard(cols)
};
};
| Clear previous rows/column clipboard content when setting new content | TINY-6006: Clear previous rows/column clipboard content when setting new content
| TypeScript | mit | tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,FernCreek/tinymce,FernCreek/tinymce,FernCreek/tinymce,TeamupCom/tinymce,tinymce/tinymce | ---
+++
@@ -23,12 +23,22 @@
const rows = Cell(Option.none<Element<HTMLTableRowElement>[]>());
const cols = Cell(Option.none<Element<HTMLTableRowElement>[]>());
+ const clearClipboard = (clipboard: Cell<Option<Element<any>[]>>) => {
+ clipboard.set(Option.none());
+ };
+
return {
getRows: rows.get,
- setRows: rows.set,
- clearRows: () => rows.set(Option.none()),
+ setRows: (r: Option<Element<HTMLTableRowElement>[]>) => {
+ rows.set(r);
+ clearClipboard(cols);
+ },
+ clearRows: () => clearClipboard(rows),
getColumns: cols.get,
- setColumns: cols.set,
- clearColumns: () => cols.set(Option.none())
+ setColumns: (c: Option<Element<HTMLTableRowElement>[]>) => {
+ cols.set(c);
+ clearClipboard(rows);
+ },
+ clearColumns: () => clearClipboard(cols)
};
}; |
f3d1da4f4e56c80722d39fbb007ec8a3c76cce20 | src/Parsing/ParseInline.ts | src/Parsing/ParseInline.ts | import { ParseResult } from './ParseResult'
import { CompletedParseResult } from './CompletedParseResult'
import { FailedParseResult } from './FailedParseResult'
import { Matcher } from '../Matching/Matcher'
import { RichSyntaxNodeType } from '../SyntaxNodes/RichSyntaxNode'
import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode'
import { SyntaxNode } from '../SyntaxNodes/SyntaxNode'
import { PlainTextNode } from '../SyntaxNodes/PlainTextNode'
import { InlineCodeNode } from '../SyntaxNodes/InlineCodeNode'
import { EmphasisNode } from '../SyntaxNodes/EmphasisNode'
import { StressNode } from '../SyntaxNodes/StressNode'
import { RevisionDeletionNode } from '../SyntaxNodes/RevisionDeletionNode'
import { RevisionInsertionNode } from '../SyntaxNodes/RevisionInsertionNode'
import { SpoilerNode } from '../SyntaxNodes/SpoilerNode'
export function parseInline(text: string, parentNode: RichSyntaxNode): ParseResult {
return parse(new Matcher(text), parentNode)
}
function parse(matcher: Matcher, parentNode: RichSyntaxNode): ParseResult {
const nodes: SyntaxNode[] = []
while (!matcher.done()) {
const result = matcher.matchAnyChar()
nodes.push(new PlainTextNode(result.matchedText))
matcher.advance(result)
}
return new CompletedParseResult(nodes, matcher.index)
} | import { ParseResult } from './ParseResult'
import { CompletedParseResult } from './CompletedParseResult'
import { FailedParseResult } from './FailedParseResult'
import { Matcher } from '../Matching/Matcher'
import { MatchResult } from '../Matching/MatchResult'
import { RichSyntaxNodeType } from '../SyntaxNodes/RichSyntaxNode'
import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode'
import { SyntaxNode } from '../SyntaxNodes/SyntaxNode'
import { PlainTextNode } from '../SyntaxNodes/PlainTextNode'
import { InlineCodeNode } from '../SyntaxNodes/InlineCodeNode'
import { EmphasisNode } from '../SyntaxNodes/EmphasisNode'
import { StressNode } from '../SyntaxNodes/StressNode'
import { RevisionDeletionNode } from '../SyntaxNodes/RevisionDeletionNode'
import { RevisionInsertionNode } from '../SyntaxNodes/RevisionInsertionNode'
import { SpoilerNode } from '../SyntaxNodes/SpoilerNode'
export function parseInline(text: string, parentNode: RichSyntaxNode): ParseResult {
return new InlineParser(new Matcher(text), parentNode).result
}
class InlineParser {
public result: ParseResult
constructor(private matcher: Matcher, private parentNode: RichSyntaxNode) {
const nodes: SyntaxNode[] = []
while (!matcher.done()) {
const result = matcher.matchAnyChar()
nodes.push(new PlainTextNode(result.matchedText))
matcher.advance(result)
}
this.result = new CompletedParseResult(nodes, matcher.index)
}
} | Make inline parser a class | Make inline parser a class
| TypeScript | mit | start/up,start/up | ---
+++
@@ -3,6 +3,7 @@
import { FailedParseResult } from './FailedParseResult'
import { Matcher } from '../Matching/Matcher'
+import { MatchResult } from '../Matching/MatchResult'
import { RichSyntaxNodeType } from '../SyntaxNodes/RichSyntaxNode'
import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode'
@@ -17,18 +18,22 @@
import { SpoilerNode } from '../SyntaxNodes/SpoilerNode'
export function parseInline(text: string, parentNode: RichSyntaxNode): ParseResult {
- return parse(new Matcher(text), parentNode)
+ return new InlineParser(new Matcher(text), parentNode).result
}
-function parse(matcher: Matcher, parentNode: RichSyntaxNode): ParseResult {
- const nodes: SyntaxNode[] = []
+class InlineParser {
+ public result: ParseResult
- while (!matcher.done()) {
- const result = matcher.matchAnyChar()
- nodes.push(new PlainTextNode(result.matchedText))
+ constructor(private matcher: Matcher, private parentNode: RichSyntaxNode) {
+ const nodes: SyntaxNode[] = []
- matcher.advance(result)
+ while (!matcher.done()) {
+ const result = matcher.matchAnyChar()
+ nodes.push(new PlainTextNode(result.matchedText))
+
+ matcher.advance(result)
+ }
+
+ this.result = new CompletedParseResult(nodes, matcher.index)
}
-
- return new CompletedParseResult(nodes, matcher.index)
} |
897e10a81e3495c7749977a51cc4b82602f9ba03 | tests/cases/fourslash/jsxExpressionFollowedByIdentifier.ts | tests/cases/fourslash/jsxExpressionFollowedByIdentifier.ts | /// <reference path="fourslash.ts" />
//@Filename: jsxExpressionFollowedByIdentifier.tsx
////declare var React: any;
////declare var x: string;
////const a = <div>{<div />/*1*/x/*2*/}</div>
goTo.marker('1');
verify.getSyntacticDiagnostics([{
code: 1005,
message: "'}' expected.",
range: {
fileName: test.marker('1').fileName,
pos: test.marker('1').position,
end: test.marker('2').position,
}
}]);
verify.quickInfoIs('var x: string'); | /// <reference path="fourslash.ts" />
//@Filename: jsxExpressionFollowedByIdentifier.tsx
////declare var React: any;
////declare var x: string;
////const a = <div>{<div />[|x|]}</div>
const range = test.ranges()[0];
verify.getSyntacticDiagnostics([{
code: 1005,
message: "'}' expected.",
range,
}]);
verify.quickInfoAt(range, 'var x: string'); | Use range instead of two markers | Use range instead of two markers
| TypeScript | apache-2.0 | alexeagle/TypeScript,kpreisser/TypeScript,RyanCavanaugh/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,weswigham/TypeScript,kpreisser/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,weswigham/TypeScript,kitsonk/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,SaschaNaz/TypeScript,minestarks/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,minestarks/TypeScript,microsoft/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,microsoft/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,SaschaNaz/TypeScript,kitsonk/TypeScript | ---
+++
@@ -3,16 +3,12 @@
//@Filename: jsxExpressionFollowedByIdentifier.tsx
////declare var React: any;
////declare var x: string;
-////const a = <div>{<div />/*1*/x/*2*/}</div>
+////const a = <div>{<div />[|x|]}</div>
-goTo.marker('1');
+const range = test.ranges()[0];
verify.getSyntacticDiagnostics([{
code: 1005,
message: "'}' expected.",
- range: {
- fileName: test.marker('1').fileName,
- pos: test.marker('1').position,
- end: test.marker('2').position,
- }
+ range,
}]);
-verify.quickInfoIs('var x: string');
+verify.quickInfoAt(range, 'var x: string'); |
f3eec97cbc2d0632b9700c4b9f3f398bf1c51463 | src/fe/components/PathDetailDisplay/ProcedureBox/ProcedureBox.tsx | src/fe/components/PathDetailDisplay/ProcedureBox/ProcedureBox.tsx | import * as React from 'react'
import Procedure from "../../../../definitions/auxillary/Procedure"
interface Props {
procedureList: Procedure[]
}
class ProcedureBox extends React.PureComponent<Props, {}> {
render() {
return (
<div>
{
this.props.procedureList.map(
(procedure: Procedure, index: number) => (
<div key={procedure.name['en']}>
{index + 1}
{'. '}
{procedure.name['en']}
</div>
)
)
}
</div>
)
}
}
export default ProcedureBox
| import * as React from 'react'
import Procedure from "../../../../definitions/auxillary/Procedure"
interface Props {
procedureList: Procedure[]
}
class ProcedureBox extends React.PureComponent<Props, {}> {
render() {
return (
<div>
{this.props.procedureList.map(
(procedure: Procedure, index: number) => (
<div key={procedure.name['en']}>
{index + 1}
{'. '}
{procedure.name['en']}
</div>
)
)}
</div>
)
}
}
export default ProcedureBox
| Remove one level of indentation | Remove one level of indentation
Signed-off-by: Andy Shu <d9a5ae79e0620530e640970c782273ccd89702f2@gmail.com>
| TypeScript | agpl-3.0 | wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate | ---
+++
@@ -9,17 +9,15 @@
render() {
return (
<div>
- {
- this.props.procedureList.map(
- (procedure: Procedure, index: number) => (
- <div key={procedure.name['en']}>
- {index + 1}
- {'. '}
- {procedure.name['en']}
- </div>
- )
+ {this.props.procedureList.map(
+ (procedure: Procedure, index: number) => (
+ <div key={procedure.name['en']}>
+ {index + 1}
+ {'. '}
+ {procedure.name['en']}
+ </div>
)
- }
+ )}
</div>
)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.