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 |
|---|---|---|---|---|---|---|---|---|---|---|
13567a1588cd21158a9db0dd07a5a4df095200c3 | app/scripts/api.ts | app/scripts/api.ts | /// <reference types="whatwg-fetch" />
import { ApplicationInfo } from './model';
import { Reading } from './model';
import { formatDateBackend } from './dates';
const checkStatus = (response: Response): Response => {
if (response.status >= 200 && response.status < 300) {
return response
} else {
throw new Error(`HTTP error ${response.status}: ${response.statusText}`);
}
}
const parseJSON = (response: Response): any => {
return response.json()
}
// Exported only so that it can be tested.
export const get = (input: RequestInfo, init?: RequestInit): Promise<any> => {
return fetch(input, init)
.then(checkStatus)
.then(parseJSON);
}
export const retrieveApplicationInfo = (): Promise<ApplicationInfo> => {
return get('/api/info');
};
export const retrieveHistoricalReadings = (searchDate: Date): Promise<Reading> => {
const input = formatDateBackend(searchDate);
return get(`/api/history?date=${input}`);
}; | /// <reference types="whatwg-fetch" />
import { ApplicationInfo } from './model';
import { Reading } from './model';
import { formatDateBackend } from './dates';
const defaultOptions: RequestInit = {
credentials: 'same-origin'
}
const checkStatus = (response: Response): Response => {
if (response.status >= 200 && response.status < 300) {
return response
} else {
throw new Error(`HTTP error ${response.status}: ${response.statusText}`);
}
}
const parseJSON = (response: Response): any => {
return response.json()
}
// Exported only so that it can be tested.
export const get = (input: RequestInfo, init?: RequestInit): Promise<any> => {
const options = { ...defaultOptions, init}
return fetch(input, options)
.then(checkStatus)
.then(parseJSON);
}
export const retrieveApplicationInfo = (): Promise<ApplicationInfo> => {
return get('/api/info');
};
export const retrieveHistoricalReadings = (searchDate: Date): Promise<Reading> => {
const input = formatDateBackend(searchDate);
return get(`/api/history?date=${input}`);
}; | Allow to send credentials with fetch requests | Allow to send credentials with fetch requests
| TypeScript | mit | mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web | ---
+++
@@ -3,6 +3,10 @@
import { ApplicationInfo } from './model';
import { Reading } from './model';
import { formatDateBackend } from './dates';
+
+const defaultOptions: RequestInit = {
+ credentials: 'same-origin'
+}
const checkStatus = (response: Response): Response => {
if (response.status >= 200 && response.status < 300) {
@@ -18,7 +22,8 @@
// Exported only so that it can be tested.
export const get = (input: RequestInfo, init?: RequestInit): Promise<any> => {
- return fetch(input, init)
+ const options = { ...defaultOptions, init}
+ return fetch(input, options)
.then(checkStatus)
.then(parseJSON);
} |
d53c9bec261eef6d7c11aeeeca309bff9a7c9739 | packages/core/src/model/tags/Tags.ts | packages/core/src/model/tags/Tags.ts | import { match } from 'tiny-types';
import { ArbitraryTag, IssueTag, ManualTag, Tag } from './';
/**
* @package
*/
export class Tags {
private static Pattern = /^@([\w-]+)[:\s]?(.*)/i;
public static from(text: string): Tag[] {
const [ , type, val ] = Tags.Pattern.exec(text);
return match<Tag[]>(type.toLowerCase())
.when('manual', _ => [ new ManualTag() ])
// todo: map as arbitrary tag if value === ''; look up ticket id
.when(/issues?/, _ => val.split(',').map(value => new IssueTag(value.trim())))
.else(value => [ new ArbitraryTag(value.trim()) ]);
}
}
| import { match } from 'tiny-types';
import { ArbitraryTag, IssueTag, ManualTag, Tag } from './';
/**
* @package
*/
export class Tags {
private static Pattern = /^@([\w-]+)[:\s]?(.*)/i;
public static from(text: string): Tag[] {
const [ , type, val ] = Tags.Pattern.exec(text);
return match<Tag[]>(type.toLowerCase())
.when('manual', _ => [ new ManualTag() ])
// todo: map as arbitrary tag if value === ''; look up ticket id
.when(/^issues?$/, _ => val.split(',').map(value => new IssueTag(value.trim())))
.else(value => [ new ArbitraryTag(value.trim()) ]);
}
}
| Support tags with "issues" in their name, i.e. "known_issues". | fix(core): Support tags with "issues" in their name, i.e. "known_issues".
| TypeScript | apache-2.0 | jan-molak/serenity-js,jan-molak/serenity-js,jan-molak/serenity-js,jan-molak/serenity-js | ---
+++
@@ -14,7 +14,7 @@
return match<Tag[]>(type.toLowerCase())
.when('manual', _ => [ new ManualTag() ])
// todo: map as arbitrary tag if value === ''; look up ticket id
- .when(/issues?/, _ => val.split(',').map(value => new IssueTag(value.trim())))
+ .when(/^issues?$/, _ => val.split(',').map(value => new IssueTag(value.trim())))
.else(value => [ new ArbitraryTag(value.trim()) ]);
}
} |
e23a8f4e8201ff3f452740b7b7a5de85dbd440e1 | src/Components/Title.tsx | src/Components/Title.tsx | import React from "react"
import styled from "styled-components"
import * as fonts from "../Assets/Fonts"
import { media } from "./Helpers"
type TitleSize = "xxsmall" | "small" | "medium" | "large" | "xlarge" | "xxlarge"
interface TitleProps extends React.HTMLProps<HTMLDivElement> {
titleSize?: TitleSize
color?: string
}
const titleSizes = {
xxsmall: "13px",
small: "25px",
medium: "30px",
large: "37px",
xlarge: "50px",
xxlarge: "72px",
}
const Title: React.SFC<TitleProps> = props => {
const newProps: TitleProps = { ...props }
delete newProps.titleSize
return <div {...newProps}>{props.children}</div>
}
const StyledTitle = styled(Title)`
font-size: ${props => titleSizes[props.titleSize]};
color: ${props => props.color};
margin: 20px 0;
${fonts.secondary.style} ${media.sm`
font-size: ${titleSizes.small};
`};
`
StyledTitle.defaultProps = {
titleSize: "medium",
color: "inherit",
}
export default StyledTitle
| import React from "react"
import styled from "styled-components"
import * as fonts from "../Assets/Fonts"
import { media } from "./Helpers"
type TitleSize = "xxsmall" | "small" | "medium" | "large" | "xlarge" | "xxlarge"
interface TitleProps extends React.HTMLProps<HTMLDivElement> {
titleSize?: TitleSize
color?: string
}
const titleSizes = {
xxsmall: "13px",
small: "25px",
medium: "30px",
large: "37px",
xlarge: "50px",
xxlarge: "72px",
}
const Title: React.SFC<TitleProps> = props => {
const newProps: TitleProps = { ...props }
delete newProps.titleSize
return <div {...newProps}>{props.children}</div>
}
const StyledTitle = styled(Title)`
font-size: ${props => titleSizes[props.titleSize]};
color: ${props => props.color};
margin: 20px 0;
${fonts.secondary.style};
${media.sm`
font-size: ${titleSizes.small};
`};
`
StyledTitle.defaultProps = {
titleSize: "medium",
color: "inherit",
}
export default StyledTitle
| Add semicolon to separate styles | Add semicolon to separate styles
| TypeScript | mit | xtina-starr/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force | ---
+++
@@ -30,7 +30,8 @@
font-size: ${props => titleSizes[props.titleSize]};
color: ${props => props.color};
margin: 20px 0;
- ${fonts.secondary.style} ${media.sm`
+ ${fonts.secondary.style};
+ ${media.sm`
font-size: ${titleSizes.small};
`};
` |
d8678603245a969e7dabc2e834efc08985884d6b | templates/module/_name.ts | templates/module/_name.ts | import { <%= pName %>Config } from "./<%= hName %>.config";
import { <%= pName %>Controller } from "./<%= hName %>.controller";
let module = angular
.module("<%= appName %>.<%= name %>", [])
.controller("<%= pName %>Controller", <%= pName %>Controller)
.config(<%= pName %>Config);
let <%= name %> = module.name;
export { <%= name %> }; | <% if (!moduleOnly) { %>import { <%= pName %>Config } from "./<%= hName %>.config";
import { <%= pName %>Controller } from "./<%= hName %>.controller";
<% } %>let module = angular
.module("<%= appName %>.<%= name %>", [])<% if (!moduleOnly) { %>
.controller("<%= pName %>Controller", <%= pName %>Controller)
.config(<%= pName %>Config)<% } %>;
let <%= name %> = module.name;
export { <%= name %> }; | Edit base module file to include moduleOnly | Edit base module file to include moduleOnly
| TypeScript | mit | Kurtz1993/ngts-cli,Kurtz1993/ngts-cli,Kurtz1993/ngts-cli | ---
+++
@@ -1,10 +1,10 @@
-import { <%= pName %>Config } from "./<%= hName %>.config";
+<% if (!moduleOnly) { %>import { <%= pName %>Config } from "./<%= hName %>.config";
import { <%= pName %>Controller } from "./<%= hName %>.controller";
-let module = angular
- .module("<%= appName %>.<%= name %>", [])
+<% } %>let module = angular
+ .module("<%= appName %>.<%= name %>", [])<% if (!moduleOnly) { %>
.controller("<%= pName %>Controller", <%= pName %>Controller)
- .config(<%= pName %>Config);
+ .config(<%= pName %>Config)<% } %>;
let <%= name %> = module.name;
|
16a02144429e538aa2e6a0bc8ef082df13206339 | app/scripts/components/home/Changelog.tsx | app/scripts/components/home/Changelog.tsx | import React from 'react';
import Icon from '@mdi/react';
import { mdiCloseCircleOutline } from '@mdi/js';
import content from '../../../../CHANGELOG.md';
import Modal from '../page/Modal';
interface ChangelogProps {
close: () => void;
}
const Changelog: React.FC<ChangelogProps> = ({ close }) => (
<Modal close={close}>
<div className="overlay-modal-content changelog" dangerouslySetInnerHTML={{ __html: content }} />
<div className="border-top ptm">
<a href="https://github.com/benct/tomlin-web/blob/master/CHANGELOG.md" target="_blank" rel="noopener noreferrer">
View on GitHub
</a>
<button className="button-blank float-right" onClick={close}>
<Icon path={mdiCloseCircleOutline} size="28px" title="Close" />
</button>
</div>
</Modal>
);
export default React.memo(Changelog);
| import React from 'react';
import Icon from '@mdi/react';
import { mdiCloseCircleOutline, mdiGithubCircle } from '@mdi/js';
import content from '../../../../CHANGELOG.md';
import Modal from '../page/Modal';
interface ChangelogProps {
close: () => void;
}
const Changelog: React.FC<ChangelogProps> = ({ close }) => (
<Modal close={close}>
<div className="overlay-modal-content changelog" dangerouslySetInnerHTML={{ __html: content }} />
<div className="border-top ptm">
<a href="https://github.com/benct/tomlin-web/blob/master/CHANGELOG.md" target="_blank" rel="noopener noreferrer">
<Icon path={mdiGithubCircle} size="28px" title="View on GitHub" className="valign-middle" />
<span className="valign-middle mlm">View on GitHub</span>
</a>
<button className="button-icon pan float-right" onClick={close}>
<Icon path={mdiCloseCircleOutline} size="28px" title="Close" />
</button>
</div>
</Modal>
);
export default React.memo(Changelog);
| Add github icon to changelog modal | Add github icon to changelog modal
| TypeScript | mit | benct/tomlin-web,benct/tomlin-web | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
import Icon from '@mdi/react';
-import { mdiCloseCircleOutline } from '@mdi/js';
+import { mdiCloseCircleOutline, mdiGithubCircle } from '@mdi/js';
import content from '../../../../CHANGELOG.md';
import Modal from '../page/Modal';
@@ -14,9 +14,10 @@
<div className="overlay-modal-content changelog" dangerouslySetInnerHTML={{ __html: content }} />
<div className="border-top ptm">
<a href="https://github.com/benct/tomlin-web/blob/master/CHANGELOG.md" target="_blank" rel="noopener noreferrer">
- View on GitHub
+ <Icon path={mdiGithubCircle} size="28px" title="View on GitHub" className="valign-middle" />
+ <span className="valign-middle mlm">View on GitHub</span>
</a>
- <button className="button-blank float-right" onClick={close}>
+ <button className="button-icon pan float-right" onClick={close}>
<Icon path={mdiCloseCircleOutline} size="28px" title="Close" />
</button>
</div> |
e5b475ad8935957ac183937129a73147a3469b42 | src/@types/partials.ts | src/@types/partials.ts | /*
Copyright 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export interface IImageInfo {
size?: number;
mimetype?: string;
thumbnail_info?: { // eslint-disable-line camelcase
w?: number;
h?: number;
size?: number;
mimetype?: string;
};
w?: number;
h?: number;
}
export enum Visibility {
Public = "public",
Private = "private",
}
export enum Preset {
PrivateChat = "private_chat",
TrustedPrivateChat = "trusted_private_chat",
PublicChat = "public_chat",
}
| /*
Copyright 2021 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export interface IImageInfo {
size?: number;
mimetype?: string;
thumbnail_info?: { // eslint-disable-line camelcase
w?: number;
h?: number;
size?: number;
mimetype?: string;
};
w?: number;
h?: number;
}
export enum Visibility {
Public = "public",
Private = "private",
}
export enum Preset {
PrivateChat = "private_chat",
TrustedPrivateChat = "trusted_private_chat",
PublicChat = "public_chat",
}
// Knock and private are reserved keywords which are not yet implemented.
export enum JoinRule {
Public = "public",
Invite = "invite",
Private = "private", // reserved keyword, not yet implemented.
Knock = "knock", // MSC2403 - only valid inside experimental room versions at this time.
Restricted = "restricted", // MSC3083 - only valid inside experimental room versions at this time.
}
export enum GuestAccess {
CanJoin = "can_join",
Forbidden = "forbidden",
}
export enum HistoryVisibility {
Invited = "invited",
Joined = "joined",
Shared = "shared",
WorldReadable = "world_readable",
}
| Create Typescript types for JoinRule, GuestAccess, HistoryVisibility, including join_rule=restricted | Create Typescript types for JoinRule, GuestAccess, HistoryVisibility, including join_rule=restricted
| TypeScript | apache-2.0 | matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk | ---
+++
@@ -37,3 +37,23 @@
TrustedPrivateChat = "trusted_private_chat",
PublicChat = "public_chat",
}
+// Knock and private are reserved keywords which are not yet implemented.
+export enum JoinRule {
+ Public = "public",
+ Invite = "invite",
+ Private = "private", // reserved keyword, not yet implemented.
+ Knock = "knock", // MSC2403 - only valid inside experimental room versions at this time.
+ Restricted = "restricted", // MSC3083 - only valid inside experimental room versions at this time.
+}
+
+export enum GuestAccess {
+ CanJoin = "can_join",
+ Forbidden = "forbidden",
+}
+
+export enum HistoryVisibility {
+ Invited = "invited",
+ Joined = "joined",
+ Shared = "shared",
+ WorldReadable = "world_readable",
+} |
7bfc6c98753df69788abc3197e57400509cc0e34 | resources/assets/lib/gallery-contest.tsx | resources/assets/lib/gallery-contest.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 * as React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { nextVal } from 'utils/seq';
import GalleryContestVoteButton from './components/gallery-contest-vote-button';
import GalleryContestVoteProgress from './components/gallery-contest-vote-progress';
export default class GalleryContest {
private eventId: string;
private root: HTMLElement;
constructor(container: HTMLElement, pswp: any) {
this.root = container.querySelector('.js-pswp-buttons') as HTMLElement;
render(
(
<>
<GalleryContestVoteButton pswp={pswp} />
<GalleryContestVoteProgress />
</>
),
this.root,
);
this.eventId = `gallery-contest-${nextVal()}`;
$(document).on(`turbolinks:before-cache.${this.eventId}`, this.destroy);
pswp.listen('destroy', this.destroy);
}
destroy = () => {
unmountComponentAtNode(this.root);
$(document).off(`.${this.eventId}`);
};
}
| // 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 * as React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { nextVal } from 'utils/seq';
import GalleryContestVoteButton from 'components/gallery-contest-vote-button';
import GalleryContestVoteProgress from 'components/gallery-contest-vote-progress';
export default class GalleryContest {
private eventId: string;
private root: HTMLElement;
constructor(container: HTMLElement, pswp: any) {
this.root = container.querySelector('.js-pswp-buttons') as HTMLElement;
render(
(
<>
<GalleryContestVoteButton pswp={pswp} />
<GalleryContestVoteProgress />
</>
),
this.root,
);
this.eventId = `gallery-contest-${nextVal()}`;
$(document).on(`turbolinks:before-cache.${this.eventId}`, this.destroy);
pswp.listen('destroy', this.destroy);
}
destroy = () => {
unmountComponentAtNode(this.root);
$(document).off(`.${this.eventId}`);
};
}
| Remove ./ relative import marker | Remove ./ relative import marker
| TypeScript | agpl-3.0 | nanaya/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,nanaya/osu-web,nanaya/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,nanaya/osu-web,ppy/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,ppy/osu-web,ppy/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,ppy/osu-web,nanaya/osu-web,ppy/osu-web,LiquidPL/osu-web | ---
+++
@@ -4,8 +4,8 @@
import * as React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { nextVal } from 'utils/seq';
-import GalleryContestVoteButton from './components/gallery-contest-vote-button';
-import GalleryContestVoteProgress from './components/gallery-contest-vote-progress';
+import GalleryContestVoteButton from 'components/gallery-contest-vote-button';
+import GalleryContestVoteProgress from 'components/gallery-contest-vote-progress';
export default class GalleryContest {
private eventId: string; |
2359a79fa240b4687a75fbf4f78bd76d87e4d50b | src/app/appSettings.ts | src/app/appSettings.ts | export const appSettings = {
chatServerUrl: 'http://localhost:8000/'
} | export const appSettings = {
chatServerUrl: 'https://serene-basin-84996.herokuapp.com/'
} | Set to remote chat server url | Set to remote chat server url
| TypeScript | mit | rgripper/meetup-chat-app,rgripper/meetup-chat-app,rgripper/meetup-chat-app | ---
+++
@@ -1,3 +1,3 @@
export const appSettings = {
- chatServerUrl: 'http://localhost:8000/'
+ chatServerUrl: 'https://serene-basin-84996.herokuapp.com/'
} |
57ec07cdc8ea93eb49ddb72b2eee18f68335b831 | src/connector/validation.ts | src/connector/validation.ts | import dotf = require('dotf');
export const claspAuthenticated = async (): Promise<boolean> => {
const dotglobal = dotf('~', 'clasprc.json');
return dotglobal.exists();
};
| import dotf = require('dotf');
export const claspAuthenticated = async (): Promise<boolean> => {
const dotglobal = dotf.default('~', 'clasprc.json');
return dotglobal.exists();
};
| Fix for dotf is not a function | Fix for dotf is not a function
| TypeScript | apache-2.0 | googledatastudio/tooling,googledatastudio/tooling,googledatastudio/tooling | ---
+++
@@ -1,6 +1,6 @@
import dotf = require('dotf');
export const claspAuthenticated = async (): Promise<boolean> => {
- const dotglobal = dotf('~', 'clasprc.json');
+ const dotglobal = dotf.default('~', 'clasprc.json');
return dotglobal.exists();
}; |
03269c9b627ad24f48f5391dba104a76805eb31b | lib/ui/src/components/sidebar/Heading.tsx | lib/ui/src/components/sidebar/Heading.tsx | import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.base === 'light' ? theme.color.defaultText : theme.color.inverseText,
marginRight: 40,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
width: 'auto',
display: 'block',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.base === 'light' ? theme.color.inverseText : theme.color.defaultText,
marginRight: 40,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
width: 'auto',
display: 'block',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| FIX heading color in darkmode | FIX heading color in darkmode
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -12,7 +12,7 @@
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
- color: theme.base === 'light' ? theme.color.defaultText : theme.color.inverseText,
+ color: theme.base === 'light' ? theme.color.inverseText : theme.color.defaultText,
marginRight: 40,
display: 'flex',
width: '100%', |
fae9778fb611e1f92e8becc4ef9788306c1d8ab6 | src/index.ts | src/index.ts | // Fix some circular deps:
import "./core/node"
import "./types/type"
export {
types,
IType,
ISimpleType,
IComplexType,
IModelType,
ISnapshottable,
IExtendedObservableMap
} from "./types"
export * from "./core/mst-operations"
export { escapeJsonPath, unescapeJsonPath, IJsonPatch } from "./core/json-patch"
export {
decorate,
addMiddleware,
IMiddlewareEvent,
IMiddlewareHandler,
IMiddlewareEventType
} from "./core/action"
export { flow } from "./core/flow"
export { isStateTreeNode, IStateTreeNode } from "./core/node"
export {
applyAction,
onAction,
IActionRecorder,
ISerializedActionCall,
recordActions
} from "./middlewares/on-action"
| // Fix some circular deps:
import "./core/node"
import "./types/type"
export {
types,
IType,
ISimpleType,
IComplexType,
IModelType,
ISnapshottable,
IExtendedObservableMap
} from "./types"
export * from "./core/mst-operations"
export { escapeJsonPath, unescapeJsonPath, IJsonPatch } from "./core/json-patch"
export {
decorate,
addMiddleware,
IMiddlewareEvent,
IMiddlewareHandler,
IMiddlewareEventType
} from "./core/action"
export { flow } from "./core/flow"
export { process } from "./core/process"
export { isStateTreeNode, IStateTreeNode } from "./core/node"
export {
applyAction,
onAction,
IActionRecorder,
ISerializedActionCall,
recordActions
} from "./middlewares/on-action"
| Undo removal of process export | Undo removal of process export
| TypeScript | mit | mweststrate/mobx-state-tree,mobxjs/mobx-state-tree,mobxjs/mobx-state-tree,mobxjs/mobx-state-tree,mweststrate/mobx-state-tree,mobxjs/mobx-state-tree | ---
+++
@@ -22,6 +22,7 @@
IMiddlewareEventType
} from "./core/action"
export { flow } from "./core/flow"
+export { process } from "./core/process"
export { isStateTreeNode, IStateTreeNode } from "./core/node"
export { |
b533ed6ba7c719d006eb29054cef1f8f0eae2892 | src/client/app/dashboard/dashboard.routes.ts | src/client/app/dashboard/dashboard.routes.ts | import { Route } from '@angular/router';
import { HomeRoutes } from './home/index';
import { MapSettingsRoutes } from './map-settings/index';
import { CameraSettingsRoutes } from './camera-settings/index';
import { ChartRoutes } from './charts/index';
import { BlankPageRoutes } from './blank-page/index';
import { TableRoutes } from './tables/index';
import { FormRoutes } from './forms/index';
import { GridRoutes } from './grid/index';
import { BSComponentRoutes } from './bs-component/index';
import { BSElementRoutes } from './bs-element/index';
import { DashboardComponent } from './index';
export const DashboardRoutes: Route[] = [
{
path: 'dashboard',
component: DashboardComponent,
children: [
...HomeRoutes,
...MapSettingsRoutes,
...CameraSettingsRoutes,
...ChartRoutes,
...BSComponentRoutes,
...TableRoutes,
...BlankPageRoutes,
...FormRoutes,
...GridRoutes,
...BSElementRoutes
]
}
];
| import { Route } from '@angular/router';
import { HomeRoutes } from './home/index';
import { MapSettingsRoutes } from './map-settings/index';
import { CameraSettingsRoutes } from './camera-settings/index';
import { RealtimeStatisticRoutes } from './realtime-statistic/index';
// import { ChartRoutes } from './charts/index';
// import { BlankPageRoutes } from './blank-page/index';
// import { TableRoutes } from './tables/index';
// import { FormRoutes } from './forms/index';
// import { GridRoutes } from './grid/index';
// import { BSComponentRoutes } from './bs-component/index';
// import { BSElementRoutes } from './bs-element/index';
import { DashboardComponent } from './index';
export const DashboardRoutes: Route[] = [
{
path: 'dashboard',
component: DashboardComponent,
children: [
...HomeRoutes,
// Settings Components
...MapSettingsRoutes,
...CameraSettingsRoutes,
// Statistic Component
...RealtimeStatisticRoutes,
// ...ChartRoutes,
// ...BSComponentRoutes,
// ...TableRoutes,
// ...BlankPageRoutes,
// ...FormRoutes,
// ...GridRoutes,
// ...BSElementRoutes
]
}
];
| Add realtimeStatistic component Comment unused components | Add realtimeStatistic component
Comment unused components
| TypeScript | mit | CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient | ---
+++
@@ -3,13 +3,14 @@
import { HomeRoutes } from './home/index';
import { MapSettingsRoutes } from './map-settings/index';
import { CameraSettingsRoutes } from './camera-settings/index';
-import { ChartRoutes } from './charts/index';
-import { BlankPageRoutes } from './blank-page/index';
-import { TableRoutes } from './tables/index';
-import { FormRoutes } from './forms/index';
-import { GridRoutes } from './grid/index';
-import { BSComponentRoutes } from './bs-component/index';
-import { BSElementRoutes } from './bs-element/index';
+import { RealtimeStatisticRoutes } from './realtime-statistic/index';
+// import { ChartRoutes } from './charts/index';
+// import { BlankPageRoutes } from './blank-page/index';
+// import { TableRoutes } from './tables/index';
+// import { FormRoutes } from './forms/index';
+// import { GridRoutes } from './grid/index';
+// import { BSComponentRoutes } from './bs-component/index';
+// import { BSElementRoutes } from './bs-element/index';
import { DashboardComponent } from './index';
@@ -19,15 +20,21 @@
component: DashboardComponent,
children: [
...HomeRoutes,
+
+ // Settings Components
...MapSettingsRoutes,
...CameraSettingsRoutes,
- ...ChartRoutes,
- ...BSComponentRoutes,
- ...TableRoutes,
- ...BlankPageRoutes,
- ...FormRoutes,
- ...GridRoutes,
- ...BSElementRoutes
+
+ // Statistic Component
+ ...RealtimeStatisticRoutes,
+
+ // ...ChartRoutes,
+ // ...BSComponentRoutes,
+ // ...TableRoutes,
+ // ...BlankPageRoutes,
+ // ...FormRoutes,
+ // ...GridRoutes,
+ // ...BSElementRoutes
]
}
]; |
0352cf197d53c471d27994585bc2fde2781e050f | packages/rendermime-extension/src/index.ts | packages/rendermime-extension/src/index.ts | /*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
JupyterLab, JupyterLabPlugin
} from '@jupyterlab/application';
import {
ILatexTypesetter, IRenderMimeRegistry, RenderMimeRegistry,
standardRendererFactories
} from '@jupyterlab/rendermime';
/**
* A plugin providing a rendermime registry.
*/
const plugin: JupyterLabPlugin<RenderMimeRegistry> = {
id: '@jupyterlab/rendermime-extension:plugin',
optional: [ILatexTypesetter],
provides: IRenderMimeRegistry,
activate: activate,
autoStart: true
};
/**
* Export the plugin as default.
*/
export
default plugin;
/**
* Activate the rendermine plugin.
*/
function activate(app: JupyterLab, latexTypesetter: ILatexTypesetter) {
return new RenderMimeRegistry({
initialFactories: standardRendererFactories,
linkHandler: {
handleLink: (node, path) => {
app.commandLinker.connectNode(
node, 'file-operations:open', { path: path }
);
}
},
latexTypesetter
});
}
| /*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
JupyterLab, JupyterLabPlugin
} from '@jupyterlab/application';
import {
ILatexTypesetter, IRenderMimeRegistry, RenderMimeRegistry,
standardRendererFactories
} from '@jupyterlab/rendermime';
/**
* A plugin providing a rendermime registry.
*/
const plugin: JupyterLabPlugin<RenderMimeRegistry> = {
id: '@jupyterlab/rendermime-extension:plugin',
optional: [ILatexTypesetter],
provides: IRenderMimeRegistry,
activate: activate,
autoStart: true
};
/**
* Export the plugin as default.
*/
export
default plugin;
/**
* Activate the rendermine plugin.
*/
function activate(app: JupyterLab, latexTypesetter: ILatexTypesetter) {
return new RenderMimeRegistry({
initialFactories: standardRendererFactories,
linkHandler: {
handleLink: (node, path) => {
app.commandLinker.connectNode(
node, 'docmanager:open', { path: path }
);
}
},
latexTypesetter
});
}
| Fix link handler for renderers | Fix link handler for renderers
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -40,7 +40,7 @@
linkHandler: {
handleLink: (node, path) => {
app.commandLinker.connectNode(
- node, 'file-operations:open', { path: path }
+ node, 'docmanager:open', { path: path }
);
}
}, |
1e19be712461e783676ffd4e6152cf74b7f5b43a | A2/quickstart/src/app/modules/app/app.module.ts | A2/quickstart/src/app/modules/app/app.module.ts | import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "../../components/app/app.component";
import { AppCustomComponent } from "../../components/app-custom/app.custom.component";
import { RacingDataService } from "../../services/racing-data.service";
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, AppCustomComponent ],
bootstrap: [ AppComponent ],
providers: [ RacingDataService ]
})
export class AppModule { }
| import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";
import { AppComponent } from "../../components/app/app.component";
import { AppCustomComponent } from "../../components/app-custom/app.custom.component";
import { RacingDataService } from "../../services/racing-data.service";
@NgModule({
imports: [ BrowserModule, FormsModule, HttpModule ],
declarations: [ AppComponent, AppCustomComponent ],
bootstrap: [ AppComponent ],
providers: [ RacingDataService ]
})
export class AppModule { }
| Add import { HttpModule } from "@angular/http"; Add HttpModule to imports section in @NgModule | Add import { HttpModule } from "@angular/http"; Add HttpModule to imports section in @NgModule
| TypeScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -1,13 +1,14 @@
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
+import { HttpModule } from "@angular/http";
import { AppComponent } from "../../components/app/app.component";
import { AppCustomComponent } from "../../components/app-custom/app.custom.component";
import { RacingDataService } from "../../services/racing-data.service";
@NgModule({
- imports: [ BrowserModule, FormsModule ],
+ imports: [ BrowserModule, FormsModule, HttpModule ],
declarations: [ AppComponent, AppCustomComponent ],
bootstrap: [ AppComponent ],
providers: [ RacingDataService ] |
03dfe8dd48c202ed991d4f2c78232988d39aab6e | lib/tasks/Typescript.ts | lib/tasks/Typescript.ts | import {buildHelper as helper} from "../Container";
const gulp = require("gulp");
const ts = require("gulp-typescript");
export default function Typescript() {
let settings = helper.getSettings(),
tsProject = ts.createProject("tsconfig.json");
return gulp.src(settings.scripts).pipe(tsProject()).js.pipe(gulp.dest(settings.distribution));
} | import {buildHelper as helper} from "../Container";
const gulp = require("gulp");
const ts = require("gulp-typescript");
export default function Typescript() {
let settings = helper.getSettings(),
tsProject = ts.createProject("tsconfig.json");
return gulp.src(settings.scripts)
.pipe(tsProject())
.on("error", function (error) {
process.exit(1);
})
.js.pipe(gulp.dest(settings.distribution));
} | Exit typescript with error code 1 if fails | Exit typescript with error code 1 if fails
| TypeScript | mit | mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild | ---
+++
@@ -6,5 +6,10 @@
let settings = helper.getSettings(),
tsProject = ts.createProject("tsconfig.json");
- return gulp.src(settings.scripts).pipe(tsProject()).js.pipe(gulp.dest(settings.distribution));
+ return gulp.src(settings.scripts)
+ .pipe(tsProject())
+ .on("error", function (error) {
+ process.exit(1);
+ })
+ .js.pipe(gulp.dest(settings.distribution));
} |
e7263d43e4454746c46b15d4faef805af8b883d1 | 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;
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;
}
}
| 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 {
if (this.store.has(key)) {
this.hits++;
return this.store.get(key);
} else {
this.misses++;
return this.set(key, this.func(key));
}
}
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;
}
}
| Remove extraneous variable. Return inside if/else | Remove extraneous variable. Return inside if/else
| TypeScript | mit | elwayman02/ember.js,qaiken/ember.js,Turbo87/ember.js,sandstrom/ember.js,bekzod/ember.js,knownasilya/ember.js,stefanpenner/ember.js,qaiken/ember.js,givanse/ember.js,sly7-7/ember.js,miguelcobain/ember.js,asakusuma/ember.js,emberjs/ember.js,jaswilli/ember.js,mfeckie/ember.js,kellyselden/ember.js,givanse/ember.js,sandstrom/ember.js,Turbo87/ember.js,intercom/ember.js,miguelcobain/ember.js,intercom/ember.js,elwayman02/ember.js,Turbo87/ember.js,emberjs/ember.js,jaswilli/ember.js,givanse/ember.js,mixonic/ember.js,givanse/ember.js,asakusuma/ember.js,cibernox/ember.js,knownasilya/ember.js,asakusuma/ember.js,miguelcobain/ember.js,cibernox/ember.js,cibernox/ember.js,GavinJoyce/ember.js,bekzod/ember.js,miguelcobain/ember.js,qaiken/ember.js,jaswilli/ember.js,sly7-7/ember.js,intercom/ember.js,mfeckie/ember.js,bekzod/ember.js,GavinJoyce/ember.js,mixonic/ember.js,asakusuma/ember.js,tildeio/ember.js,fpauser/ember.js,kellyselden/ember.js,elwayman02/ember.js,GavinJoyce/ember.js,stefanpenner/ember.js,mixonic/ember.js,jaswilli/ember.js,knownasilya/ember.js,qaiken/ember.js,cibernox/ember.js,kellyselden/ember.js,mfeckie/ember.js,fpauser/ember.js,Turbo87/ember.js,fpauser/ember.js,fpauser/ember.js,kellyselden/ember.js,GavinJoyce/ember.js,mfeckie/ember.js,sly7-7/ember.js,emberjs/ember.js,tildeio/ember.js,bekzod/ember.js,sandstrom/ember.js,elwayman02/ember.js,stefanpenner/ember.js,intercom/ember.js,tildeio/ember.js | ---
+++
@@ -8,17 +8,14 @@
}
get(key: T): V {
- let value;
if (this.store.has(key)) {
this.hits++;
- value = this.store.get(key);
+ return this.store.get(key);
} else {
this.misses++;
- value = this.set(key, this.func(key));
+ return this.set(key, this.func(key));
}
-
- return value;
}
set(key: T, value: V) { |
a688504413528c354fa35e647a4fbde55451f588 | src/sagas/playAudio.ts | src/sagas/playAudio.ts | import { call, select } from 'redux-saga/effects';
import { PlayAudio } from '../actions/audio';
import { RootState } from '../types';
const playAudioFile = async (file: HTMLAudioElement, volume: number) => {
try {
file.volume = volume;
return await file.play();
} catch (e) {
console.warn(e);
}
};
export function* playAudio(action: PlayAudio) {
const audioEnabled: boolean = yield select(
(state: RootState) => state.audioSettingsV1.enabled
);
try {
if (audioEnabled) {
const volume: number = yield select(
(state: RootState) => state.audioSettingsV1.volume
);
yield call(playAudioFile, action.file, volume);
}
} catch (e) {
console.warn('Playing audio failed.');
}
}
| import { call, select } from 'redux-saga/effects';
import { PlayAudio } from '../actions/audio';
import { RootState } from '../types';
const playAudioFile = async (file: HTMLAudioElement, volume: number) => {
try {
file.volume = volume * volume;
return await file.play();
} catch (e) {
console.warn(e);
}
};
export function* playAudio(action: PlayAudio) {
const audioEnabled: boolean = yield select(
(state: RootState) => state.audioSettingsV1.enabled
);
try {
if (audioEnabled) {
const volume: number = yield select(
(state: RootState) => state.audioSettingsV1.volume
);
yield call(playAudioFile, action.file, volume);
}
} catch (e) {
console.warn('Playing audio failed.');
}
}
| Improve granularity of volume controls. | Improve granularity of volume controls.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -4,7 +4,7 @@
const playAudioFile = async (file: HTMLAudioElement, volume: number) => {
try {
- file.volume = volume;
+ file.volume = volume * volume;
return await file.play();
} catch (e) {
console.warn(e); |
cc9441e1facd6ff4b1fd7847504b6640e1ecdfe3 | app/utils/status-bar-util.ts | app/utils/status-bar-util.ts | import * as application from "application";
// Make TypeScript happy
declare var UIResponder: any;
declare var UIStatusBarStyle: any;
declare var UIApplication: any;
declare var UIApplicationDelegate: any;
export function setStatusBarColors() {
if (application.ios) {
var AppDelegate = UIResponder.extend({
applicationDidFinishLaunchingWithOptions: function() {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent;
return true;
}
}, {
name: "AppDelegate",
protocols: [UIApplicationDelegate]
});
application.ios.delegate = AppDelegate;
}
}
| import * as application from "application";
import * as platform from "platform";
// Make TypeScript happy
declare var android: any;
declare var UIResponder: any;
declare var UIStatusBarStyle: any;
declare var UIApplication: any;
declare var UIApplicationDelegate: any;
export function setStatusBarColors() {
// Make the iOS status bar transparent with white text.
// See https://github.com/burkeholland/nativescript-statusbar/issues/2
// for details on the technique used.
if (application.ios) {
var AppDelegate = UIResponder.extend({
applicationDidFinishLaunchingWithOptions: function() {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent;
return true;
}
}, {
name: "AppDelegate",
protocols: [UIApplicationDelegate]
});
application.ios.delegate = AppDelegate;
}
// Make the Android status bar transparent.
// See http://bradmartin.net/2016/03/10/fullscreen-and-navigation-bar-color-in-a-nativescript-android-app/
// for details on the technique used.
application.android.onActivityStarted = function() {
if (application.android && platform.device.sdkVersion >= "21") {
var View = android.view.View;
var window = application.android.startActivity.getWindow();
window.setStatusBarColor(0x000000);
var decorView = window.getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
}
| Add Android into the status bar utility | Add Android into the status bar utility
| TypeScript | mit | poly-mer/community,anhoev/cms-mobile,anhoev/cms-mobile,Icenium/nativescript-sample-groceries,NativeScript/sample-Groceries,dzfweb/sample-groceries,qtagtech/nativescript_tutorial,qtagtech/nativescript_tutorial,tjvantoll/sample-Groceries,qtagtech/nativescript_tutorial,anhoev/cms-mobile,tjvantoll/sample-Groceries,NativeScript/sample-Groceries,poly-mer/community,dzfweb/sample-groceries,poly-mer/community,NativeScript/sample-Groceries,dzfweb/sample-groceries,tjvantoll/sample-Groceries | ---
+++
@@ -1,12 +1,17 @@
import * as application from "application";
+import * as platform from "platform";
// Make TypeScript happy
+declare var android: any;
declare var UIResponder: any;
declare var UIStatusBarStyle: any;
declare var UIApplication: any;
declare var UIApplicationDelegate: any;
export function setStatusBarColors() {
+ // Make the iOS status bar transparent with white text.
+ // See https://github.com/burkeholland/nativescript-statusbar/issues/2
+ // for details on the technique used.
if (application.ios) {
var AppDelegate = UIResponder.extend({
applicationDidFinishLaunchingWithOptions: function() {
@@ -19,4 +24,22 @@
});
application.ios.delegate = AppDelegate;
}
+
+ // Make the Android status bar transparent.
+ // See http://bradmartin.net/2016/03/10/fullscreen-and-navigation-bar-color-in-a-nativescript-android-app/
+ // for details on the technique used.
+ application.android.onActivityStarted = function() {
+ if (application.android && platform.device.sdkVersion >= "21") {
+ var View = android.view.View;
+ var window = application.android.startActivity.getWindow();
+ window.setStatusBarColor(0x000000);
+
+ var decorView = window.getDecorView();
+ decorView.setSystemUiVisibility(
+ View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ }
+ }
} |
41b7fb1f1246b9ee034d831beadd4e21abaa89ba | LegatumClient/src/app/home/home.component.ts | LegatumClient/src/app/home/home.component.ts | import { Component, OnInit } from '@angular/core';
declare var swal: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
handleLogin(): void {
console.log('clicked');
swal({
title: 'Login',
html:
'<input type="email" placeholder="email" id="swal-input1" class="swal2-input">' +
'<input type="password" placeholder="password" id="swal-input2" class="swal2-input">',
});
}
}
| import { Component, OnInit } from '@angular/core';
import { LoginComponent } from '../login/login.component';
declare var swal: any;
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
handleRegister(): void {
console.log('register');
swal('register user was clicked!');
}
handleLogin(): void {
console.log('clicked');
swal({
title: 'Login',
confirmButtonText: 'Login',
showCancelButton: true,
cancelButtonText: 'Register',
html:
'<input type="email" placeholder="email" class="swal2-input">' +
'<input type="password" placeholder="password" class="swal2-input">',
}).then(function () {
console.log('login has been pressed');
}, function (dismiss) {
if (dismiss === 'cancel') {
swal({
title: 'Register',
confirmButtonText: 'Register',
showCancelButton: true,
html:
'<input type="email" placeholder="email" class="swal2-input">' +
'<input type="password" placeholder="password" class="swal2-input">' +
'<input type="text" placeholder="ssn" class="swal2-input">',
});
}
});
}
}
| Add register button to the login modal =>scaffolding | Add register button to the login modal =>scaffolding
| TypeScript | apache-2.0 | tonymichaelhead/Legatum,tonymichaelhead/Legatum,tonymichaelhead/Legatum | ---
+++
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
+import { LoginComponent } from '../login/login.component';
declare var swal: any;
@@ -14,13 +15,35 @@
ngOnInit() {
}
+ handleRegister(): void {
+ console.log('register');
+ swal('register user was clicked!');
+ }
+
handleLogin(): void {
console.log('clicked');
swal({
title: 'Login',
+ confirmButtonText: 'Login',
+ showCancelButton: true,
+ cancelButtonText: 'Register',
html:
- '<input type="email" placeholder="email" id="swal-input1" class="swal2-input">' +
- '<input type="password" placeholder="password" id="swal-input2" class="swal2-input">',
+ '<input type="email" placeholder="email" class="swal2-input">' +
+ '<input type="password" placeholder="password" class="swal2-input">',
+ }).then(function () {
+ console.log('login has been pressed');
+ }, function (dismiss) {
+ if (dismiss === 'cancel') {
+ swal({
+ title: 'Register',
+ confirmButtonText: 'Register',
+ showCancelButton: true,
+ html:
+ '<input type="email" placeholder="email" class="swal2-input">' +
+ '<input type="password" placeholder="password" class="swal2-input">' +
+ '<input type="text" placeholder="ssn" class="swal2-input">',
+ });
+ }
});
}
} |
5d2096a944c3777e9f0352a5f5131d00b0f8a6c4 | src/app.ts | src/app.ts | // Imports Globals. Required for Webpack to include them in build.
import "p2";
import "PIXI";
import "Phaser";
import { Game } from './game'
window.onload = () => {
const config: Phaser.IGameConfig = {
width: 800,
height: 600,
renderer: Phaser.AUTO
}
new Game(config)
} | // Imports Globals. Required for Webpack to include them in build.
import "p2";
import "PIXI";
import "Phaser";
import { Game } from './game'
window.onload = () => {
const config: Phaser.IGameConfig = {
width: 875,
height: 630,
renderer: Phaser.AUTO
}
new Game(config)
} | Update game width and height. | Update game width and height.
| TypeScript | mit | dmk2014/phaser-template,dmk2014/phaser-template,dmk2014/phaser-template | ---
+++
@@ -7,8 +7,8 @@
window.onload = () => {
const config: Phaser.IGameConfig = {
- width: 800,
- height: 600,
+ width: 875,
+ height: 630,
renderer: Phaser.AUTO
}
|
fc7ddafed0a60423ad4a63b3992130f0e5ffd5bd | spec/config_ctrl.jest.ts | spec/config_ctrl.jest.ts | import {SunAndMoonConfigCtrl} from "../src/config_ctrl";
describe("SunAndMoonConfigCtrl", () => {
it("config_ctrl should support old position format", () => {
SunAndMoonConfigCtrl.prototype.current = {
jsonData: {
position: {
latitude: 48,
longitude: 10
}
}
};
const cc = new SunAndMoonConfigCtrl();
expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10});
});
});
| import {SunAndMoonConfigCtrl} from "../src/config_ctrl";
describe("SunAndMoonConfigCtrl", () => {
it("config_ctrl should support new position format", () => {
SunAndMoonConfigCtrl.prototype.current = {
jsonData: {
latitude: 48,
longitude: 10
}
};
const cc = new SunAndMoonConfigCtrl();
expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10});
});
it("config_ctrl should support old position format", () => {
SunAndMoonConfigCtrl.prototype.current = {
jsonData: {
position: {
latitude: 48,
longitude: 10
}
}
};
const cc = new SunAndMoonConfigCtrl();
expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10});
});
});
| Add test for new position format | tests: Add test for new position format
| TypeScript | mit | fetzerch/grafana-sunandmoon-datasource,fetzerch/grafana-sunandmoon-datasource | ---
+++
@@ -1,6 +1,17 @@
import {SunAndMoonConfigCtrl} from "../src/config_ctrl";
describe("SunAndMoonConfigCtrl", () => {
+ it("config_ctrl should support new position format", () => {
+ SunAndMoonConfigCtrl.prototype.current = {
+ jsonData: {
+ latitude: 48,
+ longitude: 10
+ }
+ };
+ const cc = new SunAndMoonConfigCtrl();
+ expect(cc.current.jsonData).toEqual({latitude: 48, longitude: 10});
+ });
+
it("config_ctrl should support old position format", () => {
SunAndMoonConfigCtrl.prototype.current = {
jsonData: { |
9e086d96689d89c6d731fabee9a3daab95a8be8a | Rolodex/Rolodex/MyScripts/contactsController.ts | Rolodex/Rolodex/MyScripts/contactsController.ts | /// reference path="../Scripts/typings/angularjs/angular.d.ts" />
var contactsApp: any;
contactsApp.controller('ContactsController',
function ContactsController($scope, contactData) {
$scope.sortOrder = 'last';
$scope.hideMessage = "Hide Details";
$scope.showMessage = "Show Details";
$scope.contacts = contactData.getContacts();
$scope.toggleShowDetails = function (contact) {
contact.showDetails = !contact.showDetails;
}
});
| /// reference path="../Scripts/typings/angularjs/angular.d.ts" />
var contactsApp: ng.IModule;
contactsApp.controller('ContactsController',
function ContactsController($scope, contactData) {
$scope.sortOrder = 'last';
$scope.hideMessage = "Hide Details";
$scope.showMessage = "Show Details";
$scope.contacts = contactData.getContacts();
$scope.toggleShowDetails = function (contact) {
contact.showDetails = !contact.showDetails;
}
});
| Change contactsApp from 'any' to 'angular.IModule' | Change contactsApp from 'any' to 'angular.IModule'
This gives us typing information about the contactsApp variable
| TypeScript | mit | BillWagner/TypeScript-CodeMash,BillWagner/TypeScript-CodeMash,BillWagner/TypeScript-CodeMash,BillWagner/TypeScript-CodeMash | ---
+++
@@ -1,7 +1,7 @@
/// reference path="../Scripts/typings/angularjs/angular.d.ts" />
-var contactsApp: any;
+var contactsApp: ng.IModule;
contactsApp.controller('ContactsController',
function ContactsController($scope, contactData) { |
7b17c25736a1b5c3921c45279699eec77bc20914 | src/search/search-index-new/storage/manager.ts | src/search/search-index-new/storage/manager.ts | import { extractTerms } from '../../search-index-old/pipeline'
import StorageRegistry from './registry'
export class StorageManager {
public initialized = false
public registry = new StorageRegistry()
private _initializationPromise
private _initializationResolve
private _storage
constructor() {
this._initializationPromise = new Promise(resolve => this._initializationResolve = resolve)
}
registerCollection(name, defs) {
this.registry.registerCollection(name, defs)
}
async putObject(collectionName: string, object) {
await this._initializationPromise
const collection = this.registry.collections[collectionName]
const indices = collection.indices || []
Object.entries(collection.fields).forEach(([fieldName, fieldDef]) => {
if (fieldDef['_index'] && fieldDef['type'] === 'text') {
object[`_${fieldName}_terms`] = [...extractTerms(object[fieldName], '_')]
} else if (fieldDef['type'] === 'json') {
object[fieldName] = JSON.stringify(object[fieldName])
}
})
await this._storage[collectionName].put(object)
}
_finishInitialization(storage) {
this._storage = storage
this._initializationResolve()
}
}
| import { extractTerms } from '../../search-index-old/pipeline'
import StorageRegistry from './registry'
export class StorageManager {
public initialized = false
public registry = new StorageRegistry()
private _initializationPromise
private _initializationResolve
private _storage
constructor() {
this._initializationPromise = new Promise(resolve => this._initializationResolve = resolve)
}
registerCollection(name, defs) {
this.registry.registerCollection(name, defs)
}
async putObject(collectionName: string, object) {
await this._initializationPromise
const collection = this.registry.collections[collectionName]
const indices = collection.indices || []
Object.entries(collection.fields).forEach(([fieldName, fieldDef]) => {
if (fieldDef['_index'] && fieldDef['type'] === 'text') {
object[`_${fieldName}_terms`] = [...extractTerms(object[fieldName], '_')]
}
})
await this._storage[collectionName].put(object)
}
_finishInitialization(storage) {
this._storage = storage
this._initializationResolve()
}
}
| Remove JSON stringification for storage | Remove JSON stringification for storage
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -24,8 +24,6 @@
Object.entries(collection.fields).forEach(([fieldName, fieldDef]) => {
if (fieldDef['_index'] && fieldDef['type'] === 'text') {
object[`_${fieldName}_terms`] = [...extractTerms(object[fieldName], '_')]
- } else if (fieldDef['type'] === 'json') {
- object[fieldName] = JSON.stringify(object[fieldName])
}
})
|
d3c17fc4ee6000a4af5763382f7cbe9fcdd2a31f | helpers/makeMetaTags.ts | helpers/makeMetaTags.ts | import constants from './constants'
export default function (
title: string,
description: string,
imageLink: string
) {
const imageUrl =
typeof imageLink === 'string' ? imageLink : constants.socialMediaImageUrl
return [
{
hid: 'description',
name: 'description',
content: description,
},
{
name: 'author',
content: 'Jack Barry',
},
// Facebook
{
property: 'og:title',
content: title,
},
{
prefix: 'og: http://ogp.me/ns#',
property: 'og:image',
content: imageUrl,
},
{
property: 'og:site_name',
content: 'DevDad.life',
},
// Twitter
{
name: 'twitter:card',
content: 'summary_large_image',
},
{
property: 'twitter:title',
content: title,
},
{
property: 'twitter:description',
content: description,
},
{
name: 'twitter:image',
content: imageUrl,
},
]
}
| import constants from './constants'
export default function (
title: string,
description: string,
imageLink: string
) {
const imageUrl =
typeof imageLink === 'string' ? imageLink : constants.socialMediaImageUrl
return [
{
prefix: 'og: http://ogp.me/ns#',
property: 'og:image',
content: imageUrl,
},
{
hid: 'description',
name: 'description',
content: description,
},
{
name: 'author',
content: 'Jack Barry',
},
// Facebook
{
property: 'og:title',
content: title,
},
{
property: 'og:site_name',
content: 'DevDad.life',
},
// Twitter
{
name: 'twitter:card',
content: 'summary_large_image',
},
{
property: 'twitter:title',
content: title,
},
{
property: 'twitter:description',
content: description,
},
{
name: 'twitter:image',
content: imageUrl,
},
]
}
| Move image meta tag to top of list | fix(general): Move image meta tag to top of list
Tries moving the meta tag for image to top of the list of elements to see if it's an order issue
| TypeScript | mit | Jack-Barry/Jack-Barry.github.io | ---
+++
@@ -9,6 +9,11 @@
typeof imageLink === 'string' ? imageLink : constants.socialMediaImageUrl
return [
+ {
+ prefix: 'og: http://ogp.me/ns#',
+ property: 'og:image',
+ content: imageUrl,
+ },
{
hid: 'description',
name: 'description',
@@ -22,11 +27,6 @@
{
property: 'og:title',
content: title,
- },
- {
- prefix: 'og: http://ogp.me/ns#',
- property: 'og:image',
- content: imageUrl,
},
{
property: 'og:site_name', |
1961af75628b7e551b51f2278260cc3a09933f37 | src/app/app.component.ts | src/app/app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
| import { Component } from '@angular/core';
export class Recipe {
id: number;
name: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Ryourisho';
recipe: Recipe = {
id: 1,
name: 'Warabi Mochi'
};
}
| Change title of app and add Recipe class | Change title of app and add Recipe class
| TypeScript | mpl-2.0 | mkozina/cookbook,mkozina/cookbook,mkozina/cookbook | ---
+++
@@ -1,4 +1,9 @@
import { Component } from '@angular/core';
+
+export class Recipe {
+ id: number;
+ name: string;
+}
@Component({
selector: 'app-root',
@@ -6,5 +11,9 @@
styleUrls: ['./app.component.css']
})
export class AppComponent {
- title = 'app works!';
+ title = 'Ryourisho';
+ recipe: Recipe = {
+ id: 1,
+ name: 'Warabi Mochi'
+ };
} |
8c772af7ffa7319c167dcb0b530f6fcb7f906a71 | src/form/SelectField.tsx | src/form/SelectField.tsx | import * as React from 'react';
import Select from 'react-select';
export const SelectField = (props) => {
const { input, simpleValue, options, ...rest } = props;
return (
<Select
{...rest}
name={input.name}
value={
simpleValue || typeof input.value !== 'object'
? options.filter((option) => option.value === input.value)
: input.value
}
onChange={(newValue: any) =>
simpleValue ? input.onChange(newValue.value) : input.onChange(newValue)
}
options={options}
onBlur={() => {
if (!props.noUpdateOnBlur) {
// See also: https://github.com/erikras/redux-form/issues/1185
props.input.onBlur(props.input.value);
}
}}
/>
);
};
| import * as React from 'react';
import Select from 'react-select';
export const SelectField = (props) => {
const { input, simpleValue, options, ...rest } = props;
return (
<Select
{...rest}
name={input.name}
value={
(simpleValue || typeof input.value !== 'object') && options
? options.filter((option) => option.value === input.value)
: input.value
}
onChange={(newValue: any) =>
simpleValue ? input.onChange(newValue.value) : input.onChange(newValue)
}
options={options}
onBlur={() => {
if (!props.noUpdateOnBlur) {
// See also: https://github.com/erikras/redux-form/issues/1185
props.input.onBlur(props.input.value);
}
}}
/>
);
};
| Make select field more robust if options list is not defined. | Make select field more robust if options list is not defined.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -8,7 +8,7 @@
{...rest}
name={input.name}
value={
- simpleValue || typeof input.value !== 'object'
+ (simpleValue || typeof input.value !== 'object') && options
? options.filter((option) => option.value === input.value)
: input.value
} |
d9460d0b2b9c835db9eb2dcbb9791adcdd399aa7 | public/app/core/components/Tooltip/withTooltip.tsx | public/app/core/components/Tooltip/withTooltip.tsx | import React from 'react';
import { Manager, Popper, Arrow } from 'react-popper';
interface IwithTooltipProps {
placement?: string;
content: string | ((props: any) => JSX.Element);
}
export default function withTooltip(WrappedComponent) {
return class extends React.Component<IwithTooltipProps, any> {
constructor(props) {
super(props);
this.setState = this.setState.bind(this);
this.state = {
placement: this.props.placement || 'auto',
show: false,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.placement && nextProps.placement !== this.state.placement) {
this.setState(prevState => {
return {
...prevState,
placement: nextProps.placement,
};
});
}
}
renderContent(content) {
if (typeof content === 'function') {
// If it's a function we assume it's a React component
const ReactComponent = content;
return <ReactComponent />;
}
return content;
}
render() {
const { content } = this.props;
return (
<Manager className="popper__manager">
<WrappedComponent {...this.props} tooltipSetState={this.setState} />
{this.state.show ? (
<Popper placement={this.state.placement} className="popper">
{this.renderContent(content)}
<Arrow className="popper__arrow" />
</Popper>
) : null}
</Manager>
);
}
};
}
| import React from 'react';
import { Manager, Popper, Arrow } from 'react-popper';
interface IwithTooltipProps {
placement?: string;
content: string | ((props: any) => JSX.Element);
className?: string;
}
export default function withTooltip(WrappedComponent) {
return class extends React.Component<IwithTooltipProps, any> {
constructor(props) {
super(props);
this.setState = this.setState.bind(this);
this.state = {
placement: this.props.placement || 'auto',
show: false,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.placement && nextProps.placement !== this.state.placement) {
this.setState(prevState => {
return {
...prevState,
placement: nextProps.placement,
};
});
}
}
renderContent(content) {
if (typeof content === 'function') {
// If it's a function we assume it's a React component
const ReactComponent = content;
return <ReactComponent />;
}
return content;
}
render() {
const { content, className } = this.props;
return (
<Manager className={`popper__manager ${className || ''}`}>
<WrappedComponent {...this.props} tooltipSetState={this.setState} />
{this.state.show ? (
<Popper placement={this.state.placement} className="popper">
{this.renderContent(content)}
<Arrow className="popper__arrow" />
</Popper>
) : null}
</Manager>
);
}
};
}
| Add className to Tooltip component | dashfolders: Add className to Tooltip component
| TypeScript | agpl-3.0 | grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana | ---
+++
@@ -4,6 +4,7 @@
interface IwithTooltipProps {
placement?: string;
content: string | ((props: any) => JSX.Element);
+ className?: string;
}
export default function withTooltip(WrappedComponent) {
@@ -39,10 +40,10 @@
}
render() {
- const { content } = this.props;
+ const { content, className } = this.props;
return (
- <Manager className="popper__manager">
+ <Manager className={`popper__manager ${className || ''}`}>
<WrappedComponent {...this.props} tooltipSetState={this.setState} />
{this.state.show ? (
<Popper placement={this.state.placement} className="popper"> |
ab8e6baff1b0bde97215ade154001df9a3b5ba27 | lib/ui/src/components/sidebar/Heading.tsx | lib/ui/src/components/sidebar/Heading.tsx | import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.color.defaultText,
marginRight: 40,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
display: 'block',
flex: '1 1 auto',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { Brand } from './Brand';
import { SidebarMenu, MenuList } from './Menu';
export interface HeadingProps {
menuHighlighted?: boolean;
menu: MenuList;
}
const BrandArea = styled.div(({ theme }) => ({
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.color.defaultText,
marginRight: 20,
display: 'flex',
width: '100%',
alignItems: 'center',
minHeight: 22,
'& > *': {
maxWidth: '100%',
height: 'auto',
display: 'block',
flex: '1 1 auto',
},
}));
const HeadingWrapper = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
position: 'relative',
});
export const Heading: FunctionComponent<HeadingProps & ComponentProps<typeof HeadingWrapper>> = ({
menuHighlighted = false,
menu,
...props
}) => {
return (
<HeadingWrapper {...props}>
<BrandArea>
<Brand />
</BrandArea>
<SidebarMenu menu={menu} isHighlighted={menuHighlighted} />
</HeadingWrapper>
);
};
| Reduce spacing to support a larger brandImage | Reduce spacing to support a larger brandImage | TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -13,7 +13,7 @@
fontSize: theme.typography.size.s2,
fontWeight: theme.typography.weight.bold,
color: theme.color.defaultText,
- marginRight: 40,
+ marginRight: 20,
display: 'flex',
width: '100%',
alignItems: 'center', |
dc937e0c7eebd2065ab890e7d734fbf75650b8b4 | packages/design-studio/schemas/pt.ts | packages/design-studio/schemas/pt.ts | const objectExample = {
type: 'object',
name: 'objectExample',
title: 'Object (1)',
fields: [{type: 'string', name: 'title', title: 'Title'}]
}
const imageExample = {
type: 'image',
name: 'imageExample',
title: 'Image example',
options: {
hotspot: true
}
}
export default {
type: 'document',
name: 'pt',
title: 'Portable Text™',
fields: [
{
type: 'string',
name: 'title',
title: 'Title'
},
{
type: 'array',
name: 'pt',
title: 'Portable text',
of: [
{
type: 'block',
of: [{...objectExample, validation: Rule => Rule.required()}],
marks: {
annotations: [
{
type: 'object',
name: 'link',
fields: [
{
type: 'string',
name: 'href',
title: 'URL',
validation: Rule => Rule.required()
}
]
},
objectExample
]
}
},
imageExample,
objectExample
]
}
]
}
| const objectExample = {
type: 'object',
name: 'objectExample',
title: 'Object (1)',
fields: [{type: 'string', name: 'title', title: 'Title'}]
}
const imageExample = {
type: 'image',
name: 'imageExample',
title: 'Image example',
options: {
hotspot: true
}
}
const pt = {
type: 'array',
name: 'pt',
title: 'Portable text',
of: [
{
type: 'block',
of: [{...objectExample, validation: Rule => Rule.required()}],
marks: {
annotations: [
{
type: 'object',
name: 'link',
fields: [
{
type: 'string',
name: 'href',
title: 'URL',
validation: Rule => Rule.required()
}
]
},
objectExample
]
}
},
imageExample,
objectExample
]
}
const arrayWithPt = {
type: 'array',
name: 'arrayWithPt',
title: 'Array with Portable Text',
of: [
{
type: 'object',
name: 'objectWithPT',
title: 'Object with PT',
fields: [
{type: 'string', name: 'title', title: 'Title'},
{type: 'array', name: 'pt', title: 'Portable Text', of: [{type: 'block'}]}
]
}
]
}
export default {
type: 'document',
name: 'pt',
title: 'Portable Text™',
fields: [
{
type: 'string',
name: 'title',
title: 'Title'
},
pt,
arrayWithPt
]
}
| Add example of PT in array item | [design-studio] Add example of PT in array item
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -14,6 +14,54 @@
}
}
+const pt = {
+ type: 'array',
+ name: 'pt',
+ title: 'Portable text',
+ of: [
+ {
+ type: 'block',
+ of: [{...objectExample, validation: Rule => Rule.required()}],
+ marks: {
+ annotations: [
+ {
+ type: 'object',
+ name: 'link',
+ fields: [
+ {
+ type: 'string',
+ name: 'href',
+ title: 'URL',
+ validation: Rule => Rule.required()
+ }
+ ]
+ },
+ objectExample
+ ]
+ }
+ },
+ imageExample,
+ objectExample
+ ]
+}
+
+const arrayWithPt = {
+ type: 'array',
+ name: 'arrayWithPt',
+ title: 'Array with Portable Text',
+ of: [
+ {
+ type: 'object',
+ name: 'objectWithPT',
+ title: 'Object with PT',
+ fields: [
+ {type: 'string', name: 'title', title: 'Title'},
+ {type: 'array', name: 'pt', title: 'Portable Text', of: [{type: 'block'}]}
+ ]
+ }
+ ]
+}
+
export default {
type: 'document',
name: 'pt',
@@ -24,35 +72,7 @@
name: 'title',
title: 'Title'
},
- {
- type: 'array',
- name: 'pt',
- title: 'Portable text',
- of: [
- {
- type: 'block',
- of: [{...objectExample, validation: Rule => Rule.required()}],
- marks: {
- annotations: [
- {
- type: 'object',
- name: 'link',
- fields: [
- {
- type: 'string',
- name: 'href',
- title: 'URL',
- validation: Rule => Rule.required()
- }
- ]
- },
- objectExample
- ]
- }
- },
- imageExample,
- objectExample
- ]
- }
+ pt,
+ arrayWithPt
]
} |
d7146d7b794ddcaf22e93b5621d9c39898ec3624 | source/filters/filter.ts | source/filters/filter.ts | 'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
protected onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | 'use strict';
import * as Rx from 'rx';
import { objectUtility } from '../services/object/object.service';
export interface IFilterWithCounts extends IFilter {
updateOptionCounts<TItemType>(data: TItemType[]): void;
}
export interface ISerializableFilter<TFilterData> extends IFilter {
type: string;
serialize(): TFilterData;
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber;
}
export interface IValueChangeCallback<TFilterData> {
(newValue: TFilterData): void;
}
export interface IFilter {
filter<TItemType>(item: TItemType): boolean;
}
export class SerializableFilter<TFilterData> implements ISerializableFilter<TFilterData> {
type: string;
protected subject: Rx.Subject;
private _value: TFilterData;
constructor() {
this.subject = new Rx.Subject();
}
// override
filter(item: any): boolean {
return true;
}
serialize(): TFilterData {
return <any>this;
}
subscribe(onValueChange: IValueChangeCallback<TFilterData>): Rx.Subscriber {
return this.subject.subscribe(onValueChange);
}
onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue;
this.subject.onNext(this._value);
}
}
} | Make onChange public for the tests. It still isn't visible on the interface, so most consumer won't care | Make onChange public for the tests. It still isn't visible on the interface, so most consumer won't care
| TypeScript | mit | RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities | ---
+++
@@ -44,7 +44,7 @@
return this.subject.subscribe(onValueChange);
}
- protected onChange(force: boolean = true): void {
+ onChange(force: boolean = true): void {
let newValue: TFilterData = this.serialize();
if (force || !objectUtility.areEqual(newValue, this._value)) {
this._value = newValue; |
0868cba1a3f7f09c32c353e39fca3b665512cad2 | server/api/constants.ts | server/api/constants.ts | export default class Constants {
public static basePath: string = process.cwd().replace(/\\/g, "/") + "/";
public static controllerPaths: string[];
public static modulesPath: string = Constants.basePath + "modules/";
public static staticPaths: string[];
public static viewPaths: string[];
public static http = {
AccessDenied: 403,
InternalError: 500,
MissingParameters: 422,
NotFound: 404,
NotModified: 304
};
}
| import * as path from "path";
export default class Constants {
public static basePath: string = path.resolve(__dirname, "../..").replace(/\\/g, "/") + "/";
public static controllerPaths: string[];
public static modulesPath: string = Constants.basePath + "modules/";
public static staticPaths: string[];
public static viewPaths: string[];
public static http = {
AccessDenied: 403,
InternalError: 500,
MissingParameters: 422,
NotFound: 404,
NotModified: 304
};
}
| Use `__dirname` instead of `process.cwd()` for basePath | Use `__dirname` instead of `process.cwd()` for basePath
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -1,5 +1,7 @@
+import * as path from "path";
+
export default class Constants {
- public static basePath: string = process.cwd().replace(/\\/g, "/") + "/";
+ public static basePath: string = path.resolve(__dirname, "../..").replace(/\\/g, "/") + "/";
public static controllerPaths: string[];
public static modulesPath: string = Constants.basePath + "modules/";
public static staticPaths: string[]; |
331f228aacd2228be58f2d7aa75e5fcfa7c9ed64 | lib/msal-electron-proof-of-concept/src/index.ts | lib/msal-electron-proof-of-concept/src/index.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
export { PublicClientApplication } from './AppConfig/publicClientApplication';
export { ApplicationConfiguration } from './AppConfig/applicationConfiguration';
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
export { PublicClientApplication } from './AppConfig/PublicClientApplication';
export { ApplicationConfiguration } from './AppConfig/ApplicationConfiguration';
| Update file export statements to match new filename casing | Update file export statements to match new filename casing
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -1,5 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
-export { PublicClientApplication } from './AppConfig/publicClientApplication';
-export { ApplicationConfiguration } from './AppConfig/applicationConfiguration';
+export { PublicClientApplication } from './AppConfig/PublicClientApplication';
+export { ApplicationConfiguration } from './AppConfig/ApplicationConfiguration'; |
8cec30fcb1f88007cedf6d2a3517258a516b18a8 | src/desktop/components/react/stitch_components/StagingBanner.tsx | src/desktop/components/react/stitch_components/StagingBanner.tsx | import React from "react"
import styled from "styled-components"
import { Banner, Box } from "@artsy/palette"
import { data as sd } from "sharify"
export const StagingBanner = () => {
return (
<Container>
<Banner
backgroundColor="purple100"
message={sd.APP_URL.replace("https://", "").replace("http://", "")}
/>
</Container>
)
}
const Container = styled(Box)`
position: relative;
z-index: 2;
`
| import React, { useState } from "react"
import styled from "styled-components"
import { Banner, Box } from "@artsy/palette"
import { data as sd } from "sharify"
export const StagingBanner = () => {
const [show, toggleVisible] = useState(true)
if (!show) {
return null
}
return (
<Container onClick={() => toggleVisible(false)}>
<Banner
backgroundColor="purple100"
message={sd.APP_URL.replace("https://", "").replace("http://", "")}
/>
</Container>
)
}
const Container = styled(Box)`
position: relative;
z-index: 2;
`
| Add toggle to hide staging banner | Add toggle to hide staging banner
| TypeScript | mit | erikdstock/force,izakp/force,yuki24/force,cavvia/force-1,joeyAghion/force,damassi/force,eessex/force,erikdstock/force,anandaroop/force,artsy/force,damassi/force,anandaroop/force,artsy/force-public,oxaudo/force,anandaroop/force,joeyAghion/force,oxaudo/force,artsy/force-public,eessex/force,cavvia/force-1,damassi/force,joeyAghion/force,eessex/force,erikdstock/force,anandaroop/force,erikdstock/force,yuki24/force,oxaudo/force,izakp/force,damassi/force,yuki24/force,yuki24/force,cavvia/force-1,eessex/force,izakp/force,izakp/force,artsy/force,joeyAghion/force,cavvia/force-1,oxaudo/force,artsy/force,artsy/force | ---
+++
@@ -1,11 +1,17 @@
-import React from "react"
+import React, { useState } from "react"
import styled from "styled-components"
import { Banner, Box } from "@artsy/palette"
import { data as sd } from "sharify"
export const StagingBanner = () => {
+ const [show, toggleVisible] = useState(true)
+
+ if (!show) {
+ return null
+ }
+
return (
- <Container>
+ <Container onClick={() => toggleVisible(false)}>
<Banner
backgroundColor="purple100"
message={sd.APP_URL.replace("https://", "").replace("http://", "")} |
a5715987222d047923790ec9e5a104a2251a3a52 | webpack-test.config.ts | webpack-test.config.ts | import * as webpack from 'webpack';
import * as path from 'path';
export default {
resolve: {
extensions: [ '.ts', '.js', '.json' ]
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
options: {
configFileName: 'tsconfig.json'
}
},
{
loader: 'angular2-template-loader'
}
],
exclude: [
/\.e2e\.ts$/,
/node_modules/
]
},
{
test: /src\/.+\.ts$/,
exclude: /(node_modules|\.spec\.ts$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post'
},
{
test: /\.json$/,
use: 'json-loader'
},
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader']
},
{
test: /\.scss$/,
use: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.html$/,
use: 'raw-loader'
}
]
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: null,
test: /\.(ts|js)($|\?)/i
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
path.join(__dirname, 'src')
),
new webpack.NoEmitOnErrorsPlugin()
]
} as webpack.Configuration;
| import * as webpack from 'webpack';
import * as path from 'path';
export default {
resolve: {
extensions: [ '.ts', '.js', '.json' ]
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{
loader: 'awesome-typescript-loader',
options: {
configFileName: 'tsconfig.json'
}
},
{
loader: 'angular2-template-loader'
}
],
exclude: [
/\.e2e\.ts$/,
/node_modules/
]
},
{
test: /.ts$/,
exclude: /(node_modules|\.spec\.ts|\.e2e\.ts$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post'
},
{
test: /\.json$/,
use: 'json-loader'
},
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader']
},
{
test: /\.scss$/,
use: ['to-string-loader', 'css-loader', 'sass-loader']
},
{
test: /\.html$/,
use: 'raw-loader'
}
]
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: null,
test: /\.(ts|js)($|\?)/i
}),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
path.join(__dirname, 'src')
),
new webpack.NoEmitOnErrorsPlugin()
]
} as webpack.Configuration;
| Fix code-coverage reports for Windows. | Fix code-coverage reports for Windows.
| TypeScript | mit | nowzoo/nowzoo-angular-bootstrap-lite,nowzoo/nowzoo-angular-bootstrap-lite,trekhleb/ng-library-starter,trekhleb/angular-library-seed,trekhleb/angular-library-seed,trekhleb/angular-library-seed,nowzoo/nowzoo-angular-bootstrap-lite,trekhleb/ng-library-starter,trekhleb/ng-library-starter | ---
+++
@@ -27,8 +27,8 @@
},
{
- test: /src\/.+\.ts$/,
- exclude: /(node_modules|\.spec\.ts$)/,
+ test: /.ts$/,
+ exclude: /(node_modules|\.spec\.ts|\.e2e\.ts$)/,
loader: 'istanbul-instrumenter-loader',
enforce: 'post'
}, |
41e554429e20d91536767a2accb6b2a7dbadbfb3 | app/src/lib/dispatcher/github-user-database.ts | app/src/lib/dispatcher/github-user-database.ts | import Dexie from 'dexie'
// NB: This _must_ be incremented whenever the DB key scheme changes.
const DatabaseVersion = 1
export interface IGitHubUser {
readonly id?: number
readonly endpoint: string
readonly email: string
readonly login: string | null
readonly avatarURL: string
}
export class GitHubUserDatabase extends Dexie {
public users: Dexie.Table<IGitHubUser, number>
public constructor(name: string) {
super(name)
this.version(DatabaseVersion).stores({
users: '++id, &[endpoint+email]',
})
}
}
| import Dexie from 'dexie'
// NB: This _must_ be incremented whenever the DB key scheme changes.
const DatabaseVersion = 2
export interface IGitHubUser {
readonly id?: number
readonly endpoint: string
readonly email: string
readonly login: string | null
readonly avatarURL: string
}
export interface IMentionableAssociation {
readonly userID: number
readonly repositoryID: number
}
export class GitHubUserDatabase extends Dexie {
public users: Dexie.Table<IGitHubUser, number>
public mentionables: Dexie.Table<IMentionableAssociation, number>
public constructor(name: string) {
super(name)
this.version(1).stores({
users: '++id, &[endpoint+email]',
})
this.version(DatabaseVersion).stores({
mentionables: '++, repositoryID',
})
}
}
| Store mentionable associations in the DB | Store mentionable associations in the DB
| TypeScript | mit | artivilla/desktop,desktop/desktop,gengjiawen/desktop,kactus-io/kactus,say25/desktop,say25/desktop,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,artivilla/desktop,BugTesterTest/desktops,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,hjobrien/desktop,artivilla/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,BugTesterTest/desktops | ---
+++
@@ -1,7 +1,7 @@
import Dexie from 'dexie'
// NB: This _must_ be incremented whenever the DB key scheme changes.
-const DatabaseVersion = 1
+const DatabaseVersion = 2
export interface IGitHubUser {
readonly id?: number
@@ -11,14 +11,24 @@
readonly avatarURL: string
}
+export interface IMentionableAssociation {
+ readonly userID: number
+ readonly repositoryID: number
+}
+
export class GitHubUserDatabase extends Dexie {
public users: Dexie.Table<IGitHubUser, number>
+ public mentionables: Dexie.Table<IMentionableAssociation, number>
public constructor(name: string) {
super(name)
+ this.version(1).stores({
+ users: '++id, &[endpoint+email]',
+ })
+
this.version(DatabaseVersion).stores({
- users: '++id, &[endpoint+email]',
+ mentionables: '++, repositoryID',
})
}
} |
7e63d9fd1e2e3f3e4a4c59f0dbad1f4f76f65343 | src/lib/kernel32/api.ts | src/lib/kernel32/api.ts | import * as D from '../windef';
import * as GT from '../types';
export const fnDef: GT.Win32FnDef = {
GetLastError: [D.DWORD, []], // err code: https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms681381(v=vs.85).aspx
GetModuleHandleW: [D.HMODULE, [D.LPCTSTR]], // retrive value from buf by ret.ref().readUInt32()
GetModuleHandleExW: [D.BOOL, [D.DWORD, D.LPCTSTR, D.HMODULE]], // flags, optional LPCTSTR name, ref hModule
};
export interface Win32Fn {
GetLastError(): GT.DWORD;
GetModuleHandleW(lpModuleName: GT.LPCTSTR): GT.HMODULE;
GetModuleHandleExW(dwFlags: GT.DWORD, lpModuleName: GT.LPCTSTR | null, phModule: GT.HMODULE): GT.BOOL;
}
| import * as D from '../windef';
import * as GT from '../types';
export const fnDef: GT.Win32FnDef = {
GetLastError: [D.DWORD, []], // err code: https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms681381(v=vs.85).aspx
GetModuleHandleW: [D.HMODULE, [D.LPCTSTR]], // retrive value from buf by ret.ref().readUInt32()
GetModuleHandleExW: [D.BOOL, [D.DWORD, D.LPCTSTR, D.HMODULE]], // flags, optional LPCTSTR name, ref hModule
GetProcessHeaps: [D.DWORD, [D.DWORD, D.PHANDLE]],
HeapFree: [D.BOOL, [D.HANDLE, D.DWORD, D.LPVOID]],
};
export interface Win32Fn {
GetLastError(): GT.DWORD;
GetModuleHandleW(lpModuleName: GT.LPCTSTR): GT.HMODULE;
GetModuleHandleExW(dwFlags: GT.DWORD, lpModuleName: GT.LPCTSTR | null, phModule: GT.HMODULE): GT.BOOL;
GetProcessHeaps(NumberOfHeaps: GT.DWORD, ProcessHeaps: GT.PHANDLE): GT.DWORD;
HeapFree( hHeap: GT.HANDLE, dwFlags: GT.DWORD, lpMem: GT.LPVOID | null): GT.BOOL;
}
| Add GetProcessHeaps(), HeapFree() of kernel32 | Add GetProcessHeaps(), HeapFree() of kernel32
| TypeScript | mit | waitingsong/node-win32-api,waitingsong/node-win32-api,waitingsong/node-win32-api | ---
+++
@@ -8,6 +8,10 @@
GetModuleHandleW: [D.HMODULE, [D.LPCTSTR]], // retrive value from buf by ret.ref().readUInt32()
GetModuleHandleExW: [D.BOOL, [D.DWORD, D.LPCTSTR, D.HMODULE]], // flags, optional LPCTSTR name, ref hModule
+
+ GetProcessHeaps: [D.DWORD, [D.DWORD, D.PHANDLE]],
+
+ HeapFree: [D.BOOL, [D.HANDLE, D.DWORD, D.LPVOID]],
};
export interface Win32Fn {
@@ -16,4 +20,8 @@
GetModuleHandleW(lpModuleName: GT.LPCTSTR): GT.HMODULE;
GetModuleHandleExW(dwFlags: GT.DWORD, lpModuleName: GT.LPCTSTR | null, phModule: GT.HMODULE): GT.BOOL;
+
+ GetProcessHeaps(NumberOfHeaps: GT.DWORD, ProcessHeaps: GT.PHANDLE): GT.DWORD;
+
+ HeapFree( hHeap: GT.HANDLE, dwFlags: GT.DWORD, lpMem: GT.LPVOID | null): GT.BOOL;
} |
fadad03fd87943a731202fe0eb520a340a117f18 | frontend/src/components/social-login-success/index.tsx | frontend/src/components/social-login-success/index.tsx | import { useQuery } from "@apollo/react-hooks";
import { Redirect, RouteComponentProps } from "@reach/router";
import { Box } from "@theme-ui/components";
import React from "react";
import { FormattedMessage } from "react-intl";
import { useLoginState } from "../../app/profile/hooks";
import { SocialLoginCheckQuery } from "../../generated/graphql-backend";
import SOCIAL_LOGIN_CHECK from "./social-login-check.graphql";
type Props = {
lang: string;
};
export const SocialLoginSuccess: React.SFC<RouteComponentProps<Props>> = ({
lang,
}) => {
const { loading, error, data } = useQuery<SocialLoginCheckQuery>(
SOCIAL_LOGIN_CHECK,
);
const [loggedIn, setLoggedIn] = useLoginState(false);
if (loggedIn) {
return <Redirect to={`/${lang}/profile/`} noThrow={true} />;
}
if (!loading && !error && data!.me) {
setLoggedIn(true);
return <Redirect to={`/${lang}/profile/`} noThrow={true} />;
}
if (!loading && error) {
return (
<Redirect
to={`/${lang}/login/`}
state={{
message: "Something went wrong, please try again",
}}
noThrow={true}
/>
);
}
return (
<Box
sx={{
maxWidth: "container",
mx: "auto",
px: 2,
}}
>
{loading && <FormattedMessage id="login.loading" />}
</Box>
);
};
| import { useQuery } from "@apollo/react-hooks";
import { Redirect, RouteComponentProps } from "@reach/router";
import { Box } from "@theme-ui/components";
import React from "react";
import { FormattedMessage } from "react-intl";
import { useLoginState } from "../../app/profile/hooks";
import { SocialLoginCheckQuery } from "../../generated/graphql-backend";
import SOCIAL_LOGIN_CHECK from "./social-login-check.graphql";
type Props = {
lang: string;
};
export const SocialLoginSuccess: React.SFC<RouteComponentProps<Props>> = ({
lang,
}) => {
const { loading, error, data } = useQuery<SocialLoginCheckQuery>(
SOCIAL_LOGIN_CHECK,
);
const [loggedIn, setLoggedIn] = useLoginState();
if (loggedIn) {
return <Redirect to={`/${lang}/profile/`} noThrow={true} />;
}
if (!loading && !error && data!.me) {
setLoggedIn(true);
return <Redirect to={`/${lang}/profile/`} noThrow={true} />;
}
if (!loading && error) {
return (
<Redirect
to={`/${lang}/login/`}
state={{
message: "Something went wrong, please try again",
}}
noThrow={true}
/>
);
}
return (
<Box
sx={{
maxWidth: "container",
mx: "auto",
px: 2,
}}
>
{loading && <FormattedMessage id="login.loading" />}
</Box>
);
};
| Fix usage of use login state | Fix usage of use login state
| TypeScript | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -18,7 +18,7 @@
const { loading, error, data } = useQuery<SocialLoginCheckQuery>(
SOCIAL_LOGIN_CHECK,
);
- const [loggedIn, setLoggedIn] = useLoginState(false);
+ const [loggedIn, setLoggedIn] = useLoginState();
if (loggedIn) {
return <Redirect to={`/${lang}/profile/`} noThrow={true} />; |
b1382a56b1a85b58ac204cc73a755df8520672e4 | helpers/fs.ts | helpers/fs.ts | import * as fs from "fs-extra";
import * as recursiveReaddir from "recursive-readdir";
export default class HelperFS {
/**
* Provides functionality of deprecated fs.exists()
* See https://github.com/nodejs/node/issues/1592
*/
public static async exists(filename: string): Promise<boolean> {
try {
await fs.access(filename);
return true;
} catch (err) {
return false;
}
}
/**
* Provides functionality of deprecated fs.existsSync()
* See https://github.com/nodejs/node/issues/1592
*/
public static existsSync(filename: string): boolean {
try {
fs.accessSync(filename);
return true;
} catch (ex) {
return false;
}
}
/**
* Maps the recursive-readdir module to a Promise interface.
*/
public static recursiveReaddir(path: string): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
recursiveReaddir(path, (err: Error, files: string[]) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
}
}
| import * as fs from "fs-extra";
import * as recursiveReaddir from "recursive-readdir";
export default class HelperFS {
/**
* DEPRECATED: use `fs-extra`.pathExists()
* Provides functionality of deprecated fs.exists()
* See https://github.com/nodejs/node/issues/1592
*/
public static async exists(filename: string): Promise<boolean> {
try {
await fs.access(filename);
return true;
} catch (err) {
return false;
}
}
/**
* DEPRECATED: use `fs-extra`.pathExistsSync()
* Provides functionality of deprecated fs.existsSync()
* See https://github.com/nodejs/node/issues/1592
*/
public static existsSync(filename: string): boolean {
try {
fs.accessSync(filename);
return true;
} catch (ex) {
return false;
}
}
/**
* Maps the recursive-readdir module to a Promise interface.
*/
public static recursiveReaddir(path: string): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
recursiveReaddir(path, (err: Error, files: string[]) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
}
}
| Mark FS helpers as deprecated | Mark FS helpers as deprecated
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -3,6 +3,7 @@
export default class HelperFS {
/**
+ * DEPRECATED: use `fs-extra`.pathExists()
* Provides functionality of deprecated fs.exists()
* See https://github.com/nodejs/node/issues/1592
*/
@@ -16,6 +17,7 @@
}
/**
+ * DEPRECATED: use `fs-extra`.pathExistsSync()
* Provides functionality of deprecated fs.existsSync()
* See https://github.com/nodejs/node/issues/1592
*/ |
25cf0590adbfdc7927c4bfdd5dbe6f2157dea397 | JSlider.ts | JSlider.ts | /**
* Created by sigurdbergsvela on 15.01.14.
*/
///<reference path="defs/jquery.d.ts"/>
class JSlider {
private _options = {
};
private sliderWrapper : JQuery;
private slidesWrapper : JQuery;
private slides : JQuery;
private currentSlide : number;
/**
* Creates a new slider out of an HTMLElement
*
* The htmlElement is expected to be the wrapper of the slider.
* The structur is expected to be
* <div> <!--The slider wrapper-->
* <ul> <!--The slides-->
* <li></li> <!--A Single slide-->
* <li></li> <!--A Single slide-->
* <li></li> <!--A Single slide-->
* </ul>
* </div>
*
* The ul element will be gived display:block, and all the LI elements will
* be given a width and height of 100%;
*
* options
* .delay : How long between each slide, -1 for no automated sliding
*/
constructor(sliderWrapper : HTMLDivElement, options : Object = {}) {
this._options['delay'] = options['delay'] || 100;
this.sliderWrapper = jQuery(sliderWrapper);
this.slidesWrapper = this.sliderWrapper.children("ul");
this.slides = this.slidesWrapper.children("li");
this.currentSlide = 0;
}
public start() : void {
}
} | /**
* Created by sigurdbergsvela on 15.01.14.
*/
///<reference path="defs/jquery.d.ts"/>
class JSlider {
private _options = {
};
private sliderWrapper : JQuery;
private slidesWrapper : JQuery;
private slides : JQuery;
private currentSlide : number;
/**
* Creates a new slider out of an HTMLElement
*
* The htmlElement is expected to be the wrapper of the slider.
* The structur is expected to be
* <div> <!--The slider wrapper-->
* <ul> <!--The slides-->
* <li></li> <!--A Single slide-->
* <li></li> <!--A Single slide-->
* <li></li> <!--A Single slide-->
* </ul>
* </div>
*
* The ul element will be gived display:block, and all the LI elements will
* be given a width and height of 100%;
*
* options
* .delay : How long between each slide, -1 for no automated sliding
*/
constructor(sliderWrapper : HTMLDivElement, options : Object = {}) {
this._options['delay'] = options['delay'] || 100;
this.sliderWrapper = jQuery(sliderWrapper);
this.slidesWrapper = this.sliderWrapper.children("ul");
this.slides = this.slidesWrapper.children("li");
this.currentSlide = 0;
this.slides.css({
"height" : "100%",
"width" : "100%"
});
}
public start() : void {
}
} | Set size of slides to 100% width and height | Set size of slides to 100% width and height
| TypeScript | lgpl-2.1 | sigurdsvela/JSlider | ---
+++
@@ -38,6 +38,11 @@
this.slides = this.slidesWrapper.children("li");
this.currentSlide = 0;
+
+ this.slides.css({
+ "height" : "100%",
+ "width" : "100%"
+ });
}
public start() : void { |
9936147bc9ccb8f21012f87295a6779759221536 | src/search/bookmarks.ts | src/search/bookmarks.ts | import { Bookmarks } from 'webextension-polyfill-ts'
import { TabManager } from 'src/activity-logger/background/tab-manager'
import { pageIsStub } from 'src/page-indexing/utils'
import PageStorage from 'src/page-indexing/background/storage'
import BookmarksStorage from 'src/bookmarks/background/storage'
import { PageIndexingBackground } from 'src/page-indexing/background'
export const addBookmark = (
pages: PageIndexingBackground,
bookmarksStorage: BookmarksStorage,
tabManager: TabManager,
) => async ({
url,
timestamp = Date.now(),
tabId,
}: {
url: string
timestamp?: number
tabId?: number
}) => {
const page = await pages.storage.getPage(url)
if (page == null || pageIsStub(page)) {
await pages.createPageViaBmTagActs({ url, tabId })
}
await bookmarksStorage.createBookmarkIfNeeded(page.url, timestamp)
tabManager.setBookmarkState(url, true)
}
export const delBookmark = (
pageStorage: PageStorage,
bookmarksStorage: BookmarksStorage,
tabManager: TabManager,
) => async ({ url }: Partial<Bookmarks.BookmarkTreeNode>) => {
await bookmarksStorage.delBookmark({ url })
await pageStorage.deletePageIfOrphaned(url)
tabManager.setBookmarkState(url, false)
}
export const pageHasBookmark = (bookmarksStorage: BookmarksStorage) => async (
url: string,
) => {
return bookmarksStorage.pageHasBookmark(url)
}
| import { Bookmarks } from 'webextension-polyfill-ts'
import { TabManager } from 'src/activity-logger/background/tab-manager'
import { pageIsStub } from 'src/page-indexing/utils'
import PageStorage from 'src/page-indexing/background/storage'
import BookmarksStorage from 'src/bookmarks/background/storage'
import { PageIndexingBackground } from 'src/page-indexing/background'
export const addBookmark = (
pages: PageIndexingBackground,
bookmarksStorage: BookmarksStorage,
tabManager: TabManager,
) => async (params: { url: string; timestamp?: number; tabId?: number }) => {
let page = await pages.storage.getPage(params.url)
if (page == null || pageIsStub(page)) {
page = await pages.createPageViaBmTagActs({
url: params.url,
tabId: params.tabId,
})
}
await bookmarksStorage.createBookmarkIfNeeded(page.url, params.timestamp)
tabManager.setBookmarkState(params.url, true)
}
export const delBookmark = (
pageStorage: PageStorage,
bookmarksStorage: BookmarksStorage,
tabManager: TabManager,
) => async ({ url }: Partial<Bookmarks.BookmarkTreeNode>) => {
await bookmarksStorage.delBookmark({ url })
await pageStorage.deletePageIfOrphaned(url)
tabManager.setBookmarkState(url, false)
}
export const pageHasBookmark = (bookmarksStorage: BookmarksStorage) => async (
url: string,
) => {
return bookmarksStorage.pageHasBookmark(url)
}
| Fix error that occured when bookmarking a page that isn't saved in the database | Fix error that occured when bookmarking a page that isn't saved in the database
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -10,23 +10,17 @@
pages: PageIndexingBackground,
bookmarksStorage: BookmarksStorage,
tabManager: TabManager,
-) => async ({
- url,
- timestamp = Date.now(),
- tabId,
-}: {
- url: string
- timestamp?: number
- tabId?: number
-}) => {
- const page = await pages.storage.getPage(url)
-
+) => async (params: { url: string; timestamp?: number; tabId?: number }) => {
+ let page = await pages.storage.getPage(params.url)
if (page == null || pageIsStub(page)) {
- await pages.createPageViaBmTagActs({ url, tabId })
+ page = await pages.createPageViaBmTagActs({
+ url: params.url,
+ tabId: params.tabId,
+ })
}
- await bookmarksStorage.createBookmarkIfNeeded(page.url, timestamp)
- tabManager.setBookmarkState(url, true)
+ await bookmarksStorage.createBookmarkIfNeeded(page.url, params.timestamp)
+ tabManager.setBookmarkState(params.url, true)
}
export const delBookmark = ( |
3fdc3e999ef5aa7c6de67b5cc50181dc51feb297 | src/content/repositories/ClipboardRepository.ts | src/content/repositories/ClipboardRepository.ts | export default interface ClipboardRepository {
read(): string;
write(text: string): void;
}
export class ClipboardRepositoryImpl {
read(): string {
const textarea = window.document.createElement("textarea");
window.document.body.append(textarea);
textarea.style.position = "fixed";
textarea.style.top = "-100px";
textarea.contentEditable = "true";
textarea.focus();
const ok = window.document.execCommand("paste");
const value = textarea.textContent!;
textarea.remove();
if (!ok) {
throw new Error("failed to access clipbaord");
}
return value;
}
write(text: string): void {
const input = window.document.createElement("input");
window.document.body.append(input);
input.style.position = "fixed";
input.style.top = "-100px";
input.value = text;
input.select();
const ok = window.document.execCommand("copy");
input.remove();
if (!ok) {
throw new Error("failed to access clipbaord");
}
}
}
| export default interface ClipboardRepository {
read(): string;
write(text: string): void;
}
export class ClipboardRepositoryImpl {
read(): string {
const textarea = window.document.createElement("textarea");
window.document.body.append(textarea);
textarea.style.position = "fixed";
textarea.style.top = "-100px";
textarea.contentEditable = "true";
textarea.focus();
const ok = window.document.execCommand("paste");
const value = textarea.value;
textarea.remove();
if (!ok) {
throw new Error("failed to access clipbaord");
}
return value;
}
write(text: string): void {
const input = window.document.createElement("input");
window.document.body.append(input);
input.style.position = "fixed";
input.style.top = "-100px";
input.value = text;
input.select();
const ok = window.document.execCommand("copy");
input.remove();
if (!ok) {
throw new Error("failed to access clipbaord");
}
}
}
| Read clipboard from textarea element's value | Read clipboard from textarea element's value
| TypeScript | mit | ueokande/vim-vixen,ueokande/vim-vixen,ueokande/vim-vixen | ---
+++
@@ -15,7 +15,7 @@
textarea.focus();
const ok = window.document.execCommand("paste");
- const value = textarea.textContent!;
+ const value = textarea.value;
textarea.remove();
if (!ok) { |
55a0a492c7703fc061c6f1082b0e40f894c900fc | saleor/static/dashboard-next/storybook/Decorator.tsx | saleor/static/dashboard-next/storybook/Decorator.tsx | import CssBaseline from "@material-ui/core/CssBaseline";
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import * as React from "react";
import { Provider as DateProvider } from "../components/DateFormatter/DateContext";
import { MessageManager } from "../components/messages";
import { TimezoneProvider } from "../components/Timezone";
import theme from "../theme";
export const Decorator = storyFn => (
<DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
<TimezoneProvider value="America/New_York">
<MuiThemeProvider theme={theme}>
<CssBaseline />
<MessageManager>
<div>{storyFn()}</div>
</MessageManager>
</MuiThemeProvider>
</TimezoneProvider>
</DateProvider>
);
export default Decorator;
| import CssBaseline from "@material-ui/core/CssBaseline";
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import * as React from "react";
import { Provider as DateProvider } from "../components/DateFormatter/DateContext";
import { FormProvider } from "../components/Form";
import { MessageManager } from "../components/messages";
import { TimezoneProvider } from "../components/Timezone";
import theme from "../theme";
export const Decorator = storyFn => (
<FormProvider>
<DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
<TimezoneProvider value="America/New_York">
<MuiThemeProvider theme={theme}>
<CssBaseline />
<MessageManager>
<div>{storyFn()}</div>
</MessageManager>
</MuiThemeProvider>
</TimezoneProvider>
</DateProvider>
</FormProvider>
);
export default Decorator;
| Add form provider to decorator | Add form provider to decorator
| TypeScript | bsd-3-clause | maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor | ---
+++
@@ -3,20 +3,23 @@
import * as React from "react";
import { Provider as DateProvider } from "../components/DateFormatter/DateContext";
+import { FormProvider } from "../components/Form";
import { MessageManager } from "../components/messages";
import { TimezoneProvider } from "../components/Timezone";
import theme from "../theme";
export const Decorator = storyFn => (
- <DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
- <TimezoneProvider value="America/New_York">
- <MuiThemeProvider theme={theme}>
- <CssBaseline />
- <MessageManager>
- <div>{storyFn()}</div>
- </MessageManager>
- </MuiThemeProvider>
- </TimezoneProvider>
- </DateProvider>
+ <FormProvider>
+ <DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
+ <TimezoneProvider value="America/New_York">
+ <MuiThemeProvider theme={theme}>
+ <CssBaseline />
+ <MessageManager>
+ <div>{storyFn()}</div>
+ </MessageManager>
+ </MuiThemeProvider>
+ </TimezoneProvider>
+ </DateProvider>
+ </FormProvider>
);
export default Decorator; |
aa5a1722e8d9871ac4b660574595701818786fe0 | 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'
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='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>
);
}
| Fix score replay download button | Fix score replay download button
| TypeScript | agpl-3.0 | ppy/osu-web,nanaya/osu-web,nanaya/osu-web,LiquidPL/osu-web,LiquidPL/osu-web,nanaya/osu-web,ppy/osu-web,ppy/osu-web,LiquidPL/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,nanaya/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,LiquidPL/osu-web,ppy/osu-web,LiquidPL/osu-web,notbakaneko/osu-web | ---
+++
@@ -18,6 +18,7 @@
{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')} |
dd5b155ae286a546e880a4be9551f185f29f64a9 | types/custom-functions-runtime/index.d.ts | types/custom-functions-runtime/index.d.ts | // Type definitions for Custom Functions 1.4
// Project: http://dev.office.com
// Definitions by: OfficeDev <https://github.com/OfficeDev>, Michael Zlatkovsky <https://github.com/Zlatkovsky>, Michelle Scharlock <https://github.com/mscharlock>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/*
office-js
Copyright (c) Microsoft Corporation
*/
////////////////////////////////////////////////////////////////
//////////////////// Begin custom-functions-runtime ////////////
////////////////////////////////////////////////////////////////
/**
* Enables you to map your own name that uses lowercase letters to a function.
*/
declare let CustomFunctionMappings: { [key: string]: Function };
declare namespace CustomFunctions {
interface StreamingHandler<T> extends CancelableHandler {
/**
* Sets the returned result for a streaming custom function.
* @beta
*/
setResult: (value: T) => void;
}
interface CancelableHandler {
/**
* Handles what should occur when a custom function is canceled.
* @beta
*/
onCanceled: () => void;
}
}
////////////////////////////////////////////////////////////////
//////////////////// End custom-functions-runtime ////////////
////////////////////////////////////////////////////////////////
| // Type definitions for Custom Functions 1.4
// Project: http://dev.office.com
// Definitions by: OfficeDev <https://github.com/OfficeDev>, Michael Zlatkovsky <https://github.com/Zlatkovsky>, Michelle Scharlock <https://github.com/mscharlock>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/*
office-js
Copyright (c) Microsoft Corporation
*/
////////////////////////////////////////////////////////////////
//////////////////// Begin custom-functions-runtime ////////////
////////////////////////////////////////////////////////////////
/**
* Enables you to map your own name that uses lowercase letters to a function.
*/
declare let CustomFunctionMappings: { [key: string]: Function };
declare namespace CustomFunctions {
interface StreamingHandler<T> extends CancelableHandler {
/**
* Sets the returned result for a streaming custom function.
* @beta
*/
setResult: (value: T | Error) => void;
}
interface CancelableHandler {
/**
* Handles what should occur when a custom function is canceled.
* @beta
*/
onCanceled: () => void;
}
}
////////////////////////////////////////////////////////////////
//////////////////// End custom-functions-runtime ////////////
////////////////////////////////////////////////////////////////
| Allow streaming Custom Functions to be set with an Error result | Allow streaming Custom Functions to be set with an Error result
| TypeScript | mit | dsebastien/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped | ---
+++
@@ -24,7 +24,7 @@
* Sets the returned result for a streaming custom function.
* @beta
*/
- setResult: (value: T) => void;
+ setResult: (value: T | Error) => void;
}
interface CancelableHandler { |
61970836544f8879bf5cb38b979c2f566a99bd57 | jupyter-widgets-htmlmanager/test/src/output_test.ts | jupyter-widgets-htmlmanager/test/src/output_test.ts |
import * as chai from 'chai';
describe('output', () => {
it('work', () => {
})
})
|
import * as chai from 'chai';
import { HTMLManager } from '../../lib/';
import { OutputModel, OutputView } from '../../lib/output';
describe('output', () => {
let model;
let view;
let manager;
beforeEach(async function() {
const widgetTag = document.createElement('div');
widgetTag.className = 'widget-subarea';
document.body.appendChild(widgetTag);
manager = new HTMLManager()
const modelId = 'u-u-i-d';
model = await manager.new_model({
model_name: 'OutputModel',
model_id: modelId,
model_module: '@jupyter-widgets/controls',
state: {
outputs: [
{
"output_type": "stream",
"name": "stdout",
"text": "hi\n"
}
],
}
});
view = await manager.display_model(
undefined, model, { el: widgetTag }
);
})
it('show the view', () => {
console.error(view);
});
})
| Test fixture for output widget | Test fixture for output widget
| TypeScript | bsd-3-clause | SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets | ---
+++
@@ -1,7 +1,41 @@
import * as chai from 'chai';
+import { HTMLManager } from '../../lib/';
+import { OutputModel, OutputView } from '../../lib/output';
+
describe('output', () => {
- it('work', () => {
+
+ let model;
+ let view;
+ let manager;
+
+ beforeEach(async function() {
+ const widgetTag = document.createElement('div');
+ widgetTag.className = 'widget-subarea';
+ document.body.appendChild(widgetTag);
+ manager = new HTMLManager()
+ const modelId = 'u-u-i-d';
+ model = await manager.new_model({
+ model_name: 'OutputModel',
+ model_id: modelId,
+ model_module: '@jupyter-widgets/controls',
+ state: {
+ outputs: [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": "hi\n"
+ }
+ ],
+ }
+ });
+ view = await manager.display_model(
+ undefined, model, { el: widgetTag }
+ );
})
+
+ it('show the view', () => {
+ console.error(view);
+ });
}) |
2899c07eae6b273279aca67a5555fc747a4851c9 | src/game.ts | src/game.ts | import {MaxesState} from "./state/MaxesState";
export class Game extends Phaser.Game {
constructor() {
super("100", "100", Phaser.AUTO);
this.state.add("maxes", MaxesState);
this.state.start("maxes");
}
}
| import { MaxesState } from "./state/MaxesState";
export class Game extends Phaser.Game {
constructor() {
super("100", "100", Phaser.CANVAS);
this.preserveDrawingBuffer = true;
this.state.add("maxes", MaxesState);
this.state.start("maxes");
}
}
| Add workaround for flickering issue on Mali-400 GPUs. | Add workaround for flickering issue on Mali-400 GPUs.
| TypeScript | mit | NickH-nz/ts-reference-for-automated-testing | ---
+++
@@ -1,8 +1,10 @@
-import {MaxesState} from "./state/MaxesState";
+import { MaxesState } from "./state/MaxesState";
export class Game extends Phaser.Game {
constructor() {
- super("100", "100", Phaser.AUTO);
+ super("100", "100", Phaser.CANVAS);
+
+ this.preserveDrawingBuffer = true;
this.state.add("maxes", MaxesState);
|
a3a0b52bf24aea09d5f0cd9e457ad6d60ae0a1e8 | src/utils/logger.test.ts | src/utils/logger.test.ts | /* eslint-disable no-console */
import { loggerFns, OBJ, MESSAGE } from '../../test/fixtures';
import logger, { Logger, LoggerFunction } from './logger';
type IndexableConsole = typeof console & {
[key: string]: LoggerFunction | jest.Mocked<LoggerFunction>;
};
type IndexableLogger = Logger & {
[key: string]: LoggerFunction;
};
const indexableConsole = console as IndexableConsole;
const indexableLogger = logger as IndexableLogger;
describe('util: logger', () => {
it('returns an object with all the expected methods', () => {
expect(logger).toEqual(
expect.objectContaining(
loggerFns.reduce(
(obj, fn) => ({
...obj,
[fn]: expect.any(Function),
}),
{},
),
),
);
});
it('calls the corresponding console functions with the same arguments', () => {
const args = [MESSAGE, OBJ];
loggerFns.forEach(fn => {
const orig = indexableConsole[fn];
indexableConsole[fn] = jest.fn();
expect(indexableConsole[fn]).toHaveBeenCalledTimes(0);
indexableLogger[fn](...args);
expect(indexableConsole[fn]).toHaveBeenCalledTimes(1);
expect(indexableConsole[fn]).toHaveBeenCalledWith(...args);
indexableConsole[fn] = orig;
});
});
});
| /* eslint-disable no-console */
import { loggerFns, OBJ, MESSAGE } from '../../test/fixtures';
import logger, { Logger, LoggerFunction } from './logger';
type IndexableConsole = typeof console & {
[key: string]: LoggerFunction | jest.Mocked<LoggerFunction>;
};
type IndexableLogger = Logger & {
[key: string]: LoggerFunction;
};
const indexableConsole = console as IndexableConsole;
const indexableLogger = logger as IndexableLogger;
describe('util: logger', () => {
it('returns an object with all the expected methods', () => {
expect(logger).toEqual(
expect.objectContaining(
loggerFns.reduce(
(obj, fn) => ({
...obj,
[fn]: expect.any(Function),
}),
{},
),
),
);
});
it('calls the corresponding console functions with the same arguments', () => {
const args = [MESSAGE, OBJ];
loggerFns.forEach(fn => {
const orig = indexableConsole[fn];
// eslint-disable-next-line jest/prefer-spy-on
indexableConsole[fn] = jest.fn();
expect(indexableConsole[fn]).toHaveBeenCalledTimes(0);
indexableLogger[fn](...args);
expect(indexableConsole[fn]).toHaveBeenCalledTimes(1);
expect(indexableConsole[fn]).toHaveBeenCalledWith(...args);
indexableConsole[fn] = orig;
});
});
});
| Disable jest/prefer-spy-on rule for a one-off | Disable jest/prefer-spy-on rule for a one-off
| TypeScript | mit | wKovacs64/pwned,wKovacs64/pwned | ---
+++
@@ -32,6 +32,7 @@
const args = [MESSAGE, OBJ];
loggerFns.forEach(fn => {
const orig = indexableConsole[fn];
+ // eslint-disable-next-line jest/prefer-spy-on
indexableConsole[fn] = jest.fn();
expect(indexableConsole[fn]).toHaveBeenCalledTimes(0);
indexableLogger[fn](...args); |
72feff21babbbb428256920ea7da17fec0161ed1 | packages/reducers/src/core/communication/kernels.ts | packages/reducers/src/core/communication/kernels.ts | import { combineReducers } from "redux-immutable";
import { Action } from "redux";
import * as Immutable from "immutable";
import {
makeKernelCommunicationRecord,
makeKernelsCommunicationRecord
} from "@nteract/types";
import * as actions from "@nteract/actions";
// TODO: we should spec out a way to watch the killKernel lifecycle.
const byRef = (state = Immutable.Map(), action: Action) => {
let typedAction;
switch (action.type) {
case actions.RESTART_KERNEL:
case actions.LAUNCH_KERNEL:
case actions.LAUNCH_KERNEL_BY_NAME:
typedAction = action as actions.LaunchKernelAction;
return state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: null,
loading: true
})
);
case actions.RESTART_KERNEL_SUCCESSFUL:
case actions.LAUNCH_KERNEL_SUCCESSFUL:
typedAction = action as actions.RestartKernelSuccessful;
return state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: null,
loading: false
})
);
case actions.RESTART_KERNEL_FAILED:
case actions.LAUNCH_KERNEL_FAILED:
typedAction = action as actions.LaunchKernelFailed;
return state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: typedAction.payload.error,
loading: false
})
);
default:
return state;
}
};
export const kernels = combineReducers(
{ byRef },
makeKernelsCommunicationRecord as any
);
| import { combineReducers } from "redux-immutable";
import { Action } from "redux";
import * as Immutable from "immutable";
import {
makeKernelCommunicationRecord,
makeKernelsCommunicationRecord
} from "@nteract/types";
import * as actions from "@nteract/actions";
// TODO: we should spec out a way to watch the killKernel lifecycle.
const byRef = (state = Immutable.Map(), action: Action) => {
let typedAction;
switch (action.type) {
case actions.RESTART_KERNEL:
case actions.LAUNCH_KERNEL:
case actions.LAUNCH_KERNEL_BY_NAME:
typedAction = action as actions.LaunchKernelAction;
return state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: null,
loading: true
})
);
case actions.RESTART_KERNEL_SUCCESSFUL:
case actions.LAUNCH_KERNEL_SUCCESSFUL:
typedAction = action as actions.RestartKernelSuccessful;
return state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: null,
loading: false
})
);
case actions.RESTART_KERNEL_FAILED:
case actions.LAUNCH_KERNEL_FAILED:
typedAction = action as actions.LaunchKernelFailed;
return typedAction.payload.kernelRef
? state.set(
typedAction.payload.kernelRef,
makeKernelCommunicationRecord({
error: typedAction.payload.error,
loading: false
})
)
: state;
default:
return state;
}
};
export const kernels = combineReducers(
{ byRef },
makeKernelsCommunicationRecord as any
);
| Add defensive check for kernelRef in failed action | Add defensive check for kernelRef in failed action
| TypeScript | bsd-3-clause | nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract,rgbkrk/nteract,rgbkrk/nteract,nteract/nteract,rgbkrk/nteract,nteract/composition,rgbkrk/nteract,nteract/composition,rgbkrk/nteract,nteract/nteract | ---
+++
@@ -36,13 +36,15 @@
case actions.RESTART_KERNEL_FAILED:
case actions.LAUNCH_KERNEL_FAILED:
typedAction = action as actions.LaunchKernelFailed;
- return state.set(
- typedAction.payload.kernelRef,
- makeKernelCommunicationRecord({
- error: typedAction.payload.error,
- loading: false
- })
- );
+ return typedAction.payload.kernelRef
+ ? state.set(
+ typedAction.payload.kernelRef,
+ makeKernelCommunicationRecord({
+ error: typedAction.payload.error,
+ loading: false
+ })
+ )
+ : state;
default:
return state;
} |
e341abd96558fb529187b2feab8e553340076deb | src/resolve/latest-solver.ts | src/resolve/latest-solver.ts | import { satisfies } from 'semver';
import { Workspace } from '../workspace';
import { Dependency } from '../manifest';
import { Registration } from '../sources';
import { DependencyGraph } from './dependency-graph';
import Resolver, { Resolution } from './resolver';
import unique from '../utils/unique';
export default async function solve(
workspace: Workspace,
resolver: Resolver
): Promise<DependencyGraph> {
const dependencies = workspace.root.dependencies;
await resolveDependencies(dependencies, resolver);
const graph = [];
const errors = [];
for (const [name, resolution] of resolver) {
const matching = getMatching(resolution);
if (!matching) {
errors.push(resolution);
} else {
graph.push(matching);
}
}
if (errors.length) {
// TODO
throw new Error('Unable to resolve dependency graph for given manifest');
}
return graph;
}
export async function resolveDependencies(
dependencies: Dependency[],
resolver: Resolver
): Promise<void> {
const resolved = await Promise.all(
dependencies.map(dependency => resolver.get(dependency))
);
for (const resolution of resolved) {
const { registered } = resolution;
const latest = getMatching(resolution) || registered[registered.length - 1];
await resolveDependencies(latest.dependencies, resolver);
}
}
export function getMatching(resolution: Resolution): Registration | undefined {
const range = unique(resolution.range).join(' ');
const registered = resolution.registered.slice().reverse();
return registered.find(registration =>
satisfies(registration.version, range)
);
}
| import { satisfies } from 'semver';
import { Workspace } from '../workspace';
import { Dependency } from '../manifest';
import { Registration } from '../sources';
import { DependencyGraph } from './dependency-graph';
import Resolver, { Resolution } from './resolver';
import unique from '../utils/unique';
export default async function solve(
workspace: Workspace,
resolver: Resolver
): Promise<DependencyGraph> {
const dependencies = workspace.root.dependencies;
await resolveDependencies(dependencies, resolver);
const graph = [];
const errors = [];
for (const [name, resolution] of resolver) {
const matching = getMatching(resolution);
if (!matching) {
errors.push(resolution);
} else {
graph.push(matching);
}
}
if (errors.length) {
// TODO
throw new Error('Unable to resolve dependency graph for given manifest');
}
return graph;
}
export async function resolveDependencies(
dependencies: Dependency[],
resolver: Resolver
): Promise<void> {
const resolved = await Promise.all(
dependencies.map(dependency => resolver.get(dependency))
);
for (const resolution of resolved) {
const { registered } = resolution;
const latest = getMatching(resolution) || registered[registered.length - 1];
await resolveDependencies(latest.dependencies, resolver);
}
}
export function getMatching(resolution: Resolution): Registration | undefined {
const range = unique(resolution.range).join(' ');
const registered = resolution.registered.slice().reverse();
return !range
? registered[0]
: registered.find(registration => satisfies(registration.version, range));
}
| Handle resolve with no version (e.g. path dependencies) | Handle resolve with no version (e.g. path dependencies)
| TypeScript | mit | vba-blocks/vba-blocks,vba-blocks/vba-blocks,vba-blocks/vba-blocks | ---
+++
@@ -53,7 +53,7 @@
const range = unique(resolution.range).join(' ');
const registered = resolution.registered.slice().reverse();
- return registered.find(registration =>
- satisfies(registration.version, range)
- );
+ return !range
+ ? registered[0]
+ : registered.find(registration => satisfies(registration.version, range));
} |
1ebf3979967a9199f529d2553a5e18aeb98947db | src/providers/auth-service.ts | src/providers/auth-service.ts | import { SettingService } from './setting-service';
import { Filter } from './../models/filter';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { ImsService } from './ims-service';
import { Observable } from 'rxjs/Observable';
import { Credential } from '../models/credential';
import { Info } from '../models/info';
@Injectable()
export class AuthService {
currentCredential: Credential;
archive: string;
filterId: number;
constructor(public http: Http, public imsService: ImsService, public settingService: SettingService) {
}
login(credentials): Observable<Info> {
return this.imsService.getInfo(credentials).map(info => this.setCurrentCredential(info, credentials));
}
logout() {
this.currentCredential = null;
}
setCurrentCredential(info: Info, credentials: Credential): Info {
this.currentCredential = credentials;
return info;
}
setArchive(filter: Filter) {
this.settingService.setFilter(this.currentCredential.server, this.currentCredential.username, filter);
this.archive = filter.archiveName;
this.filterId = Number(filter.id);
}
}
| import { SettingService } from './setting-service';
import { Filter } from './../models/filter';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import { ImsService } from './ims-service';
import { Observable } from 'rxjs/Observable';
import { Credential } from '../models/credential';
import { Info } from '../models/info';
@Injectable()
export class AuthService {
DEFAULT_LOGIN_TIMEOUT: number = 5000;
currentCredential: Credential;
archive: string;
filterId: number;
constructor(public http: Http, public imsService: ImsService, public settingService: SettingService) {
}
login(credentials): Observable<Info> {
return this.imsService.getInfo(credentials).map(info => this.setCurrentCredential(info, credentials)).timeout(this.DEFAULT_LOGIN_TIMEOUT);
}
logout() {
this.currentCredential = null;
}
setCurrentCredential(info: Info, credentials: Credential): Info {
this.currentCredential = credentials;
return info;
}
setArchive(filter: Filter) {
this.settingService.setFilter(this.currentCredential.server, this.currentCredential.username, filter);
this.archive = filter.archiveName;
this.filterId = Number(filter.id);
}
}
| Add as quickfix to prevent endless login on 401 on ios. | Add as quickfix to prevent endless login on 401 on ios.
| TypeScript | mit | IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app | ---
+++
@@ -3,6 +3,7 @@
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/timeout';
import { ImsService } from './ims-service';
import { Observable } from 'rxjs/Observable';
import { Credential } from '../models/credential';
@@ -11,15 +12,17 @@
@Injectable()
export class AuthService {
+ DEFAULT_LOGIN_TIMEOUT: number = 5000;
currentCredential: Credential;
archive: string;
filterId: number;
+
constructor(public http: Http, public imsService: ImsService, public settingService: SettingService) {
}
login(credentials): Observable<Info> {
- return this.imsService.getInfo(credentials).map(info => this.setCurrentCredential(info, credentials));
+ return this.imsService.getInfo(credentials).map(info => this.setCurrentCredential(info, credentials)).timeout(this.DEFAULT_LOGIN_TIMEOUT);
}
logout() { |
3a82c2207710d67ee2829a0f2ae1fc66bddea6cd | src/SyntaxNodes/getEntriesForTableOfContents.ts | src/SyntaxNodes/getEntriesForTableOfContents.ts | import { OutlineSyntaxNode } from './OutlineSyntaxNode'
import { UpDocument } from './UpDocument'
import { Heading } from './Heading'
import { concat } from '../CollectionHelpers'
export function getEntriesForTableOfContents(nodes: OutlineSyntaxNode[]): UpDocument.TableOfContents.Entry[] {
return concat(
nodes.map(node =>
node instanceof Heading
? [node]
: node.descendantsToIncludeInTableOfContents()
))
}
| import { OutlineSyntaxNode } from './OutlineSyntaxNode'
import { UpDocument } from './UpDocument'
import { Heading } from './Heading'
import { concat } from '../CollectionHelpers'
export function getEntriesForTableOfContents(nodes: OutlineSyntaxNode[]): UpDocument.TableOfContents.Entry[] {
return concat(
nodes.map(node =>
node instanceof Heading
? [node]
: node.descendantsToIncludeInTableOfContents()))
}
| Use consistent close parenthesis placement | Use consistent close parenthesis placement
| TypeScript | mit | start/up,start/up | ---
+++
@@ -9,6 +9,5 @@
nodes.map(node =>
node instanceof Heading
? [node]
- : node.descendantsToIncludeInTableOfContents()
- ))
+ : node.descendantsToIncludeInTableOfContents()))
} |
c7eed5c11e604b4246575cb8f4ebf58f2ca8217c | src/SegmentParser.ts | src/SegmentParser.ts | import {
Config,
ParserConfig,
validate,
parseConfig,
ConversionType
} from './config/index';
type Parsed = string | number | Date;
interface ParsedData {
[key: string]: Parsed;
}
export default class SegmentParser {
config: ParserConfig;
constructor(rawConfig: Config) {
this.config = parseConfig(validate(rawConfig));
}
parse(input: string): ParsedData {
const { fields } = this.config;
return fields.reduce((accum, field) => {
const { name, range, convertTo } = field;
const data = this.convert(input.slice(...range), convertTo);
return { ...accum, [name]: data };
}, {});
}
private convert(s: string, convertTo: ConversionType): Parsed {
switch (convertTo) {
case 'numeric':
return parseInt(s);
case 'date':
const re = /(\d{2})(\d{2})(\d{4})/;
const [, month, day, year] = re.exec(s);
return new Date(`${month}/${day}/${year}`);
default:
return s;
}
}
}
| import {
Config,
ParserConfig,
validate,
parseConfig,
ConversionType
} from './config/index';
type Parsed = string | number | Date;
interface ParsedData {
[key: string]: Parsed;
}
export default class SegmentParser {
config: ParserConfig;
constructor(rawConfig: Config) {
this.config = parseConfig(validate(rawConfig));
}
parse(input: string): ParsedData {
const { fields, size } = this.config;
if (input.length !== size) {
throw Error(
'The provided data does not match the length for this section'
);
}
return fields.reduce((accum, field) => {
const { name, range, convertTo } = field;
const data = this.convert(input.slice(...range), convertTo);
return { ...accum, [name]: data };
}, {});
}
private convert(s: string, convertTo: ConversionType): Parsed {
switch (convertTo) {
case 'numeric':
return parseInt(s);
case 'date':
const re = /(\d{2})(\d{2})(\d{4})/;
const [, month, day, year] = re.exec(s);
return new Date(`${month}/${day}/${year}`);
default:
return s;
}
}
}
| Throw an error if the size of the file doesn't match | Throw an error if the size of the file doesn't match
| TypeScript | mit | adregan/segment-parser,adregan/segment-parser | ---
+++
@@ -18,7 +18,13 @@
}
parse(input: string): ParsedData {
- const { fields } = this.config;
+ const { fields, size } = this.config;
+
+ if (input.length !== size) {
+ throw Error(
+ 'The provided data does not match the length for this section'
+ );
+ }
return fields.reduce((accum, field) => {
const { name, range, convertTo } = field; |
0d5fb0720077993c4f6c2f76a62233f58e32beb6 | src/Test/Html/Config/ToggleNsfl.ts | src/Test/Html/Config/ToggleNsfl.ts | import { expect } from 'chai'
import Up from '../../../index'
import { InlineNsflNode } from '../../../SyntaxNodes/InlineNsflNode'
describe("The text in an inline NSFL convention's label", () => {
it("uses the provided term for 'toggleNsfl'", () => {
const up = new Up({
i18n: {
terms: { toggleNsfl: 'show/hide' }
}
})
const node = new InlineNsflNode([])
const html =
'<span class="up-nsfl up-revealable">'
+ '<label for="up-nsfl-1">show/hide</label>'
+ '<input id="up-nsfl-1" type="checkbox">'
+ '<span></span>'
+ '</span>'
expect(up.toHtml(node)).to.be.eql(html)
})
})
| import { expect } from 'chai'
import Up from '../../../index'
import { InlineNsflNode } from '../../../SyntaxNodes/InlineNsflNode'
import { NsflBlockNode } from '../../../SyntaxNodes/NsflBlockNode'
describe("The text in an inline NSFL convention's label", () => {
it("uses the provided term for 'toggleNsfl'", () => {
const up = new Up({
i18n: {
terms: { toggleNsfl: 'show/hide' }
}
})
const node = new InlineNsflNode([])
const html =
'<span class="up-nsfl up-revealable">'
+ '<label for="up-nsfl-1">show/hide</label>'
+ '<input id="up-nsfl-1" type="checkbox">'
+ '<span></span>'
+ '</span>'
expect(up.toHtml(node)).to.be.eql(html)
})
})
describe("The text in an inline NSFL convention's label", () => {
it("uses the provided term for 'toggleNsfl'", () => {
const up = new Up({
i18n: {
terms: { toggleNsfl: 'show/hide' }
}
})
const node = new NsflBlockNode([])
const html =
'<div class="up-nsfl up-revealable">'
+ '<label for="up-nsfl-1">show/hide</label>'
+ '<input id="up-nsfl-1" type="checkbox">'
+ '<div></div>'
+ '</div>'
expect(up.toHtml(node)).to.be.eql(html)
})
})
| Add passing NSFL block test | Add passing NSFL block test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,6 +1,7 @@
import { expect } from 'chai'
import Up from '../../../index'
import { InlineNsflNode } from '../../../SyntaxNodes/InlineNsflNode'
+import { NsflBlockNode } from '../../../SyntaxNodes/NsflBlockNode'
describe("The text in an inline NSFL convention's label", () => {
@@ -23,3 +24,25 @@
expect(up.toHtml(node)).to.be.eql(html)
})
})
+
+
+describe("The text in an inline NSFL convention's label", () => {
+ it("uses the provided term for 'toggleNsfl'", () => {
+ const up = new Up({
+ i18n: {
+ terms: { toggleNsfl: 'show/hide' }
+ }
+ })
+
+ const node = new NsflBlockNode([])
+
+ const html =
+ '<div class="up-nsfl up-revealable">'
+ + '<label for="up-nsfl-1">show/hide</label>'
+ + '<input id="up-nsfl-1" type="checkbox">'
+ + '<div></div>'
+ + '</div>'
+
+ expect(up.toHtml(node)).to.be.eql(html)
+ })
+}) |
b4f8277cb6503bd889654f0e4f364627e9e00af9 | client/src/assets/player/peertube-link-button.ts | client/src/assets/player/peertube-link-button.ts | import { VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
class PeerTubeLinkButton extends Button {
createEl () {
return this.buildElement()
}
updateHref () {
const currentTime = Math.floor(this.player().currentTime())
this.el().setAttribute('href', this.buildHref(currentTime))
}
handleClick () {
this.player_.pause()
}
private buildElement () {
const el = videojsUntyped.dom.createEl('a', {
href: this.buildHref(),
innerHTML: 'PeerTube',
title: 'Go to the video page',
className: 'vjs-peertube-link',
target: '_blank'
})
el.addEventListener('mouseenter', () => this.updateHref())
return el
}
private buildHref (time?: number) {
let href = window.location.href.replace('embed', 'watch')
if (time) href += '?start=' + time
return href
}
}
Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
| import { VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
class PeerTubeLinkButton extends Button {
createEl () {
return this.buildElement()
}
updateHref () {
const currentTime = Math.floor(this.player().currentTime())
this.el().setAttribute('href', this.buildHref(currentTime))
}
handleClick () {
this.player_.pause()
}
private buildElement () {
const el = videojsUntyped.dom.createEl('a', {
href: this.buildHref(),
innerHTML: 'PeerTube',
title: 'Go to the video page',
className: 'vjs-peertube-link',
target: '_blank'
})
el.addEventListener('mouseenter', () => this.updateHref())
return el
}
private buildHref (time?: number) {
let href = window.location.href.replace('embed', 'watch')
if (time) {
if (window.location.search) href += '&start=' + time
else href += '?start=' + time
}
return href
}
}
Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
| Fix resume video after peertube embed link click | Fix resume video after peertube embed link click
| TypeScript | agpl-3.0 | Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -32,7 +32,10 @@
private buildHref (time?: number) {
let href = window.location.href.replace('embed', 'watch')
- if (time) href += '?start=' + time
+ if (time) {
+ if (window.location.search) href += '&start=' + time
+ else href += '?start=' + time
+ }
return href
} |
c02aba3c52dd54e86be3859cb8938ffde12c0c24 | test/test_runner.ts | test/test_runner.ts | import * as fs from "fs";
import testRunner = require("vscode/lib/testrunner");
const onExit = require("signal-exit"); // tslint:disable-line:no-var-requires
// Ensure we write coverage on exit.
declare const __coverage__: any;
onExit(() => {
// Unhandled exceptions here seem to hang, but console.error+process.exit do not! ¯\_(ツ)_/¯
try {
if (typeof __coverage__ !== "undefined" && typeof process.env.COVERAGE_OUTPUT !== "undefined" && process.env.COVERAGE_OUTPUT) {
fs.writeFileSync(process.env.COVERAGE_OUTPUT, JSON.stringify(__coverage__));
}
} catch (e) {
console.error(e);
process.exit(1);
}
});
testRunner.configure({
reporter: "list",
slow: 1500, // increased threshold before marking a test as slow
timeout: 10000, // increased timeout because starting up Code, Analyzer, etc. is slooow
ui: "bdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true, // colored output from test results
});
module.exports = testRunner;
| import * as fs from "fs";
import testRunner = require("vscode/lib/testrunner");
const onExit = require("signal-exit"); // tslint:disable-line:no-var-requires
// Ensure we write coverage on exit.
declare const __coverage__: any;
onExit(() => {
// Unhandled exceptions here seem to hang, but console.error+process.exit do not! ¯\_(ツ)_/¯
try {
if (typeof __coverage__ !== "undefined" && typeof process.env.COVERAGE_OUTPUT !== "undefined" && process.env.COVERAGE_OUTPUT) {
fs.writeFileSync(process.env.COVERAGE_OUTPUT, JSON.stringify(__coverage__));
}
} catch (e) {
console.error(e);
process.exit(1);
}
});
testRunner.configure({
slow: 1500, // increased threshold before marking a test as slow
timeout: 10000, // increased timeout because starting up Code, Analyzer, etc. is slooow
ui: "bdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true, // colored output from test results
});
module.exports = testRunner;
| Remove list reported which is formatted worse but still has extra newlines | Remove list reported which is formatted worse but still has extra newlines
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -17,7 +17,6 @@
});
testRunner.configure({
- reporter: "list",
slow: 1500, // increased threshold before marking a test as slow
timeout: 10000, // increased timeout because starting up Code, Analyzer, etc. is slooow
ui: "bdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.) |
aff2e40d800399ecc64d073e3f0f8c290a5b128a | packages/game/src/lobby/containers/RemoteGameList.tsx | packages/game/src/lobby/containers/RemoteGameList.tsx | import * as React from 'react';
import { inject, observer } from 'mobx-react';
import { Text } from 'rebass';
import { RemoteGameComponent } from 'lobby/components/RemoteGameComponent';
import { RemoteGameStore } from 'lobby/stores/remotegame';
type RemoteGameListProps = {
remoteGameStore?: RemoteGameStore;
userId: string;
};
const RemoteGameListComponent: React.StatelessComponent<RemoteGameListProps> = ({ remoteGameStore, userId }) => (
<div>
{remoteGameStore.games.length == 0 ? (
<Text>No games found.</Text>
) : (
remoteGameStore.games.map((game) => <RemoteGameComponent key={game.gameId} game={game} userId={userId} />)
)}
</div>
);
export const RemoteGameList = inject('remoteGameStore')(observer(RemoteGameListComponent));
| import * as React from 'react';
import { inject, observer } from 'mobx-react';
import { Text } from 'rebass';
import { RemoteGameComponent } from 'lobby/components/RemoteGameComponent';
import { RemoteGameStore } from 'lobby/stores/remotegame';
type RemoteGameListProps = {
remoteGameStore?: RemoteGameStore;
userId: string;
};
const RemoteGameListComponent: React.StatelessComponent<RemoteGameListProps> = ({ remoteGameStore, userId }) => {
const gamesWithUser = remoteGameStore.games.filter((game) =>
game.leaderboard.map((leader) => leader.name).includes(userId)
);
return (
<div>
{gamesWithUser.length == 0 ? (
<Text>No games found.</Text>
) : (
gamesWithUser.map((game) => <RemoteGameComponent key={game.gameId} game={game} userId={userId} />)
)}
</div>
);
};
export const RemoteGameList = inject('remoteGameStore')(observer(RemoteGameListComponent));
| Add filtering by user to the remote games list | Add filtering by user to the remote games list
| TypeScript | mit | tomwwright/graph-battles,tomwwright/graph-battles,tomwwright/graph-battles | ---
+++
@@ -9,14 +9,20 @@
remoteGameStore?: RemoteGameStore;
userId: string;
};
-const RemoteGameListComponent: React.StatelessComponent<RemoteGameListProps> = ({ remoteGameStore, userId }) => (
- <div>
- {remoteGameStore.games.length == 0 ? (
- <Text>No games found.</Text>
- ) : (
- remoteGameStore.games.map((game) => <RemoteGameComponent key={game.gameId} game={game} userId={userId} />)
- )}
- </div>
-);
+const RemoteGameListComponent: React.StatelessComponent<RemoteGameListProps> = ({ remoteGameStore, userId }) => {
+ const gamesWithUser = remoteGameStore.games.filter((game) =>
+ game.leaderboard.map((leader) => leader.name).includes(userId)
+ );
+
+ return (
+ <div>
+ {gamesWithUser.length == 0 ? (
+ <Text>No games found.</Text>
+ ) : (
+ gamesWithUser.map((game) => <RemoteGameComponent key={game.gameId} game={game} userId={userId} />)
+ )}
+ </div>
+ );
+};
export const RemoteGameList = inject('remoteGameStore')(observer(RemoteGameListComponent)); |
3e3b468047dc8ebdfa46ec5a96341b1104a6f38e | transpilation/deploy.ts | transpilation/deploy.ts | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string) {
const result: any = exec(command);
return result.stdout;
}
const porcelain = cmd("git status --porcelain");
if (porcelain.trim()) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpile/deploy.ts", "dist/transpile/deploy.js" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
cmd("git rm -rf * --dry-run");
toDeploy.forEach(f => cmd(`git add cmd{f}`)); | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string) {
const result: any = exec(command);
return result.stdout;
}
const porcelain = cmd("git status --porcelain");
if (porcelain.trim()) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpile/deploy.ts", "dist/transpile/deploy.js" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
cmd("git rm -rf *");
toDeploy.forEach(f => cmd(`git add cmd{f}`));
console.log(cmd("git status")); | Check status after git rm -rf *. | Check status after git rm -rf *.
| TypeScript | mit | mmkal/slimejs,mmkal/slimejs,mmkal/slimejs,mmkal/slimejs | ---
+++
@@ -20,6 +20,8 @@
fs.writeFileSync(".gitignore", gitignore, "utf8");
-cmd("git rm -rf * --dry-run");
+cmd("git rm -rf *");
toDeploy.forEach(f => cmd(`git add cmd{f}`));
+
+console.log(cmd("git status")); |
f9527fc7e887912cc9f02efc1004e051ee1ff0d8 | gulpfile.ts | gulpfile.ts | /// <reference path="./typings/bundle.d.ts" />
import {task, src, dest, watch} from 'gulp';
import * as ts from 'gulp-typescript';
import * as tslint from 'gulp-tslint';
import * as babel from 'gulp-babel';
task('build', ['build:ts']);
function buildTypeScript(): ts.CompilationStream {
const project = ts.createProject('tsconfig.json', {
typescript: require('typescript')
});
return project.src().pipe(ts(project));
}
task('build:ts', () =>
buildTypeScript()
.pipe(babel())
.pipe(dest('./built'))
);
task('lint', () =>
src('./src/**/*.ts')
.pipe(tslint({
tslint: require('tslint')
}))
.pipe(tslint.report('verbose'))
);
task('test', ['build', 'lint']);
task('watch', ['build'], () =>
watch('./src/**/*.ts', ['build:ts'])
);
| /// <reference path="./typings/bundle.d.ts" />
import {task, src, dest, watch} from 'gulp';
import * as ts from 'gulp-typescript';
import * as tslint from 'gulp-tslint';
import * as babel from 'gulp-babel';
task('build', ['build:ts']);
const project = ts.createProject('tsconfig.json', {
typescript: require('typescript')
});
function buildTypeScript(): ts.CompilationStream {
return project.src().pipe(ts(project));
}
task('build:ts', () =>
buildTypeScript()
.pipe(babel())
.pipe(dest('./built'))
);
task('lint', () =>
src('./src/**/*.ts')
.pipe(tslint({
tslint: require('tslint')
}))
.pipe(tslint.report('verbose'))
);
task('test', ['build', 'lint']);
task('watch', ['build'], () =>
watch('./src/**/*.ts', ['build:ts'])
);
| Create project object before running tasks | Create project object before running tasks
| TypeScript | mit | MissKernel/Misskey-API,misskey-delta/Misskey-API,sirotama/misskey-api,sirotama/misskey-api,misskey-delta/Misskey-API | ---
+++
@@ -7,11 +7,11 @@
task('build', ['build:ts']);
+const project = ts.createProject('tsconfig.json', {
+ typescript: require('typescript')
+});
+
function buildTypeScript(): ts.CompilationStream {
- const project = ts.createProject('tsconfig.json', {
- typescript: require('typescript')
- });
-
return project.src().pipe(ts(project));
}
|
483393af7a5b68c76d7ef6502ee4e42029f3dbf9 | app/modal/simple-modal.ts | app/modal/simple-modal.ts | import { ComponentFactoryResolver, ComponentRef, ApplicationRef, Injectable, ReflectiveInjector,
Type, ViewContainerRef } from '@angular/core';
import { BaseModal } from './base-modal.component';
import { BaseModalConfig } from './base-modal-config';
@Injectable()
export class SimpleModal {
constructor(private app:ApplicationRef, private cfr:ComponentFactoryResolver) {
}
show(config:BaseModalConfig, modal:Type<BaseModal>) : Promise<string> {
// Top level hack
let vcr:ViewContainerRef = this.app['_rootComponents'][0]['_hostElement'].vcRef;
// Set up a promise to resolve when the modal is dismissed.
let resolve:(value?: string | PromiseLike<string>) => void;
let promise = new Promise<string>((res) => {
resolve = res;
});
let inj = ReflectiveInjector.resolveAndCreate([
{ provide: BaseModalConfig, useValue: config }], vcr.injector);
let comp = this.cfr.resolveComponentFactory(modal);
let cref:ComponentRef<any> = vcr.createComponent(comp, vcr.length, inj);
cref.instance.cref = cref;
cref.instance.resolver = resolve;
return promise;
}
}
| import { ComponentFactoryResolver, ComponentRef, ApplicationRef, Injectable, ReflectiveInjector,
Type, ViewContainerRef } from '@angular/core';
import { BaseModal } from './base-modal.component';
import { BaseModalConfig } from './base-modal-config';
@Injectable()
export class SimpleModal {
constructor(private app:ApplicationRef, private cfr:ComponentFactoryResolver) {
}
show(config:any, modal:Type<BaseModal>) : Promise<string> {
// Top level hack
let vcr:ViewContainerRef = this.app['_rootComponents'][0]['_hostElement'].vcRef;
// Set up a promise to resolve when the modal is dismissed.
let resolve:(value?: string | PromiseLike<string>) => void;
let promise = new Promise<string>((res) => {
resolve = res;
});
let inj:ReflectiveInjector;
if (config.constructor.name === 'BaseModalConfig') {
inj = ReflectiveInjector.resolveAndCreate([
{ provide: BaseModalConfig, useValue: config }], vcr.injector);
} else {
inj = ReflectiveInjector.resolveAndCreate([
{ provide: config.constructor, useValue: config }, { provide: BaseModalConfig, useValue: config }], vcr.injector);
}
let comp = this.cfr.resolveComponentFactory(modal);
let cref:ComponentRef<any> = vcr.createComponent(comp, vcr.length, inj);
cref.instance.cref = cref;
cref.instance.resolver = resolve;
return promise;
}
}
| Allow for extended modal configs | Allow for extended modal configs
| TypeScript | mit | czeckd/angular2-simple-modal,czeckd/angular-simple-modal,czeckd/angular2-simple-modal,czeckd/angular-simple-modal,czeckd/angular-simple-modal,czeckd/angular2-simple-modal | ---
+++
@@ -10,7 +10,7 @@
constructor(private app:ApplicationRef, private cfr:ComponentFactoryResolver) {
}
- show(config:BaseModalConfig, modal:Type<BaseModal>) : Promise<string> {
+ show(config:any, modal:Type<BaseModal>) : Promise<string> {
// Top level hack
let vcr:ViewContainerRef = this.app['_rootComponents'][0]['_hostElement'].vcRef;
@@ -19,8 +19,15 @@
let promise = new Promise<string>((res) => {
resolve = res;
});
- let inj = ReflectiveInjector.resolveAndCreate([
- { provide: BaseModalConfig, useValue: config }], vcr.injector);
+
+ let inj:ReflectiveInjector;
+ if (config.constructor.name === 'BaseModalConfig') {
+ inj = ReflectiveInjector.resolveAndCreate([
+ { provide: BaseModalConfig, useValue: config }], vcr.injector);
+ } else {
+ inj = ReflectiveInjector.resolveAndCreate([
+ { provide: config.constructor, useValue: config }, { provide: BaseModalConfig, useValue: config }], vcr.injector);
+ }
let comp = this.cfr.resolveComponentFactory(modal);
|
0b00e53ffab61b9cae063a79fe9af9a52f02134d | app/src/services/analytics.ts | app/src/services/analytics.ts | import { Component, Inject, Injector, bind } from 'angular2/angular2';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
@Component({
directives: [ ROUTER_DIRECTIVES ]
})
export class AnalyticsService {
//Set the analytics id of the page we want to send data
id : string = "UA-70134683-1";
constructor(public router: Router){
//we instantiate the google analytics service
window.ga('create', this.id, 'auto');
this.router.subscribe(this.onRouteChanged);
}
onRouteChanged(path){
//should we send more data?
window.ga('send', 'pageview', { 'page' : path});
}
//Manual send
send(type : string){
if (window.ga)
window.ga('send', type);
}
}
| import { Component, Inject, Injector, bind } from 'angular2/angular2';
import {Router, ROUTER_DIRECTIVES} from 'angular2/router';
@Component({
directives: [ ROUTER_DIRECTIVES ]
})
export class AnalyticsService {
//Set the analytics id of the page we want to send data
id : string = "UA-70134683-1";
constructor(public router: Router){
//we instantiate the google analytics service
window.ga('create', this.id, 'auto');
//We set the router to call onRouteChanged every time we change the page
this.router.subscribe(this.onRouteChanged);
}
onRouteChanged(path){
//should we send more data?
window.ga('send', 'pageview', { 'page' : path});
}
//Manual send.
static send(type : string){
if (window.ga)
window.ga('send', type);
}
}
| Set static to send method | Set static to send method
| TypeScript | agpl-3.0 | Minds/front,Minds/front,Minds/front,Minds/front | ---
+++
@@ -12,6 +12,8 @@
constructor(public router: Router){
//we instantiate the google analytics service
window.ga('create', this.id, 'auto');
+
+ //We set the router to call onRouteChanged every time we change the page
this.router.subscribe(this.onRouteChanged);
}
@@ -20,8 +22,8 @@
window.ga('send', 'pageview', { 'page' : path});
}
- //Manual send
- send(type : string){
+ //Manual send.
+ static send(type : string){
if (window.ga)
window.ga('send', type);
} |
3e56e89e380a92476375cf94d546c81ff65514dc | src/offering/routes.ts | src/offering/routes.ts | import { StateDeclaration } from '@waldur/core/types';
import { OfferingDetailsContainer } from './OfferingDetailsContainer';
export const states: StateDeclaration[] = [
{
name: 'offeringDetails',
url: '/offering/:uuid/',
component: OfferingDetailsContainer,
},
];
| import { StateDeclaration } from '@waldur/core/types';
import { OfferingDetailsContainer } from './OfferingDetailsContainer';
export const states: StateDeclaration[] = [
{
name: 'offeringDetails',
url: '/offering/:uuid/',
component: OfferingDetailsContainer,
data: {
sidebarKey: 'marketplace-project-resources',
},
},
];
| Expand resources sidebar menu for offerings. | Expand resources sidebar menu for offerings.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -7,5 +7,8 @@
name: 'offeringDetails',
url: '/offering/:uuid/',
component: OfferingDetailsContainer,
+ data: {
+ sidebarKey: 'marketplace-project-resources',
+ },
},
]; |
b7f0903385fadd673fb44c3a0ad529742b076d7e | client/test/Combatant.test.ts | client/test/Combatant.test.ts | import { StatBlock } from "../../common/StatBlock";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
beforeEach(() => {
InitializeSettings();
});
test("Should have its Max HP set from the statblock", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
}); | import { StatBlock } from "../../common/StatBlock";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
beforeEach(() => {
InitializeSettings();
});
test("Should have its Max HP set from the statblock", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
test("Should update its Max HP when its statblock is updated", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
expect(combatant.MaxHP).toBe(15);
});
}); | Test that combatant tracks statblock max HP | Test that combatant tracks statblock max HP
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -13,4 +13,12 @@
expect(combatant.MaxHP).toBe(10);
});
+
+ test("Should update its Max HP when its statblock is updated", () => {
+ const encounter = buildEncounter();
+ const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), Player: "player" });
+
+ combatant.StatBlock({ ...StatBlock.Default(), HP: { Value: 15, Notes: "" } });
+ expect(combatant.MaxHP).toBe(15);
+ });
}); |
e8a69fdc60b394b377c18f3c8aedcbd746a1b6e4 | dom/src/mockDOMSource.ts | dom/src/mockDOMSource.ts | import {Observable} from 'rx';
export interface DOMSelection {
observable: Observable<any>;
events: (eventType: string) => Observable<any>;
}
export class MockedDOMSelection {
public observable: Observable<any>;
constructor(private mockConfigEventTypes: Object,
mockConfigObservable?: Observable<any>) {
if (mockConfigObservable) {
this.observable = mockConfigObservable;
} else {
this.observable = Observable.empty();
}
}
public events(eventType: string) {
const mockConfigEventTypes = this.mockConfigEventTypes;
const keys = Object.keys(mockConfigEventTypes);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === eventType) {
return mockConfigEventTypes[key];
}
}
return Observable.empty();
}
}
export class MockedDOMSource {
constructor(private mockConfig: Object) {
}
public select(selector: string): DOMSelection {
const mockConfig = this.mockConfig;
const keys = Object.keys(mockConfig);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === selector) {
return new MockedDOMSelection(mockConfig[key], mockConfig['observable']);
}
}
return new MockedDOMSelection({}, mockConfig['observable']);
}
}
export function mockDOMSource(mockConfig: Object): MockedDOMSource {
return new MockedDOMSource(mockConfig);
}
| import {Observable} from 'rx';
export interface DOMSelection {
observable: Observable<any>;
events: (eventType: string) => Observable<any>;
}
export class MockedDOMSource {
public observable: Observable<any>;
constructor(private _mockConfig: Object) {
if (_mockConfig['observable']) {
this.observable = _mockConfig['observable'];
} else {
this.observable = Observable.empty();
}
}
public events(eventType: string) {
const mockConfig = this._mockConfig;
const keys = Object.keys(mockConfig);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === eventType) {
return mockConfig[key];
}
}
return Observable.empty();
}
public select(selector: string): DOMSelection {
const mockConfig = this._mockConfig;
const keys = Object.keys(mockConfig);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === selector) {
return new MockedDOMSource(mockConfig[key]);
}
}
return new MockedDOMSource({});
}
}
export function mockDOMSource(mockConfig: Object): MockedDOMSource {
return new MockedDOMSource(mockConfig);
}
| Fix some tests/issues with mocDOMSource | Fix some tests/issues with mocDOMSource
| TypeScript | mit | cyclejs/cyclejs,staltz/cycle,staltz/cycle,maskinoshita/cyclejs,cyclejs/cyclejs,ntilwalli/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,ntilwalli/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cycle-core,ntilwalli/cyclejs,usm4n/cyclejs,usm4n/cyclejs,cyclejs/cycle-core,cyclejs/cyclejs | ---
+++
@@ -5,47 +5,41 @@
events: (eventType: string) => Observable<any>;
}
-export class MockedDOMSelection {
+export class MockedDOMSource {
public observable: Observable<any>;
- constructor(private mockConfigEventTypes: Object,
- mockConfigObservable?: Observable<any>) {
- if (mockConfigObservable) {
- this.observable = mockConfigObservable;
+ constructor(private _mockConfig: Object) {
+ if (_mockConfig['observable']) {
+ this.observable = _mockConfig['observable'];
} else {
this.observable = Observable.empty();
}
}
public events(eventType: string) {
- const mockConfigEventTypes = this.mockConfigEventTypes;
- const keys = Object.keys(mockConfigEventTypes);
+ const mockConfig = this._mockConfig;
+ const keys = Object.keys(mockConfig);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === eventType) {
- return mockConfigEventTypes[key];
+ return mockConfig[key];
}
}
return Observable.empty();
}
-}
-
-export class MockedDOMSource {
- constructor(private mockConfig: Object) {
- }
public select(selector: string): DOMSelection {
- const mockConfig = this.mockConfig;
+ const mockConfig = this._mockConfig;
const keys = Object.keys(mockConfig);
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
if (key === selector) {
- return new MockedDOMSelection(mockConfig[key], mockConfig['observable']);
+ return new MockedDOMSource(mockConfig[key]);
}
}
- return new MockedDOMSelection({}, mockConfig['observable']);
+ return new MockedDOMSource({});
}
}
|
cb94bbd1deffa90f4795b2a11fd3278be70ff5f8 | src/web/controllers/dev.ts | src/web/controllers/dev.ts | /// <reference path="../../../typings/bundle.d.ts" />
import async = require('async');
import Application = require('../../models/application');
import conf = require('../../config');
export = render;
var render = (req: any, res: any): void => {
async.series([
(callback: any) => {
if (req.login) {
Application.findByUserId(req.me.id, (apps: Application[]) => {
callback(null, apps);
});
} else {
callback(null, null);
}
}],
(err: any, results: any) => {
res.display(req, res, 'dev', {
apps: results[0],
});
});
};
| /// <reference path="../../../typings/bundle.d.ts" />
import async = require('async');
import Application = require('../../models/application');
import conf = require('../../config');
export = render;
var render = (req: any, res: any): void => {
async.series([
(callback: any) => {
if (req.login) {
Application.findByUserId(req.me.id, (apps: Application[]) => {
callback(null, apps);
});
} else {
callback(null, []);
}
}],
(err: any, results: any) => {
res.display(req, res, 'dev', {
apps: results[0],
});
});
};
| Fix to return array on time of non-login. | Fix to return array on time of non-login.
| TypeScript | mit | sirotama/Misskey,sirotama/Misskey | ---
+++
@@ -15,7 +15,7 @@
callback(null, apps);
});
} else {
- callback(null, null);
+ callback(null, []);
}
}],
(err: any, results: any) => { |
24dd0b1d26c316852cd3f645f7bd394ffe0f3734 | applications/play/pages/index.ts | applications/play/pages/index.ts | // @flow
import * as React from "react";
import { connect } from "react-redux";
import Main from "../components/Main";
import { actions } from "../redux";
function detectPlatform(req) {
if (req && req.headers) {
// Server side
const userAgent = req.headers["user-agent"];
if (/Windows/.test(userAgent)) {
return "Windows";
} else if (/Linux/.test(userAgent)) {
return "Linux";
}
// Client side
} else if (navigator.platform) {
if (/Win/.test(navigator.platform)) {
return "Windows";
} else if (/Linux/.test(navigator.platform)) {
return "Linux";
}
}
// Else keep macOS default
return "macOS";
}
class Page extends React.Component<*, *> {
static async getInitialProps({ req, store, query }) {
// Note that we cannot dispatch async actions in getInitialProps since it's
// being handled server side. If we _need_ to do that, we should refactor
// the related epics so that we can either (a) await them in some way or (b)
// manually fetch the things we need and only dispatch the final,
// synchronous actions.
store.dispatch(actions.setPlatform(detectPlatform(req)));
store.dispatch(actions.initalizeFromQuery(query));
}
render() {
return <Main />;
}
}
export default connect()(Page);
| import * as React from "react";
import { connect } from "react-redux";
import Main from "../components/Main";
import { actions } from "../redux";
function detectPlatform(req) {
if (req && req.headers) {
// Server side
const userAgent = req.headers["user-agent"];
if (/Windows/.test(userAgent)) {
return "Windows";
} else if (/Linux/.test(userAgent)) {
return "Linux";
}
// Client side
} else if (navigator.platform) {
if (/Win/.test(navigator.platform)) {
return "Windows";
} else if (/Linux/.test(navigator.platform)) {
return "Linux";
}
}
// Else keep macOS default
return "macOS";
}
class Page extends React.Component {
static async getInitialProps({ req, store, query }) {
// Note that we cannot dispatch async actions in getInitialProps since it's
// being handled server side. If we _need_ to do that, we should refactor
// the related epics so that we can either (a) await them in some way or (b)
// manually fetch the things we need and only dispatch the final,
// synchronous actions.
store.dispatch(actions.setPlatform(detectPlatform(req)));
store.dispatch(actions.initalizeFromQuery(query));
}
render() {
return <Main />;
}
}
export default connect()(Page);
| Rename files to use TypeScript extension | Rename files to use TypeScript extension
| TypeScript | bsd-3-clause | nteract/composition,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract | ---
+++
@@ -1,4 +1,3 @@
-// @flow
import * as React from "react";
import { connect } from "react-redux";
@@ -26,7 +25,7 @@
return "macOS";
}
-class Page extends React.Component<*, *> {
+class Page extends React.Component {
static async getInitialProps({ req, store, query }) {
// Note that we cannot dispatch async actions in getInitialProps since it's
// being handled server side. If we _need_ to do that, we should refactor |
ed0070c470b9371378501a47c8cf304bf796c4da | src/queue/processors/object-storage/index.ts | src/queue/processors/object-storage/index.ts | import * as Bull from 'bull';
import deleteFile from './delete-file';
const jobs = {
deleteFile,
} as any;
export default function(q: Bull.Queue) {
for (const [k, v] of Object.entries(jobs)) {
q.process(k, v as any);
}
}
| import * as Bull from 'bull';
import deleteFile from './delete-file';
const jobs = {
deleteFile,
} as any;
export default function(q: Bull.Queue) {
for (const [k, v] of Object.entries(jobs)) {
q.process(k, 16, v as any);
}
}
| Set job concurrency to reduce performance issue | Set job concurrency to reduce performance issue
| TypeScript | mit | syuilo/Misskey,syuilo/Misskey | ---
+++
@@ -7,6 +7,6 @@
export default function(q: Bull.Queue) {
for (const [k, v] of Object.entries(jobs)) {
- q.process(k, v as any);
+ q.process(k, 16, v as any);
}
} |
54233ee9f61917909662062baa5bf13d31c0696d | src/app/states/devices/usb/abstract-usb-device.ts | src/app/states/devices/usb/abstract-usb-device.ts | import { AbstractDevice } from '../abstract-device';
export abstract class AbstractUSBDevice extends AbstractDevice {
abstract readonly pid: string;
abstract readonly vid: string;
readonly driver = 'CdcAcmSerialDriver';
abstract readonly baudRate: number;
abstract readonly dataBits: number;
}
| import { AbstractDevice } from '../abstract-device';
export abstract class AbstractUSBDevice extends AbstractDevice {
abstract readonly pid: string;
abstract readonly vid: string;
readonly driver: string = 'CdcAcmSerialDriver';
abstract readonly baudRate: number;
abstract readonly dataBits: number;
}
| Fix the impossibility to override usb device driver | Fix the impossibility to override usb device driver
| TypeScript | apache-2.0 | openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile | ---
+++
@@ -3,7 +3,7 @@
export abstract class AbstractUSBDevice extends AbstractDevice {
abstract readonly pid: string;
abstract readonly vid: string;
- readonly driver = 'CdcAcmSerialDriver';
+ readonly driver: string = 'CdcAcmSerialDriver';
abstract readonly baudRate: number;
abstract readonly dataBits: number;
} |
380bd7a7a892e8bb33c9afbf8dc5b4e7d3ae6c7e | src/routes/push.ts | src/routes/push.ts | import firebaseAdmin from 'firebase-admin';
import express from 'express';
import PushService from '../services/PushService';
const router: express.Router = express.Router();
const pushService: PushService = new PushService();
router.post('/', (req, res) => {
const push: firebaseAdmin.messaging.Message = {
token: req.body.token,
data: req.body.data,
notification: req.body.notification,
android: req.body.android,
webpush: req.body.webpush,
apns: req.body.apns
};
pushService.send(req.body.platformId, push)
.then((response: any) => {
console.log(response);
})
.catch((e: Error) => {
console.log('Error: ' + e);
});
res.send('Push queued.');
});
export default router;
| import { messaging as firebaseMessaging } from 'firebase-admin';
import express from 'express';
import PushService from '../services/PushService';
const router: express.Router = express.Router();
const pushService: PushService = new PushService();
router.post('/', (req, res) => {
const push: firebaseMessaging.Message = {
token: req.body.token,
data: req.body.data,
notification: req.body.notification,
android: req.body.android,
webpush: req.body.webpush,
apns: req.body.apns
};
pushService.send(req.body.platformId, push)
.then((response: any) => {
console.log(response);
})
.catch((e: Error) => {
console.log('Error: ' + e);
});
res.send('Push queued.');
});
export default router;
| Use same import for Firebase Messaging as in other files | Use same import for Firebase Messaging as in other files
| TypeScript | mit | schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service | ---
+++
@@ -1,4 +1,4 @@
-import firebaseAdmin from 'firebase-admin';
+import { messaging as firebaseMessaging } from 'firebase-admin';
import express from 'express';
import PushService from '../services/PushService';
@@ -6,7 +6,7 @@
const pushService: PushService = new PushService();
router.post('/', (req, res) => {
- const push: firebaseAdmin.messaging.Message = {
+ const push: firebaseMessaging.Message = {
token: req.body.token,
data: req.body.data,
notification: req.body.notification, |
c035dab94b1a7e6cd5f3a6024a3d435bebb026ae | tests/button/Button.tsx | tests/button/Button.tsx | import * as React from 'react';
export class Button extends React.Component {
render() {
return (
<div className="button">{this.props.children}</div>
);
}
}
export class BadButton extends React.Component {
render() {
`
`;
if (1 == 1) throw new Error('Error in Bad button');
return (
<div className="bad-button">{this.props.children}</div>
);
}
}
| import * as React from 'react';
// This interface has been put here just so that the line
// numbers in the transpiled javascript file are different.
interface ButtonProps {
someProp: any;
};
export class Button extends React.Component {
render() {
return (
<div className="button">{this.props.children}</div>
);
}
}
export class BadButton extends React.Component {
render() {
`
`;
if (1 == 1) throw new Error('Error in Bad button');
return (
<div className="bad-button">{this.props.children}</div>
);
}
}
| Add a placeholder interface in a test file | Add a placeholder interface in a test file
| TypeScript | mit | kulshekhar/ts-jest,kulshekhar/ts-jest | ---
+++
@@ -1,4 +1,10 @@
import * as React from 'react';
+
+// This interface has been put here just so that the line
+// numbers in the transpiled javascript file are different.
+interface ButtonProps {
+ someProp: any;
+};
export class Button extends React.Component {
render() { |
a0d258fbcd93623cfd8983578b1d97e049ccce9c | web/e2e/app.e2e-spec.ts | web/e2e/app.e2e-spec.ts | import { browser, ExpectedConditions, promise } from 'protractor';
import { Create, Ladder } from './app.po';
describe('base flow', () => {
const ladder: Ladder = new Ladder();
const create: Create = new Create();
const oneSecond = 1000;
it('should create a ladder with default settings', () => {
create.navigateTo();
create.setParameter('name', 'foo');
create.submit();
browser.wait(ExpectedConditions.urlContains('foo'), oneSecond);
});
it('should make a simple transitive ranking', () => {
ladder.navigateTo('foo');
ladder.reportDuel('x', 'y');
ladder.reportDuel('y', 'z');
const scorePromises = [
ladder.getScore('x'),
ladder.getScore('y'),
ladder.getScore('z'),
];
promise.all(scorePromises).then((scores) => {
expect(scores[0]).toBeGreaterThan(scores[1]);
expect(scores[1]).toBeGreaterThan(scores[2]);
});
});
});
| import { browser, ExpectedConditions, promise } from 'protractor';
import { Create, Ladder } from './app.po';
describe('base flow', () => {
const ladder: Ladder = new Ladder();
const create: Create = new Create();
const oneSecond = 1000;
it('should create a ladder with default settings', () => {
create.navigateTo();
create.setParameter('name', 'foo');
create.submit();
browser.wait(ExpectedConditions.urlContains('foo'), 5 * oneSecond);
});
it('should make a simple transitive ranking', () => {
ladder.navigateTo('foo');
ladder.reportDuel('x', 'y');
ladder.reportDuel('y', 'z');
const scorePromises = [
ladder.getScore('x'),
ladder.getScore('y'),
ladder.getScore('z'),
];
promise.all(scorePromises).then((scores) => {
expect(scores[0]).toBeGreaterThan(scores[1]);
expect(scores[1]).toBeGreaterThan(scores[2]);
});
});
});
| Allow more time for ladder creation in e2e test (timed out on Travis). | Allow more time for ladder creation in e2e test (timed out on Travis).
| TypeScript | mit | lrem/ladders,lrem/ladders,lrem/ladders,lrem/ladders,lrem/ladders | ---
+++
@@ -10,7 +10,7 @@
create.navigateTo();
create.setParameter('name', 'foo');
create.submit();
- browser.wait(ExpectedConditions.urlContains('foo'), oneSecond);
+ browser.wait(ExpectedConditions.urlContains('foo'), 5 * oneSecond);
});
it('should make a simple transitive ranking', () => { |
a4fe145370f39657743db0f8ad0f4cee353aa7e8 | modules/account-lib/src/coin/celo/resources.ts | modules/account-lib/src/coin/celo/resources.ts | import EthereumCommon from 'ethereumjs-common';
/**
* A Common object defining the chain and the hardfork for CELO Testnet
*/
export const testnetCommon = EthereumCommon.forCustomChain(
'mainnet', // It's a test net based on the main ethereum net
{
name: 'alfajores',
networkId: 44786,
chainId: 44786,
},
'petersburg',
);
/**
* A Common object defining the chain and the hardfork for CELO Mainnet
*/
export const mainnetCommon = EthereumCommon.forCustomChain(
'mainnet',
{
name: 'rc1',
networkId: 42220,
chainId: 42220,
},
'petersburg',
);
| import EthereumCommon from 'ethereumjs-common';
/**
* A Common object defining the chain and the hardfork for CELO Testnet
*/
export const testnetCommon = EthereumCommon.forCustomChain(
'mainnet', // It's a test net based on the main ethereum net
{
name: 'alfajores',
networkId: 44787,
chainId: 44787,
},
'petersburg',
);
/**
* A Common object defining the chain and the hardfork for CELO Mainnet
*/
export const mainnetCommon = EthereumCommon.forCustomChain(
'mainnet',
{
name: 'rc1',
networkId: 42220,
chainId: 42220,
},
'petersburg',
);
| Update CELO network/chainId Ticket: BG-24642 | Update CELO network/chainId
Ticket: BG-24642
| TypeScript | apache-2.0 | BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS | ---
+++
@@ -7,8 +7,8 @@
'mainnet', // It's a test net based on the main ethereum net
{
name: 'alfajores',
- networkId: 44786,
- chainId: 44786,
+ networkId: 44787,
+ chainId: 44787,
},
'petersburg',
); |
ee0c6428bc8a8cc95c0bad9b2cf3506019fb4d90 | app/test/replay-steps.ts | app/test/replay-steps.ts | // rx streams require events to be replayed over time to make any sense.
export default function replaySteps(steps: any[], timeoutMax: number = 90) {
if (steps.length > 0) {
let head = steps[0];
let headArg = undefined;
let remaining = steps.slice(1);
let timeout = Math.ceil(Math.random() * timeoutMax) + 10;
if (typeof head === 'number') {
timeout = head;
head = remaining[0];
remaining = remaining.slice(1);
} else if (typeof head !== 'function') {
let forObj = head;
timeout = forObj.wait || timeout;
if (forObj.for.length > 1) {
remaining = [{
for: forObj.for.slice(1),
wait: forObj.wait,
fn: forObj.fn
}].concat(remaining);
}
head = forObj.fn;
headArg = forObj.for[0];
}
setTimeout(() => {
head(headArg);
replaySteps(remaining);
}, timeout);
}
return;
}
| // rx streams require events to be replayed over time to make any sense.
export default function replaySteps(steps: any[], timeoutMax: number = 100, timeoutMin: number = 10) {
if (steps.length > 0) {
let head = steps[0];
let headArg = undefined;
let remaining = steps.slice(1);
let timeout = Math.random() * timeoutMax + timeoutMin;
if (typeof head === 'number') {
timeout = head;
head = remaining[0];
remaining = remaining.slice(1);
} else if (typeof head !== 'function') {
let forObj = head;
timeout = forObj.wait || timeout;
if (forObj.for.length > 1) {
remaining = [{
for: forObj.for.slice(1),
wait: forObj.wait,
fn: forObj.fn
}].concat(remaining);
}
head = forObj.fn;
headArg = forObj.for[0];
}
setTimeout(() => {
head(headArg);
replaySteps(remaining, timeoutMax, timeoutMin);
}, timeout);
}
return;
}
| Allow passing min timeout to replaySteps | Allow passing min timeout to replaySteps
| TypeScript | mit | stofte/linq-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor,stofte/ream-editor | ---
+++
@@ -1,10 +1,10 @@
// rx streams require events to be replayed over time to make any sense.
-export default function replaySteps(steps: any[], timeoutMax: number = 90) {
+export default function replaySteps(steps: any[], timeoutMax: number = 100, timeoutMin: number = 10) {
if (steps.length > 0) {
let head = steps[0];
let headArg = undefined;
let remaining = steps.slice(1);
- let timeout = Math.ceil(Math.random() * timeoutMax) + 10;
+ let timeout = Math.random() * timeoutMax + timeoutMin;
if (typeof head === 'number') {
timeout = head;
head = remaining[0];
@@ -24,7 +24,7 @@
}
setTimeout(() => {
head(headArg);
- replaySteps(remaining);
+ replaySteps(remaining, timeoutMax, timeoutMin);
}, timeout);
}
return; |
a1091a424f26f58b46a03a9e263abc711509150e | lib/core-common/src/utils/normalize-stories.ts | lib/core-common/src/utils/normalize-stories.ts | import fs from 'fs';
import { resolve } from 'path';
import type { StoriesEntry, NormalizedStoriesEntry } from '../types';
const DEFAULT_FILES = '*.stories.@(mdx|tsx|ts|jsx|js)';
const DEFAULT_TITLE_PREFIX = '';
export const normalizeStoriesEntry = (
entry: StoriesEntry,
configDir: string
): NormalizedStoriesEntry => {
let glob;
let directory;
let files;
let titlePrefix;
if (typeof entry === 'string') {
if (!entry.includes('**') && fs.lstatSync(resolve(configDir, entry)).isDirectory()) {
directory = entry;
titlePrefix = DEFAULT_TITLE_PREFIX;
files = DEFAULT_FILES;
} else {
glob = entry;
}
} else {
directory = entry.directory;
files = entry.files || DEFAULT_FILES;
titlePrefix = entry.titlePrefix || DEFAULT_TITLE_PREFIX;
}
if (typeof glob !== 'undefined') {
return { glob, specifier: undefined };
}
return { glob: `${directory}/**/${files}`, specifier: { directory, titlePrefix, files } };
};
export const normalizeStories = (entries: StoriesEntry[], configDir: string) =>
entries.map((entry) => normalizeStoriesEntry(entry, configDir));
| import fs from 'fs';
import { resolve } from 'path';
import type { StoriesEntry, NormalizedStoriesEntry } from '../types';
const DEFAULT_FILES = '*.stories.@(mdx|tsx|ts|jsx|js)';
const DEFAULT_TITLE_PREFIX = '';
const isDirectory = (configDir: string, entry: string) => {
try {
return fs.lstatSync(resolve(configDir, entry)).isDirectory();
} catch (err) {
return false;
}
};
export const normalizeStoriesEntry = (
entry: StoriesEntry,
configDir: string
): NormalizedStoriesEntry => {
let glob;
let directory;
let files;
let titlePrefix;
if (typeof entry === 'string') {
if (!entry.includes('**') && isDirectory(configDir, entry)) {
directory = entry;
titlePrefix = DEFAULT_TITLE_PREFIX;
files = DEFAULT_FILES;
} else {
glob = entry;
}
} else {
directory = entry.directory;
files = entry.files || DEFAULT_FILES;
titlePrefix = entry.titlePrefix || DEFAULT_TITLE_PREFIX;
}
if (typeof glob !== 'undefined') {
return { glob, specifier: undefined };
}
return { glob: `${directory}/**/${files}`, specifier: { directory, titlePrefix, files } };
};
export const normalizeStories = (entries: StoriesEntry[], configDir: string) =>
entries.map((entry) => normalizeStoriesEntry(entry, configDir));
| Fix auto-title generation for stories entries that are not globs and not files | Core: Fix auto-title generation for stories entries that are not globs and not files
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -4,6 +4,14 @@
const DEFAULT_FILES = '*.stories.@(mdx|tsx|ts|jsx|js)';
const DEFAULT_TITLE_PREFIX = '';
+
+const isDirectory = (configDir: string, entry: string) => {
+ try {
+ return fs.lstatSync(resolve(configDir, entry)).isDirectory();
+ } catch (err) {
+ return false;
+ }
+};
export const normalizeStoriesEntry = (
entry: StoriesEntry,
@@ -14,7 +22,7 @@
let files;
let titlePrefix;
if (typeof entry === 'string') {
- if (!entry.includes('**') && fs.lstatSync(resolve(configDir, entry)).isDirectory()) {
+ if (!entry.includes('**') && isDirectory(configDir, entry)) {
directory = entry;
titlePrefix = DEFAULT_TITLE_PREFIX;
files = DEFAULT_FILES; |
65d791cccddc7b6bb6d1e8b439a808d02d7bc27f | src/datastore/postgres/schema/v5.ts | src/datastore/postgres/schema/v5.ts | import { IDatabase } from "pg-promise";
// tslint:disable-next-line: no-any
export async function runSchema(db: IDatabase<any>) {
// Create schema
await db.none(`
CREATE TABLE metrics_activities (
user_id TEXT NOT NULL,
room_id TEXT NOT NULL,
date DATE,
CONSTRAINT cons_activities_unique UNIQUE(user_id, room_id, date),
CONSTRAINT cons_activities_user FOREIGN KEY(user_id) REFERENCES users(userid),
CONSTRAINT cons_activities_room FOREIGN KEY(room_id) REFERENCES rooms(id)
);
`);
}
| import { IDatabase } from "pg-promise";
// tslint:disable-next-line: no-any
export async function runSchema(db: IDatabase<any>) {
// Create schema
await db.none(`
CREATE TABLE metrics_activities (
user_id TEXT NOT NULL,
room_id TEXT NOT NULL,
date DATE,
CONSTRAINT cons_activities_unique UNIQUE(user_id, room_id, date)
);
`);
}
| Remove foreign key contraints from the database | Remove foreign key contraints from the database | TypeScript | apache-2.0 | matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack | ---
+++
@@ -8,9 +8,7 @@
user_id TEXT NOT NULL,
room_id TEXT NOT NULL,
date DATE,
- CONSTRAINT cons_activities_unique UNIQUE(user_id, room_id, date),
- CONSTRAINT cons_activities_user FOREIGN KEY(user_id) REFERENCES users(userid),
- CONSTRAINT cons_activities_room FOREIGN KEY(room_id) REFERENCES rooms(id)
+ CONSTRAINT cons_activities_unique UNIQUE(user_id, room_id, date)
);
`);
} |
167375ea0a79ed883adf761032e67eb1941555f2 | src/test.ts | src/test.ts | import Course from './Course';
import { generateCourses } from './CourseGenerator';
import { parseCourses } from './CourseParser';
for (let i = 0; i < 100; i++) {
const sample = [...generateCourses(5)];
const parsedCourses = parseCourses(sample);
const possibleCombinations = Course.possibleSectionCombinations(parsedCourses);
if (possibleCombinations.size > 0) {
console.log(JSON.stringify(sample));
possibleCombinations.forEach((combination) => {
combination.forEach((section, course) => {
console.log(`${course.code} -> ${section.identifier}`);
});
});
console.log(`Iteration ${i}`);
break;
}
} | import { generateCourses, parseCourses, Course } from './main';
for (let i = 0; i < 100; i++) {
const sample = [...generateCourses(5)];
const parsedCourses = parseCourses(sample);
const possibleCombinations = Course.possibleSectionCombinations(parsedCourses);
if (possibleCombinations.size > 0) {
console.log(JSON.stringify(sample));
possibleCombinations.forEach((combination) => {
combination.forEach((section, course) => {
console.log(`${course.code} -> ${section.identifier}`);
});
});
console.log(`Iteration ${i}`);
break;
}
} | Use imports from main file | Use imports from main file
| TypeScript | unlicense | rizadh/scheduler | ---
+++
@@ -1,6 +1,4 @@
-import Course from './Course';
-import { generateCourses } from './CourseGenerator';
-import { parseCourses } from './CourseParser';
+import { generateCourses, parseCourses, Course } from './main';
for (let i = 0; i < 100; i++) {
const sample = [...generateCourses(5)]; |
3cd2b3c994752706d1e24634a1ac332d6960891b | src/index.ts | src/index.ts | import { setup as bemClassNameSetup, BemSettings } from 'bem-cn';
interface Modifications {
[name: string]: string | boolean | undefined;
}
let block = bemClassNameSetup();
function bemClassNameLite(blockName: string) {
const b = block(blockName);
function element(elementName: string, modifiers: Modifications | null, mixin?: string): string;
function element(elementName: string, mixin?: string): string;
function element(elementName: string, modifiers: Modifications): string;
function element(mods: Modifications | null, mixin?: string): string;
function element(elementName: string): string;
function element(mods: Modifications | null): string;
function element(): string;
function element(...args: any) {
const elementName = args.shift();
let [modifiers, mixin] = args;
let result;
if (typeof elementName !== 'string' || typeof modifiers === 'string') {
mixin = modifiers;
modifiers = null;
}
result = b(elementName, modifiers);
if (mixin) {
result = result.mix(mixin);
}
return result.toString();
}
element.builder = function () {
return b;
};
return element;
}
bemClassNameLite.setup = function (config: BemSettings) {
block = bemClassNameSetup(config);
};
bemClassNameLite.reset = function () {
block = bemClassNameSetup();
};
export default bemClassNameLite;
| import { setup as bemClassNameSetup, BemSettings } from 'bem-cn';
interface Modifications {
[name: string]: string | boolean | undefined;
}
let block = bemClassNameSetup();
function isString(data: any) {
return typeof data === 'string';
}
function hasMixinShape(data: any) {
return isString(data) || (Array.isArray(data) && data.every(isString));
}
function bemClassNameLite(blockName: string) {
const b = block(blockName);
function element(elementName: string, modifiers: Modifications | null, mixin?: string | string[]): string;
function element(elementName: string, mixin?: string | string[]): string;
function element(elementName: string, modifiers: Modifications): string;
function element(mods: Modifications | null, mixin?: string | string[]): string;
function element(elementName: string): string;
function element(mods: Modifications | null): string;
function element(): string;
function element(...args: any) {
const elementName = args.shift();
let [modifiers, mixin] = args;
let result;
if (typeof elementName !== 'string' || hasMixinShape(modifiers)) {
mixin = modifiers;
modifiers = null;
}
result = b(elementName, modifiers);
if (mixin) {
result = result.mix(mixin);
}
return result.toString();
}
element.builder = function () {
return b;
};
return element;
}
bemClassNameLite.setup = function (config: BemSettings) {
block = bemClassNameSetup(config);
};
bemClassNameLite.reset = function () {
block = bemClassNameSetup();
};
export default bemClassNameLite;
| Add support for multiple mixins | Add support for multiple mixins | TypeScript | mit | mistakster/bem-cn-lite,mistakster/bem-cn-lite | ---
+++
@@ -6,23 +6,32 @@
let block = bemClassNameSetup();
+function isString(data: any) {
+ return typeof data === 'string';
+}
+
+function hasMixinShape(data: any) {
+ return isString(data) || (Array.isArray(data) && data.every(isString));
+}
+
+
function bemClassNameLite(blockName: string) {
const b = block(blockName);
- function element(elementName: string, modifiers: Modifications | null, mixin?: string): string;
- function element(elementName: string, mixin?: string): string;
+ function element(elementName: string, modifiers: Modifications | null, mixin?: string | string[]): string;
+ function element(elementName: string, mixin?: string | string[]): string;
function element(elementName: string, modifiers: Modifications): string;
- function element(mods: Modifications | null, mixin?: string): string;
+ function element(mods: Modifications | null, mixin?: string | string[]): string;
function element(elementName: string): string;
function element(mods: Modifications | null): string;
function element(): string;
-
+
function element(...args: any) {
const elementName = args.shift();
let [modifiers, mixin] = args;
let result;
- if (typeof elementName !== 'string' || typeof modifiers === 'string') {
+ if (typeof elementName !== 'string' || hasMixinShape(modifiers)) {
mixin = modifiers;
modifiers = null;
} |
66e4cf764b697b018e03a664b5c980c9f795432c | APM-Final/src/app/products/product-detail.guard.ts | APM-Final/src/app/products/product-detail.guard.ts | import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProductDetailGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const id = +next.url[1].path;
if (isNaN(id) || id < 1) {
alert('Invalid product Id');
this.router.navigate(['/products']);
return false;
}
return true;
}
}
| import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProductDetailGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const id = +next.url[1].path;
// const id2 = next.paramMap.get('id');
// console.log(id2);
if (isNaN(id) || id < 1) {
alert('Invalid product Id');
this.router.navigate(['/products']);
return false;
}
return true;
}
}
| Add altternate syntax to read the URL from the route. | Add altternate syntax to read the URL from the route.
| TypeScript | mit | DeborahK/Angular2-GettingStarted,DeborahK/Angular2-GettingStarted,DeborahK/Angular2-APM,DeborahK/Angular2-GettingStarted,DeborahK/Angular2-APM | ---
+++
@@ -13,6 +13,8 @@
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const id = +next.url[1].path;
+ // const id2 = next.paramMap.get('id');
+ // console.log(id2);
if (isNaN(id) || id < 1) {
alert('Invalid product Id');
this.router.navigate(['/products']); |
e8b61c713cdbff32fc05b2da2873aad20532cb14 | src/index.ts | src/index.ts | export * from "./interface";
import {GinBuilder} from "./builder";
export {GinBuilder} from "./builder";
export * from "./enum";
export * from "./filter";
export const gindownloader = new GinBuilder();
| export * from "./interface";
import {GinBuilder} from "./builder";
export {GinBuilder, MangaHereBuilder} from "./builder";
export * from "./enum";
export * from "./filter";
export * from "./parser";
export const gindownloader = new GinBuilder();
export {MangaHereConfig} from "./manga/mangahere/config";
export {RequestRetryStrategy} from "./strategies/retry_strategy";
export {MangaHereParser} from "./manga/mangahere/parser";
export {mangahereLogger} from "./manga/mangahere/logger";
export {MangaHereGenre} from "./manga/mangahere/genre";
export {MangaRequestResult} from "./util/mangaRequestResult";
export {RetryRequestFactory} from "./factories/retryRequest";
| Add 'Hajime-chan is No. 1' to the invalid list | Add 'Hajime-chan is No. 1' to the invalid list
| TypeScript | mit | pikax/gin-downloader,pikax/gin-downloader | ---
+++
@@ -1,10 +1,22 @@
export * from "./interface";
import {GinBuilder} from "./builder";
-export {GinBuilder} from "./builder";
+export {GinBuilder, MangaHereBuilder} from "./builder";
export * from "./enum";
export * from "./filter";
+export * from "./parser";
+
export const gindownloader = new GinBuilder();
+
+
+
+export {MangaHereConfig} from "./manga/mangahere/config";
+export {RequestRetryStrategy} from "./strategies/retry_strategy";
+export {MangaHereParser} from "./manga/mangahere/parser";
+export {mangahereLogger} from "./manga/mangahere/logger";
+export {MangaHereGenre} from "./manga/mangahere/genre";
+export {MangaRequestResult} from "./util/mangaRequestResult";
+export {RetryRequestFactory} from "./factories/retryRequest"; |
adb346364f6fb65e8da58149c1c2280ea99528d7 | src/index.ts | src/index.ts | #!/usr/bin/env node
console.log("vim-js-alternate: initialized");
import ProjectionLoader from "./ProjectionLoader";
import { ProjectionResolver } from "./ProjectionResolver";
var Vim = require("vim-node-driver");
var vim = new Vim();
var projectionLoader = new ProjectionLoader();
var projectionResolver = new ProjectionResolver(projectionLoader);
var currentBuffer;
var currentAlternateFile = null;
var alternateCache = {};
vim.on("BufEnter", (args) => {
currentBuffer = args.currentBuffer;
if(currentBuffer) {
currentAlternateFile = projectionResolver.getAlternate(currentBuffer);
console.log("Resolving projection for: " + currentBuffer + " | " + projectionResolver.getAlternate(currentBuffer));
}
});
vim.addCommand("Alternate", () => {
var alternateFile = currentAlternateFile;
// If not resolved, try the cache
if(!alternateFile)
alternateFile = alternateCache[currentBuffer];
if(alternateFile) {
// Store a reverse mapping so we can jump back easily
alternateCache[alternateFile] = currentBuffer;
vim.exec("edit " + alternateFile)
}
});
console.log("command registered")
| declare var vim;
console.log("vim-js-alternate: initialized");
import ProjectionLoader from "./ProjectionLoader";
import { ProjectionResolver } from "./ProjectionResolver";
var projectionLoader = new ProjectionLoader();
var projectionResolver = new ProjectionResolver(projectionLoader);
var currentBuffer;
var currentAlternateFile = null;
var alternateCache = {};
vim.on("BufEnter", (args) => {
currentBuffer = args.currentBuffer;
if(currentBuffer) {
currentAlternateFile = projectionResolver.getAlternate(currentBuffer);
console.log("Resolving projection for: " + currentBuffer + " | " + projectionResolver.getAlternate(currentBuffer));
}
});
vim.addCommand("Alternate", () => {
var alternateFile = currentAlternateFile;
// If not resolved, try the cache
if(!alternateFile)
alternateFile = alternateCache[currentBuffer];
if(alternateFile) {
// Store a reverse mapping so we can jump back easily
alternateCache[alternateFile] = currentBuffer;
vim.exec("edit " + alternateFile)
}
});
console.log("command registered")
| Switch to ambient vim variable | Switch to ambient vim variable
| TypeScript | mit | extr0py/vim-js-alternate,extr0py/vim-js-alternate | ---
+++
@@ -1,12 +1,8 @@
-#!/usr/bin/env node
-
+declare var vim;
console.log("vim-js-alternate: initialized");
import ProjectionLoader from "./ProjectionLoader";
import { ProjectionResolver } from "./ProjectionResolver";
-
-var Vim = require("vim-node-driver");
-var vim = new Vim();
var projectionLoader = new ProjectionLoader();
var projectionResolver = new ProjectionResolver(projectionLoader); |
df55617448625673676ef57cb5b2e16098a4d825 | src/sidebar-overlay/components/CongratsMessage.tsx | src/sidebar-overlay/components/CongratsMessage.tsx | import React, { PureComponent } from 'react'
import { browser } from 'webextension-polyfill-ts'
const styles = require('./CongratsMessage.css')
const partyPopperIcon = browser.runtime.getURL('/img/party_popper.svg')
class CongratsMessage extends PureComponent {
moreAboutSidebar = () => {
browser.tabs.create({
url: 'https://worldbrain.io',
})
}
goToDashboard = () => {
browser.tabs.create({
url: browser.runtime.getURL('/options.html#/overview'),
})
}
render() {
return (
<div className={styles.container}>
<div className={styles.firstRow}>
<img
src={partyPopperIcon}
alt="🎉"
className={styles.partyPopper}
/>
<p className={styles.title}>
Congrats on your first annotation
</p>
</div>
<div className={styles.learnMore} onClick={this.goToDashboard}>
Go back to Dashboard
</div>
</div>
)
}
}
export default CongratsMessage
| import React, { PureComponent } from 'react'
import { browser } from 'webextension-polyfill-ts'
import { remoteFunction } from 'src/util/webextensionRPC'
const styles = require('./CongratsMessage.css')
const partyPopperIcon = browser.runtime.getURL('/img/party_popper.svg')
class CongratsMessage extends PureComponent {
openOptionsTab = remoteFunction('openOptionsTab')
moreAboutSidebar = () => {
browser.tabs.create({
url: 'https://worldbrain.io',
})
}
goToDashboard = () => this.openOptionsTab('overview')
render() {
return (
<div className={styles.container}>
<div className={styles.firstRow}>
<img
src={partyPopperIcon}
alt="🎉"
className={styles.partyPopper}
/>
<p className={styles.title}>
Congrats on your first annotation
</p>
</div>
<div className={styles.learnMore} onClick={this.goToDashboard}>
Go back to Dashboard
</div>
</div>
)
}
}
export default CongratsMessage
| Use remote function to open dashboard. | Use remote function to open dashboard.
In the CongratsMessage button. Fixes issue where the button wasn't
working in Firefox. Also, should fix the issue where this didn't work
in content script.
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -1,22 +1,21 @@
import React, { PureComponent } from 'react'
import { browser } from 'webextension-polyfill-ts'
+import { remoteFunction } from 'src/util/webextensionRPC'
const styles = require('./CongratsMessage.css')
const partyPopperIcon = browser.runtime.getURL('/img/party_popper.svg')
class CongratsMessage extends PureComponent {
+ openOptionsTab = remoteFunction('openOptionsTab')
+
moreAboutSidebar = () => {
browser.tabs.create({
url: 'https://worldbrain.io',
})
}
- goToDashboard = () => {
- browser.tabs.create({
- url: browser.runtime.getURL('/options.html#/overview'),
- })
- }
+ goToDashboard = () => this.openOptionsTab('overview')
render() {
return ( |
048ebb49f9e381a584d4e7dd5ebe9f3734d8d608 | src/app/app.component.ts | src/app/app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'demo-app',
template: `
<prx-header>
<prx-navitem route="/" text="PRX StyleGuide"></prx-navitem>
<prx-navuser userName="Mary">
<div class="user-loaded profile-image-placeholder"></div>
</prx-navuser>
</prx-header>
<prx-modal></prx-modal>
<main>
<article>
<router-outlet></router-outlet>
</article>
</main>
<prx-footer></prx-footer>
<prx-toastr></prx-toastr>
`,
styles: [`
.profile-image-placeholder {
width: 30px;
height: 30px;
border-radius: 50%;
border: 1px solid rgb(112, 142, 151);
background-color: #7b9fa7;
display: inline-block;
vertical-align: middle;
margin-left: 10px;
}
@media screen and (min-width: 768px) {
.profile-image-placeholder {
border-width: 2px;
width: 40px;
height: 40px;
}
}
`]
})
export class AppComponent {}
| import { Component } from '@angular/core';
@Component({
selector: 'demo-app',
template: `
<prx-header>
<prx-navitem route="/" text="PRX StyleGuide"></prx-navitem>
<prx-navuser userName="Mary">
<div class="user-loaded profile-image-placeholder"></div>
</prx-navuser>
</prx-header>
<prx-modal></prx-modal>
<main>
<article>
<router-outlet></router-outlet>
</article>
</main>
<prx-footer>
<p>
And also some footer content, including a <a href="#">link to something</a>.
</p>
<a href="#">And also a standalone link</a>
</prx-footer>
<prx-toastr></prx-toastr>
`,
styles: [`
.profile-image-placeholder {
width: 30px;
height: 30px;
border-radius: 50%;
border: 1px solid rgb(112, 142, 151);
background-color: #7b9fa7;
display: inline-block;
vertical-align: middle;
margin-left: 10px;
}
@media screen and (min-width: 768px) {
.profile-image-placeholder {
border-width: 2px;
width: 40px;
height: 40px;
}
}
`]
})
export class AppComponent {}
| Remove hardcoded beta notice, but add content projection | Remove hardcoded beta notice, but add content projection
| TypeScript | mit | PRX/styleguide.prx.org,PRX/styleguide.prx.org,PRX/styleguide.prx.org,PRX/styleguide.prx.org | ---
+++
@@ -15,7 +15,12 @@
<router-outlet></router-outlet>
</article>
</main>
- <prx-footer></prx-footer>
+ <prx-footer>
+ <p>
+ And also some footer content, including a <a href="#">link to something</a>.
+ </p>
+ <a href="#">And also a standalone link</a>
+ </prx-footer>
<prx-toastr></prx-toastr>
`,
styles: [` |
9ae399927f8ff982ea24da70cda58233c7a4a301 | test/test.ts | test/test.ts | import { expect } from "chai";
import * as skinview3d from "../src/skinview3d";
import skin1_8Default from "./textures/skin-1.8-default-no_hd.png";
import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png";
import skinOldDefault from "./textures/skin-old-default-no_hd.png";
describe("detect model of texture", () => {
it("1.8 default", async () => {
const image = document.createElement("img");
image.src = skin1_8Default;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
it("1.8 slim", async () => {
const image = document.createElement("img");
image.src = skin1_8Slim;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(true);
});
it("old default", async () => {
const image = document.createElement("img");
image.src = skinOldDefault;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
}); | /// <reference path="shims.d.ts"/>
import { expect } from "chai";
import * as skinview3d from "../src/skinview3d";
import skin1_8Default from "./textures/skin-1.8-default-no_hd.png";
import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png";
import skinOldDefault from "./textures/skin-old-default-no_hd.png";
import skinLegacyHatDefault from "./textures/skin-legacyhat-default-no_hd.png";
describe("detect model of texture", () => {
it("1.8 default", async () => {
const image = document.createElement("img");
image.src = skin1_8Default;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
it("1.8 slim", async () => {
const image = document.createElement("img");
image.src = skin1_8Slim;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(true);
});
it("old default", async () => {
const image = document.createElement("img");
image.src = skinOldDefault;
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
/* TODO: implement transparent hat check for 64x32 skins
it("legacy hat test", async () => {
const image = document.createElement("img");
image.src = skinLegacyHatDefault;
await Promise.resolve();
});
*/
});
| Add refrence to the shim so VSCode does not throw errors | Add refrence to the shim so VSCode does not throw errors
| TypeScript | mit | to2mbn/skinview3d | ---
+++
@@ -1,9 +1,12 @@
+/// <reference path="shims.d.ts"/>
+
import { expect } from "chai";
import * as skinview3d from "../src/skinview3d";
import skin1_8Default from "./textures/skin-1.8-default-no_hd.png";
import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png";
import skinOldDefault from "./textures/skin-old-default-no_hd.png";
+import skinLegacyHatDefault from "./textures/skin-legacyhat-default-no_hd.png";
describe("detect model of texture", () => {
it("1.8 default", async () => {
@@ -26,4 +29,13 @@
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
+
+ /* TODO: implement transparent hat check for 64x32 skins
+ it("legacy hat test", async () => {
+ const image = document.createElement("img");
+ image.src = skinLegacyHatDefault;
+ await Promise.resolve();
+
+ });
+ */
}); |
4dffe81caf01a69b61d5144fc821387cee1dc1c1 | test/util.ts | test/util.ts | import { spawn } from 'child_process';
import { readFile, readFileSync, readdirSync } from 'fs';
import * as path from 'path';
import { formatText } from '../src/index';
export function runLuaCode(code: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const process = spawn('lua53', ['-']);
try {
process.stdin.write(code, 'utf-8');
process.stdin.end();
} catch (e) {
reject(e);
}
process.stderr.on('data', (data: Buffer) => {
const str = data.toString();
return reject(new Error(str));
});
process.on('close', exitCode => {
if (exitCode === 0) {
resolve(true);
}
});
});
}
export function readFileContents(path: string) {
return new Promise<string>((resolve, reject) => {
readFile(path, 'utf-8', (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
}
export function runTest(dirName: string) {
test(path.basename(dirName), () => {
readdirSync(dirName).forEach(fileName => {
if (!fileName.endsWith('.lua')) {
return;
}
const filePath = path.join(dirName, fileName);
const text = readFileSync(filePath, 'utf-8');
const formatted = formatText(text);
expect(formatted).toMatchSnapshot(fileName);
});
});
}
| import { spawn } from 'child_process';
import { readFile, readFileSync, readdirSync } from 'fs';
import * as path from 'path';
import { formatText } from '../src/index';
import { UserOptions } from '../src/options';
export function runLuaCode(code: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const process = spawn('lua53', ['-']);
try {
process.stdin.write(code, 'utf-8');
process.stdin.end();
} catch (e) {
reject(e);
}
process.stderr.on('data', (data: Buffer) => {
const str = data.toString();
return reject(new Error(str));
});
process.on('close', exitCode => {
if (exitCode === 0) {
resolve(true);
}
});
});
}
export function readFileContents(path: string) {
return new Promise<string>((resolve, reject) => {
readFile(path, 'utf-8', (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
}
export function runTest(dirName: string, userOptions?: UserOptions) {
test(path.basename(dirName), () => {
readdirSync(dirName).forEach(fileName => {
if (!fileName.endsWith('.lua')) {
return;
}
const filePath = path.join(dirName, fileName);
const text = readFileSync(filePath, 'utf-8');
const formatted = formatText(text, userOptions);
expect(formatted).toMatchSnapshot(fileName);
});
});
}
| Add support for running tests with options. | Add support for running tests with options.
| TypeScript | mit | trixnz/lua-fmt,willmoffat/lua-fmt,willmoffat/lua-fmt,trixnz/lua-fmt | ---
+++
@@ -3,6 +3,7 @@
import * as path from 'path';
import { formatText } from '../src/index';
+import { UserOptions } from '../src/options';
export function runLuaCode(code: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
@@ -40,7 +41,7 @@
});
}
-export function runTest(dirName: string) {
+export function runTest(dirName: string, userOptions?: UserOptions) {
test(path.basename(dirName), () => {
readdirSync(dirName).forEach(fileName => {
if (!fileName.endsWith('.lua')) {
@@ -49,7 +50,7 @@
const filePath = path.join(dirName, fileName);
const text = readFileSync(filePath, 'utf-8');
- const formatted = formatText(text);
+ const formatted = formatText(text, userOptions);
expect(formatted).toMatchSnapshot(fileName);
}); |
5756256af81db3e06f743d9ddf9964ebe95815da | lib/hooks/typescript-compilation.ts | lib/hooks/typescript-compilation.ts | ///<reference path="../.d.ts"/>
"use strict";
require("./../bootstrap");
import * as path from "path";
import fiberBootstrap = require("./../common/fiber-bootstrap");
fiberBootstrap.run(() => {
$injector.require("typeScriptCompilationService", "./common/services/typescript-compilation-service");
let project: Project.IProject = $injector.resolve("project");
project.ensureProject();
let typeScriptFiles = project.getTypeScriptFiles().wait();
if(typeScriptFiles.typeScriptFiles.length > typeScriptFiles.definitionFiles.length) { // We need this check because some of non-typescript templates(for example KendoUI.Strip) contain typescript definition files
let typeScriptCompilationService: ITypeScriptCompilationService = $injector.resolve("typeScriptCompilationService");
let $fs: IFileSystem = $injector.resolve("fs");
let pathToTsConfig = path.join(project.getProjectDir().wait(), "tsconfig.json");
if($fs.exists(pathToTsConfig).wait()) {
let json = $fs.readJson(pathToTsConfig).wait();
typeScriptCompilationService.compileWithDefaultOptions({ noEmitOnError: !!(json && json.compilerOptions && json.compilerOptions.noEmitOnError) }).wait();
} else {
typeScriptCompilationService.compileFiles({ noEmitOnError: false }, typeScriptFiles.typeScriptFiles, typeScriptFiles.definitionFiles).wait();
}
}
});
| ///<reference path="../.d.ts"/>
"use strict";
require("./../bootstrap");
import * as path from "path";
import fiberBootstrap = require("./../common/fiber-bootstrap");
fiberBootstrap.run(() => {
$injector.require("typeScriptCompilationService", "./common/services/typescript-compilation-service");
let project: Project.IProject = $injector.resolve("project");
if (!project.projectData) {
return;
}
let typeScriptFiles = project.getTypeScriptFiles().wait();
if (typeScriptFiles.typeScriptFiles.length > typeScriptFiles.definitionFiles.length) { // We need this check because some of non-typescript templates(for example KendoUI.Strip) contain typescript definition files
let typeScriptCompilationService: ITypeScriptCompilationService = $injector.resolve("typeScriptCompilationService");
let $fs: IFileSystem = $injector.resolve("fs");
let pathToTsConfig = path.join(project.getProjectDir().wait(), "tsconfig.json");
if ($fs.exists(pathToTsConfig).wait()) {
let json = $fs.readJson(pathToTsConfig).wait();
typeScriptCompilationService.compileWithDefaultOptions({ noEmitOnError: !!(json && json.compilerOptions && json.compilerOptions.noEmitOnError) }).wait();
} else {
typeScriptCompilationService.compileFiles({ noEmitOnError: false }, typeScriptFiles.typeScriptFiles, typeScriptFiles.definitionFiles).wait();
}
}
});
| Fix bug in commands fail if executed outside project | Fix bug in commands fail if executed outside project
When checking if command is executed in project in the typescript-compilation hook need to return not to throw error because the not in project message and command help will not be shown.
| TypeScript | apache-2.0 | Icenium/icenium-cli,Icenium/icenium-cli | ---
+++
@@ -7,13 +7,16 @@
fiberBootstrap.run(() => {
$injector.require("typeScriptCompilationService", "./common/services/typescript-compilation-service");
let project: Project.IProject = $injector.resolve("project");
- project.ensureProject();
+ if (!project.projectData) {
+ return;
+ }
+
let typeScriptFiles = project.getTypeScriptFiles().wait();
- if(typeScriptFiles.typeScriptFiles.length > typeScriptFiles.definitionFiles.length) { // We need this check because some of non-typescript templates(for example KendoUI.Strip) contain typescript definition files
+ if (typeScriptFiles.typeScriptFiles.length > typeScriptFiles.definitionFiles.length) { // We need this check because some of non-typescript templates(for example KendoUI.Strip) contain typescript definition files
let typeScriptCompilationService: ITypeScriptCompilationService = $injector.resolve("typeScriptCompilationService");
let $fs: IFileSystem = $injector.resolve("fs");
let pathToTsConfig = path.join(project.getProjectDir().wait(), "tsconfig.json");
- if($fs.exists(pathToTsConfig).wait()) {
+ if ($fs.exists(pathToTsConfig).wait()) {
let json = $fs.readJson(pathToTsConfig).wait();
typeScriptCompilationService.compileWithDefaultOptions({ noEmitOnError: !!(json && json.compilerOptions && json.compilerOptions.noEmitOnError) }).wait();
} else { |
6b8df6bcea01a7ef5a956568e3347826ada2783a | src/main.ts | src/main.ts | import {createState, createReducer} from "./rxjs-redux";
import {counterActions, counterReducer, CounterState} from "./counter";
import {nameActions, nameReducer, NameState} from "./appName";
// our application state as a strongly typed class which makes up the initial state
interface IAppState extends CounterState, NameState /* otherState1, otherState2,...*/ {}
// best practice is to use a plain object as State instance to allow serialization etc.
const initialState: IAppState = {
counter: 0,
appName: "Initial Name"
};
// put together all reducers just as with createReducer in Redux
const reducer = createReducer<IAppState>(
counterReducer,
nameReducer
/* ...
myOtherReducer1,
myOtherReducer2
*/
);
// the state replaces the store known from Redux
const state = createState(reducer, initialState);
// output every state change
state.subscribe(newState => {
const stateJson = document.createTextNode(JSON.stringify(newState, undefined, 2));
document.querySelector("body").appendChild(stateJson);
// add a line break after each state update
const breakLine = document.createElement("br");
document.querySelector("body").appendChild(breakLine);
});
// dispatch some actions
counterActions.increment.next(1);
counterActions.increment.next(1);
nameActions.appName.next("Foo");
counterActions.decrement.next(5);
counterActions.increment.next(8);
nameActions.appName.next("Bar");
| import {createState, createReducer} from "./rxjs-redux";
import {counterActions, counterReducer, CounterState} from "./counter";
import {nameActions, nameReducer, NameState} from "./appName";
// our application state as a strongly typed class which makes up the initial state
interface IAppState extends CounterState, NameState /* otherState1, otherState2,...*/ {}
// best practice is to use a plain object as State instance to allow serialization etc.
const initialState: IAppState = {
counter: 0,
appName: "Initial Name"
};
// put together all reducers just as with createReducer in Redux
const reducer = createReducer<IAppState>(
counterReducer,
nameReducer
/* ...
myOtherReducer1,
myOtherReducer2
*/
);
// the state replaces the store known from Redux
const state = createState(reducer, initialState);
// output every state change
state.subscribe(newState => {
const stateJson = document.createTextNode(JSON.stringify(newState));
document.querySelector("body").appendChild(stateJson);
// add a line break after each state update
const breakLine = document.createElement("br");
document.querySelector("body").appendChild(breakLine);
});
// dispatch some actions
counterActions.increment.next(1);
counterActions.increment.next(1);
nameActions.appName.next("Foo");
counterActions.decrement.next(5);
counterActions.increment.next(8);
nameActions.appName.next("Bar");
| Remove pretty-printing JSON for code simplicity sake | Remove pretty-printing JSON for code simplicity sake
| TypeScript | mit | Dynalon/redux-pattern-with-rx,Dynalon/redux-pattern-with-rx | ---
+++
@@ -26,7 +26,7 @@
// output every state change
state.subscribe(newState => {
- const stateJson = document.createTextNode(JSON.stringify(newState, undefined, 2));
+ const stateJson = document.createTextNode(JSON.stringify(newState));
document.querySelector("body").appendChild(stateJson);
// add a line break after each state update |
17050243ba59ee4268210f277bc5501c692fd26c | components/layout.tsx | components/layout.tsx | import Head from 'next/head'
import Link from 'next/link'
export default function Layout({
children,
title
}: {
children: React.ReactNode
title?: string
}) {
return (
<>
<Head>
<title>{title && title + " | "}Kevin Plattret, Software Engineer</title>
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
<link rel="shortcut icon" href="/icons/favicon.png" />
</Head>
<header className="header">
<Link href="/"><a className="alt">Kevin Plattret</a></Link>
<nav className="navigation">
<ul>
<li><Link href="/blog"><a className="alt">Blog</a></Link></li>
<li><Link href="/work"><a className="alt">Work</a></Link></li>
</ul>
</nav>
</header>
<main className="content">{children}</main>
<footer className="footer">
<p>Written by Kevin Plattret in London and other places. Source code available
on <a href="https://github.com/kplattret/kevinplattret.com">GitHub</a>. Feel free to reach
out via <a href="mailto:kevin@plattret.com">email</a>.</p>
</footer>
</>
)
}
| import Head from 'next/head'
import Link from 'next/link'
export default function Layout({
children,
title
}: {
children: React.ReactNode
title?: string
}) {
return (
<>
<Head>
<title>{title && title + " | "}Kevin Plattret, Software Engineer</title>
<link rel="apple-touch-icon" sizes="180x180" href="/icons/apple-touch-icon.png" />
<link rel="shortcut icon" href="/icons/favicon.png" />
</Head>
<header className="header">
<Link href="/"><a className="alt">Kevin Plattret</a></Link>
<nav className="navigation">
<ul>
<li><Link href="/blog"><a className="alt">Blog</a></Link></li>
<li><Link href="/work"><a className="alt">Work</a></Link></li>
</ul>
</nav>
</header>
<main className="content">{children}</main>
<footer className="footer">
<p>Written by Kevin Plattret in London and other places. Source code available
on <a href="https://github.com/kplattret/kevinplattret.com">GitHub</a>. Feel free to reach
out via <a href="mailto:kevin@plattret.com">email</a> (
<a href="https://keys.openpgp.org/search?q=kevin@plattret.com">PGP key</a>).</p>
</footer>
</>
)
}
| Add link to publib PGP key in footer | Add link to publib PGP key in footer
Let's make it easier for people to find my public PGP key if they want
to send me encrypted emails. This adds a link to my public key hosted on
the official OpenPGP keyserver.
| TypeScript | mit | kplattret/kplattret.github.io,kplattret/kplattret.github.io | ---
+++
@@ -33,7 +33,8 @@
<footer className="footer">
<p>Written by Kevin Plattret in London and other places. Source code available
on <a href="https://github.com/kplattret/kevinplattret.com">GitHub</a>. Feel free to reach
- out via <a href="mailto:kevin@plattret.com">email</a>.</p>
+ out via <a href="mailto:kevin@plattret.com">email</a> (
+ <a href="https://keys.openpgp.org/search?q=kevin@plattret.com">PGP key</a>).</p>
</footer>
</>
) |
950e4a6a898e776271a233420f3cf00bdeb2c7c7 | app/src/lib/app-state.ts | app/src/lib/app-state.ts | import User from '../models/user'
import Repository from '../models/repository'
import { Commit, Branch } from './local-git-operations'
import { FileChange, WorkingDirectoryStatus, WorkingDirectoryFileChange } from '../models/status'
/** All of the shared app state. */
export interface IAppState {
readonly users: ReadonlyArray<User>
readonly repositories: ReadonlyArray<Repository>
readonly selectedRepository: Repository | null
readonly repositoryState: IRepositoryState | null
readonly currentPopup: Popup | null
}
export enum Popup {
CreateBranch = 1,
ShowBranches,
}
export enum RepositorySection {
Changes,
History
}
export interface IRepositoryState {
readonly historyState: IHistoryState
readonly changesState: IChangesState
readonly selectedSection: RepositorySection
readonly committerEmail: string | null
readonly branchesState: IBranchesState
}
export interface IBranchesState {
readonly currentBranch: Branch | null
readonly defaultBranch: Branch | null
readonly allBranches: ReadonlyArray<Branch>
readonly recentBranches: ReadonlyArray<Branch>
readonly commits: Map<string, Commit>
}
export interface IHistorySelection {
readonly commit: Commit | null
readonly file: FileChange | null
}
export interface IHistoryState {
readonly selection: IHistorySelection
readonly commits: ReadonlyArray<Commit>
readonly commitCount: number
readonly loading: boolean
readonly changedFiles: ReadonlyArray<FileChange>
}
export interface IChangesState {
readonly workingDirectory: WorkingDirectoryStatus
readonly selectedFile: WorkingDirectoryFileChange | null
}
| import User from '../models/user'
import Repository from '../models/repository'
import { Commit, Branch } from './local-git-operations'
import { FileChange, WorkingDirectoryStatus, WorkingDirectoryFileChange } from '../models/status'
/** All of the shared app state. */
export interface IAppState {
readonly users: ReadonlyArray<User>
readonly repositories: ReadonlyArray<Repository>
readonly selectedRepository: Repository | null
readonly repositoryState: IRepositoryState | null
readonly currentPopup: Popup | null
}
export enum Popup {
CreateBranch = 1,
ShowBranches,
}
export enum RepositorySection {
Changes,
History
}
export interface IRepositoryState {
readonly historyState: IHistoryState
readonly changesState: IChangesState
readonly selectedSection: RepositorySection
readonly committerEmail: string | null
readonly branchesState: IBranchesState
}
export interface IBranchesState {
readonly currentBranch: Branch | null
readonly defaultBranch: Branch | null
readonly allBranches: ReadonlyArray<Branch>
readonly recentBranches: ReadonlyArray<Branch>
/** The commits loaded, keyed by their full SHA. */
readonly commits: Map<string, Commit>
}
export interface IHistorySelection {
readonly commit: Commit | null
readonly file: FileChange | null
}
export interface IHistoryState {
readonly selection: IHistorySelection
readonly commits: ReadonlyArray<Commit>
readonly commitCount: number
readonly loading: boolean
readonly changedFiles: ReadonlyArray<FileChange>
}
export interface IChangesState {
readonly workingDirectory: WorkingDirectoryStatus
readonly selectedFile: WorkingDirectoryFileChange | null
}
| Document how the commits map is used. | Document how the commits map is used.
| TypeScript | mit | j-f1/forked-desktop,BugTesterTest/desktops,j-f1/forked-desktop,kactus-io/kactus,gengjiawen/desktop,desktop/desktop,say25/desktop,BugTesterTest/desktops,BugTesterTest/desktops,desktop/desktop,say25/desktop,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,artivilla/desktop,hjobrien/desktop,desktop/desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,artivilla/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,hjobrien/desktop,hjobrien/desktop,kactus-io/kactus,shiftkey/desktop,artivilla/desktop,kactus-io/kactus,say25/desktop,shiftkey/desktop | ---
+++
@@ -37,6 +37,8 @@
readonly defaultBranch: Branch | null
readonly allBranches: ReadonlyArray<Branch>
readonly recentBranches: ReadonlyArray<Branch>
+
+ /** The commits loaded, keyed by their full SHA. */
readonly commits: Map<string, Commit>
}
|
90e5cc3ad53e6a054cb3e0a0cd369613233471c3 | ts/export/packer/local.ts | ts/export/packer/local.ts | import * as fs from "fs";
import { Document } from "../../docx/document";
import { Numbering } from "../../numbering";
import { Properties } from "../../properties";
import { Styles } from "../../styles";
import { Packer } from "./packer";
export class LocalPacker extends Packer {
private stream: fs.WriteStream;
constructor(document: Document, styles?: Styles, properties?: Properties, numbering?: Numbering) {
super(document, styles, properties, numbering);
}
public pack(path: string): void {
path = path.replace(/.docx$/, "");
this.stream = fs.createWriteStream(`${path}.docx`);
super.pack(this.stream);
}
}
| import * as fs from "fs";
import { Document } from "../../docx/document";
import { Numbering } from "../../numbering";
import { Properties } from "../../properties";
import { Styles } from "../../styles";
import { Packer } from "./packer";
export class LocalPacker extends Packer {
private stream: fs.WriteStream;
constructor(document: Document, styles?: Styles, properties?: Properties, numbering?: Numbering) {
super(document, styles, properties, numbering);
}
public pack(path: string): void {
this.stream = fs.createWriteStream(`${path}.docx`);
super.pack(this.stream);
}
}
| Revert "fixed the build :P removed .docx extension if one is already present" | Revert "fixed the build :P removed .docx extension if one is already present"
This reverts commit 9f61ca7abeefa05e91c9ca30a6b3998fb65c1704.
| TypeScript | mit | dolanmiu/docx,dolanmiu/docx,dolanmiu/docx | ---
+++
@@ -13,7 +13,6 @@
}
public pack(path: string): void {
- path = path.replace(/.docx$/, "");
this.stream = fs.createWriteStream(`${path}.docx`);
super.pack(this.stream);
} |
9f5fa1387ac80a7a49b71a32d99473975f1c95d1 | src/app/spell-dialog-modal/spell-dialog-modal.component.ts | src/app/spell-dialog-modal/spell-dialog-modal.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Mage } from '../model/mage.model';
import { SpellBook } from '../model/spellbook.model';
import { Spell } from '../model/spell.model';
@Component({
selector: 'app-spell-dialog-modal',
templateUrl: './spell-dialog-modal.component.html',
styleUrls: ['./spell-dialog-modal.component.css']
})
export class SpellDialogModalComponent implements OnInit {
@Input() userMage : Mage;
public currentSchool: string;
constructor() {
this.currentSchool = "";
}
ngOnInit() {
if(this.userMage== null){
this.userMage = new Mage();
}
}
getAvailableSpells(): Array<Spell>{
if(this.currentSchool == '')
{
return SpellBook.spells;
}
else
{
return SpellBook.spells.filter(this.spellSchoolMatchesSelectedSchoold);
}
}
getSchools(): Array<string>{
return SpellBook.schools;
}
addSpell(spell: Spell){
this.userMage.addSpellToCollection(spell);
}
spellSchoolMatchesSelectedSchoold(value: Spell) : boolean {
if(value.school == this.currentSchool)
{
return true;
}
else
{
return false;
}
}
}
| import { Component, OnInit, Input } from '@angular/core';
import { Mage } from '../model/mage.model';
import { SpellBook } from '../model/spellbook.model';
import { Spell } from '../model/spell.model';
@Component({
selector: 'app-spell-dialog-modal',
templateUrl: './spell-dialog-modal.component.html',
styleUrls: ['./spell-dialog-modal.component.css']
})
export class SpellDialogModalComponent implements OnInit {
@Input() userMage : Mage;
currentSchool: string;
schoolFilter: Array<string>;
constructor() {
this.schoolFilter = SpellBook.schools;
this.schoolFilter.push('All');
this.currentSchool = 'All';
}
ngOnInit() {
if(this.userMage== null){
this.userMage = new Mage();
}
}
getAvailableSpells(): Array<Spell>{
if(this.currentSchool == 'All')
{
return SpellBook.spells;
}
else
{
return SpellBook.spells.filter(x=>(x.school == this.currentSchool));
}
}
getSchools(): Array<string>{
return this.schoolFilter;
}
addSpell(spell: Spell){
this.userMage.addSpellToCollection(spell);
}
}
| Fix for Spell School filter | Fix for Spell School filter
Anonymous function works becuase it's in scope, which the called
function was not.
| TypeScript | mit | ChargerIIC/Frostgrave-WarRoster,ChargerIIC/Frostgrave-WarRoster,ChargerIIC/Frostgrave-WarRoster | ---
+++
@@ -12,10 +12,14 @@
@Input() userMage : Mage;
- public currentSchool: string;
+ currentSchool: string;
+ schoolFilter: Array<string>;
constructor() {
- this.currentSchool = "";
+ this.schoolFilter = SpellBook.schools;
+ this.schoolFilter.push('All');
+
+ this.currentSchool = 'All';
}
ngOnInit() {
@@ -26,32 +30,22 @@
}
getAvailableSpells(): Array<Spell>{
- if(this.currentSchool == '')
+ if(this.currentSchool == 'All')
{
return SpellBook.spells;
}
else
{
- return SpellBook.spells.filter(this.spellSchoolMatchesSelectedSchoold);
+ return SpellBook.spells.filter(x=>(x.school == this.currentSchool));
}
}
getSchools(): Array<string>{
- return SpellBook.schools;
+ return this.schoolFilter;
}
addSpell(spell: Spell){
this.userMage.addSpellToCollection(spell);
}
- spellSchoolMatchesSelectedSchoold(value: Spell) : boolean {
- if(value.school == this.currentSchool)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
} |
2798e415985af98b6af8aa47c6a650f463e2983a | src/app/basic-example/basic-example.component.ts | src/app/basic-example/basic-example.component.ts | import {Component, OnInit} from "@angular/core";
import {FormControl, FormGroup, Validators} from "@angular/forms";
@Component({
selector: 'app-basic-example',
templateUrl: './basic-example.component.html',
styleUrls: ['./basic-example.component.css']
})
export class BasicExampleComponent implements OnInit {
formGroup: FormGroup;
ngOnInit() {
this.formGroup = new FormGroup({
Email: new FormControl('', [
Validators.required,
Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
]),
Password: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20)
])
});
}
onSubmit() {
console.log(this.formGroup);
}
onReset() {
this.formGroup.reset();
}
}
| import {Component, OnInit} from "@angular/core";
import {FormControl, FormGroup, Validators} from "@angular/forms";
@Component({
selector: 'app-basic-example',
templateUrl: './basic-example.component.html',
styleUrls: ['./basic-example.component.css']
})
export class BasicExampleComponent implements OnInit {
formGroup: FormGroup;
ngOnInit() {
this.formGroup = new FormGroup({
Email: new FormControl('', [
Validators.required,
Validators.email
]),
Password: new FormControl('', [
Validators.required,
Validators.minLength(8),
Validators.maxLength(20)
])
});
}
onSubmit() {
console.log(this.formGroup);
}
onReset() {
this.formGroup.reset();
}
}
| Update basic example to use email validator | Update basic example to use email validator
| TypeScript | mit | third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation | ---
+++
@@ -14,7 +14,7 @@
this.formGroup = new FormGroup({
Email: new FormControl('', [
Validators.required,
- Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
+ Validators.email
]),
Password: new FormControl('', [
Validators.required, |
daab348fd5b338a2ea7cd0fd82abcd2393e7e561 | src/app/card/child-card/child-card.component.ts | src/app/card/child-card/child-card.component.ts | /**
* Created by wiekonek on 11.12.16.
*/
import {Component, Input, OnInit} from '@angular/core';
import {ChildCard} from "../card";
@Component({
selector: 'child-card',
templateUrl: './child-card.component.html'
})
export class ChildCardComponent implements OnInit {
@Input() model: ChildCard;
@Input() type: string;
protected jiraUrl: string = "";
ngOnInit(): void {
//TODO Is there any other way to get the jira base url?
this.jiraUrl = 'https://' + this.model.url.split('/')[2] + '/browse/' + this.model.key;
}
}
| /**
* Created by wiekonek on 11.12.16.
*/
import {Component, Input, OnInit} from '@angular/core';
import {ChildCard} from "../card";
@Component({
selector: 'child-card',
templateUrl: './child-card.component.html'
})
export class ChildCardComponent implements OnInit {
@Input() model: ChildCard;
@Input() type: string;
protected jiraUrl: string = "";
ngOnInit(): void {
//TODO Is there any other way to get the jira base url?
if(this.model.url != null)
this.jiraUrl = 'https://' + this.model.url.split('/')[2] + '/browse/' + this.model.key;
else
this.jiraUrl = '';
}
}
| Fix Other columns display issue. | Fix Other columns display issue.
| TypeScript | mit | JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend,JiraGoggles/jiragoggles-frontend | ---
+++
@@ -15,7 +15,11 @@
protected jiraUrl: string = "";
ngOnInit(): void {
+
//TODO Is there any other way to get the jira base url?
- this.jiraUrl = 'https://' + this.model.url.split('/')[2] + '/browse/' + this.model.key;
+ if(this.model.url != null)
+ this.jiraUrl = 'https://' + this.model.url.split('/')[2] + '/browse/' + this.model.key;
+ else
+ this.jiraUrl = '';
}
} |
b5207aab2dd220cbd4252448f2f9241fd1c02f3b | client/src/containers/groupDetail.ts | client/src/containers/groupDetail.ts | import { connect, Dispatch } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { AppState } from '../constants/types';
import GroupDetail from '../components/groupDetail';
import * as actions from '../actions/group';
export function mapStateToProps(state: AppState, params: any) {
let groupSequence = parseInt(params.match.params.groupSequence, 10);
let results;
state.groups.uniqueNames.forEach(function (uniqueName: string, idx: number) {
if (state.groups.ByUniqueNames[uniqueName].sequence === groupSequence) {
results = {group: state.groups.ByUniqueNames[uniqueName]};
}
});
if (!results) {
results = {group: null};
}
return results;
}
export interface DispatchProps {
onDelete?: () => any;
fetchData?: () => any;
}
export function mapDispatchToProps(dispatch: Dispatch<actions.GroupAction>, params: any): DispatchProps {
return {
onDelete: () => dispatch(() => undefined),
fetchData: () => dispatch(
actions.fetchGroup(
params.match.params.user,
params.match.params.projectName,
params.match.params.groupSequence))
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(GroupDetail));
| import { connect, Dispatch } from 'react-redux';
import { withRouter } from 'react-router-dom';
import * as _ from 'lodash';
import { AppState } from '../constants/types';
import GroupDetail from '../components/groupDetail';
import * as actions from '../actions/group';
import { getGroupUniqueName } from '../constants/utils';
export function mapStateToProps(state: AppState, params: any) {
let groupUniqueName = getGroupUniqueName(
params.match.params.user,
params.match.params.projectName,
params.match.params.groupSequence);
return _.includes(state.groups.uniqueNames, groupUniqueName) ?
{group: state.groups.ByUniqueNames[groupUniqueName]} :
{group: null};
}
export interface DispatchProps {
onDelete?: () => any;
fetchData?: () => any;
}
export function mapDispatchToProps(dispatch: Dispatch<actions.GroupAction>, params: any): DispatchProps {
return {
onDelete: () => dispatch(() => undefined),
fetchData: () => dispatch(
actions.fetchGroup(
params.match.params.user,
params.match.params.projectName,
params.match.params.groupSequence))
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(GroupDetail));
| Update group detail state to props mapping | Update group detail state to props mapping
| TypeScript | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -1,24 +1,20 @@
import { connect, Dispatch } from 'react-redux';
import { withRouter } from 'react-router-dom';
+import * as _ from 'lodash';
import { AppState } from '../constants/types';
import GroupDetail from '../components/groupDetail';
import * as actions from '../actions/group';
+import { getGroupUniqueName } from '../constants/utils';
-export function mapStateToProps(state: AppState, params: any) {
- let groupSequence = parseInt(params.match.params.groupSequence, 10);
- let results;
-
- state.groups.uniqueNames.forEach(function (uniqueName: string, idx: number) {
- if (state.groups.ByUniqueNames[uniqueName].sequence === groupSequence) {
- results = {group: state.groups.ByUniqueNames[uniqueName]};
- }
- });
-
- if (!results) {
- results = {group: null};
- }
- return results;
+export function mapStateToProps(state: AppState, params: any) {
+ let groupUniqueName = getGroupUniqueName(
+ params.match.params.user,
+ params.match.params.projectName,
+ params.match.params.groupSequence);
+ return _.includes(state.groups.uniqueNames, groupUniqueName) ?
+ {group: state.groups.ByUniqueNames[groupUniqueName]} :
+ {group: null};
}
export interface DispatchProps { |
221f0bcfb0297f69d76ce4b2dcce0b32b419d0ff | mousetrap/mousetrap.d.ts | mousetrap/mousetrap.d.ts | // Type definitions for Mousetrap 1.2.2
// Project: http://craig.is/killing/mice
// Definitions by: Dániel Tar https://github.com/qcz
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface ExtendedKeyboardEvent extends KeyboardEvent {
returnValue: bool; // IE returnValue
}
interface MousetrapStatic {
stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => bool;
bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string, action?: string): void;
unbind(keyArray: string[], action?: string): void;
trigger(keys: string, action?: string): void;
reset(): void;
}
declare var Mousetrap: MousetrapStatic;
| // Type definitions for Mousetrap 1.2.2
// Project: http://craig.is/killing/mice
// Definitions by: Dániel Tar https://github.com/qcz
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface ExtendedKeyboardEvent extends KeyboardEvent {
returnValue: boolean; // IE returnValue
}
interface MousetrapStatic {
stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean;
bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
unbind(keys: string, action?: string): void;
unbind(keyArray: string[], action?: string): void;
trigger(keys: string, action?: string): void;
reset(): void;
}
declare var Mousetrap: MousetrapStatic;
| Replace bool with boolean (for TypeScript 0.9.0+) | Replace bool with boolean (for TypeScript 0.9.0+) | TypeScript | mit | esperco/DefinitelyTyped,gamesbrainiac/DefinitelyTyped,aindlq/DefinitelyTyped,acepoblete/DefinitelyTyped,bruennijs/DefinitelyTyped,danludwig/DefinitelyTyped,vagarenko/DefinitelyTyped,subash-a/DefinitelyTyped,syntax42/DefinitelyTyped,ciriarte/DefinitelyTyped,mariokostelac/DefinitelyTyped,hafenr/DefinitelyTyped,ctaggart/DefinitelyTyped,tinganho/DefinitelyTyped,arueckle/DefinitelyTyped,KhodeN/DefinitelyTyped,pkaul/DefinitelyTyped,masonkmeyer/DefinitelyTyped,abbasmhd/DefinitelyTyped,newclear/DefinitelyTyped,elisee/DefinitelyTyped,wilfrem/DefinitelyTyped,davidpricedev/DefinitelyTyped,axelcostaspena/DefinitelyTyped,blittle/DefinitelyTyped,sledorze/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,Zzzen/DefinitelyTyped,RX14/DefinitelyTyped,jpevarnek/DefinitelyTyped,bobslaede/DefinitelyTyped,nestalk/DefinitelyTyped,hastebrot/DefinitelyTyped,georgemarshall/DefinitelyTyped,aaharu/DefinitelyTyped,bpowers/DefinitelyTyped,ctaggart/DefinitelyTyped,zuzusik/DefinitelyTyped,igorsechyn/DefinitelyTyped,tgrospic/DefinitelyTyped,yuit/DefinitelyTyped,laco0416/DefinitelyTyped,rerezz/DefinitelyTyped,akonwi/DefinitelyTyped,david-driscoll/DefinitelyTyped,corps/DefinitelyTyped,robl499/DefinitelyTyped,takenet/DefinitelyTyped,amanmahajan7/DefinitelyTyped,artch/DefinitelyTyped,QuatroCode/DefinitelyTyped,TheBay0r/DefinitelyTyped,mcrawshaw/DefinitelyTyped,AgentME/DefinitelyTyped,jfoliveira/DefinitelyTyped,UzEE/DefinitelyTyped,miguelmq/DefinitelyTyped,panuhorsmalahti/DefinitelyTyped,designxtek/DefinitelyTyped,s093294/DefinitelyTyped,harcher81/DefinitelyTyped,ArturSoler/DefinitelyTyped,Stephanvs/DefinitelyTyped,chrootsu/DefinitelyTyped,damianog/DefinitelyTyped,zuohaocheng/DefinitelyTyped,Litee/DefinitelyTyped,mariokostelac/DefinitelyTyped,pkaul/DefinitelyTyped,Karabur/DefinitelyTyped,ayanoin/DefinitelyTyped,duncanmak/DefinitelyTyped,Lorisu/DefinitelyTyped,YousefED/DefinitelyTyped,OpenMaths/DefinitelyTyped,isman-usoh/DefinitelyTyped,teves-castro/DefinitelyTyped,bilou84/DefinitelyTyped,use-strict/DefinitelyTyped,mariokostelac/DefinitelyTyped,ducin/DefinitelyTyped,arcticwaters/DefinitelyTyped,sventschui/DefinitelyTyped,raijinsetsu/DefinitelyTyped,chadoliver/DefinitelyTyped,nitintutlani/DefinitelyTyped,docgit/DefinitelyTyped,ErykB2000/DefinitelyTyped,martinduparc/DefinitelyTyped,wilfrem/DefinitelyTyped,tigerxy/DefinitelyTyped,3x14159265/DefinitelyTyped,takfjt/DefinitelyTyped,brainded/DefinitelyTyped,JoshRosen/DefinitelyTyped,jimthedev/DefinitelyTyped,alvarorahul/DefinitelyTyped,fdecampredon/DefinitelyTyped,Litee/DefinitelyTyped,sorskoot/DefinitelyTyped,bjfletcher/DefinitelyTyped,nestalk/DefinitelyTyped,alextkachman/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,dmorosinotto/DefinitelyTyped,TildaLabs/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,balassy/DefinitelyTyped,DeadAlready/DefinitelyTyped,adammartin1981/DefinitelyTyped,deeleman/DefinitelyTyped,iislucas/DefinitelyTyped,vagarenko/DefinitelyTyped,glenndierckx/DefinitelyTyped,xswordsx/DefinitelyTyped,pkaul/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,gedaiu/DefinitelyTyped,the41/DefinitelyTyped,dydek/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,KhodeN/DefinitelyTyped,felipe3dfx/DefinitelyTyped,Seikho/DefinitelyTyped,georgemarshall/DefinitelyTyped,TiddoLangerak/DefinitelyTyped,zoetrope/DefinitelyTyped,JeremyCBrooks/DefinitelyTyped,evansolomon/DefinitelyTyped,designxtek/DefinitelyTyped,Dominator008/DefinitelyTyped,amir-arad/DefinitelyTyped,michaelbromley/DefinitelyTyped,chbrown/DefinitelyTyped,Riron/DefinitelyTyped,Airblader/DefinitelyTyped,giabao/DefinitelyTyped,kanreisa/DefinitelyTyped,s093294/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,OpenMaths/DefinitelyTyped,awerlang/DefinitelyTyped,Zenorbi/DefinitelyTyped,QuatroCode/DefinitelyTyped,44ka28ta/DefinitelyTyped,micurs/DefinitelyTyped,syuilo/DefinitelyTyped,digitalpixies/DefinitelyTyped,M-Zuber/DefinitelyTyped,bennett000/DefinitelyTyped,emanuelhp/DefinitelyTyped,maxlang/DefinitelyTyped,trystanclarke/DefinitelyTyped,esperco/DefinitelyTyped,harcher81/DefinitelyTyped,44ka28ta/DefinitelyTyped,colindembovsky/DefinitelyTyped,nainslie/DefinitelyTyped,bardt/DefinitelyTyped,OliveTreeBible/DefinitelyTyped,jraymakers/DefinitelyTyped,giabao/DefinitelyTyped,MidnightDesign/DefinitelyTyped,nelsonmorais/DefinitelyTyped,rschmukler/DefinitelyTyped,ArturSoler/DefinitelyTyped,wkrueger/DefinitelyTyped,laball/DefinitelyTyped,nwolverson/DefinitelyTyped,dariajung/DefinitelyTyped,demerzel3/DefinitelyTyped,bencoveney/DefinitelyTyped,akonwi/DefinitelyTyped,jeffbcross/DefinitelyTyped,philippstucki/DefinitelyTyped,algas/DefinitelyTyped,jsaelhof/DefinitelyTyped,Mek7/DefinitelyTyped,sventschui/DefinitelyTyped,RX14/DefinitelyTyped,Ptival/DefinitelyTyped,nicholashead/DefinitelyTyped,scsouthw/DefinitelyTyped,musakarakas/DefinitelyTyped,behzad88/DefinitelyTyped,amanmahajan7/DefinitelyTyped,PawelStroinski/DefinitelyTyped,algas/DefinitelyTyped,balassy/DefinitelyTyped,lucyhe/DefinitelyTyped,kyo-ago/DefinitelyTyped,tboyce/DefinitelyTyped,igorraush/DefinitelyTyped,dpsthree/DefinitelyTyped,dmoonfire/DefinitelyTyped,musically-ut/DefinitelyTyped,rockclimber90/DefinitelyTyped,paypac/DefinitelyTyped,chrilith/DefinitelyTyped,dsebastien/DefinitelyTyped,tomtarrot/DefinitelyTyped,DustinWehr/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,vpineda1996/DefinitelyTyped,nycdotnet/DefinitelyTyped,AndyBursh/DefinitelyTyped,JanVoracek/DefinitelyTyped,hiraash/DefinitelyTyped,musicist288/DefinitelyTyped,olivierlemasle/DefinitelyTyped,rgripper/DefinitelyTyped,tarruda/DefinitelyTyped,harcher81/DefinitelyTyped,DeluxZ/DefinitelyTyped,tgfjt/DefinitelyTyped,Syati/DefinitelyTyped,RedSeal-co/DefinitelyTyped,Airblader/DefinitelyTyped,optical/DefinitelyTyped,newclear/DefinitelyTyped,ctaggart/DefinitelyTyped,paulbakker/DefinitelyTyped,mszczepaniak/DefinitelyTyped,shlomiassaf/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,colindembovsky/DefinitelyTyped,vote539/DefinitelyTyped,alexdresko/DefinitelyTyped,schmuli/DefinitelyTyped,Jwsonic/DefinitelyTyped,michalczukm/DefinitelyTyped,johan-gorter/DefinitelyTyped,Airblader/DefinitelyTyped,toedter/DefinitelyTyped,ecramer89/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,JoshRosen/DefinitelyTyped,rolandzwaga/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,Dashlane/DefinitelyTyped,RupertAvery/DefinitelyTyped,donnut/DefinitelyTyped,lbesson/DefinitelyTyped,aroder/DefinitelyTyped,elisee/DefinitelyTyped,Maplecroft/DefinitelyTyped,PopSugar/DefinitelyTyped,mattblang/DefinitelyTyped,mareek/DefinitelyTyped,rgripper/DefinitelyTyped,david-driscoll/DefinitelyTyped,TyOverby/DefinitelyTyped,KhodeN/DefinitelyTyped,demerzel3/DefinitelyTyped,chrootsu/DefinitelyTyped,stacktracejs/DefinitelyTyped,xica/DefinitelyTyped,hesselink/DefinitelyTyped,Asido/DefinitelyTyped,44ka28ta/DefinitelyTyped,opichals/DefinitelyTyped,bayitajesi/DefinitelyTyped,Stephanvs/DefinitelyTyped,lseguin42/DefinitelyTyped,designxtek/DefinitelyTyped,mhegazy/DefinitelyTyped,tomtheisen/DefinitelyTyped,abner/DefinitelyTyped,emanuelhp/DefinitelyTyped,grahammendick/DefinitelyTyped,smrq/DefinitelyTyped,forumone/DefinitelyTyped,bdukes/DefinitelyTyped,jasonswearingen/DefinitelyTyped,YusukeHirao/DefinitelyTyped,martinduparc/DefinitelyTyped,mrk21/DefinitelyTyped,lukehoban/DefinitelyTyped,sorskoot/DefinitelyTyped,samwgoldman/DefinitelyTyped,scriby/DefinitelyTyped,PawelStroinski/DefinitelyTyped,frogcjn/DefinitelyTyped,PascalSenn/DefinitelyTyped,Airblader/DefinitelyTyped,Dominator008/DefinitelyTyped,schmuli/DefinitelyTyped,omidkrad/DefinitelyTyped,gildorwang/DefinitelyTyped,hx0day/DefinitelyTyped,LordJZ/DefinitelyTyped,wilkerlucio/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,gerich-home/DefinitelyTyped,hellopao/DefinitelyTyped,hatz48/DefinitelyTyped,pwelter34/DefinitelyTyped,dwango-js/DefinitelyTyped,timjk/DefinitelyTyped,anweiss/DefinitelyTyped,Wordenskjold/DefinitelyTyped,aaharu/DefinitelyTyped,spion/DefinitelyTyped,nodeframe/DefinitelyTyped,greglo/DefinitelyTyped,stimms/DefinitelyTyped,Zzzen/DefinitelyTyped,shiwano/DefinitelyTyped,aldo-roman/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,kmeurer/DefinitelyTyped,sorskoot/DefinitelyTyped,Belelros/DefinitelyTyped,stylelab-io/DefinitelyTyped,progre/DefinitelyTyped,wilkerlucio/DefinitelyTyped,optical/DefinitelyTyped,pwelter34/DefinitelyTyped,nestalk/DefinitelyTyped,paypac/DefinitelyTyped,mareek/DefinitelyTyped,colindembovsky/DefinitelyTyped,giggio/DefinitelyTyped,daptiv/DefinitelyTyped,philippsimon/DefinitelyTyped,reppners/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,moonpyk/DefinitelyTyped,demerzel3/DefinitelyTyped,alextkachman/DefinitelyTyped,benishouga/DefinitelyTyped,nycdotnet/DefinitelyTyped,stephenjelfs/DefinitelyTyped,kabogo/DefinitelyTyped,chrismbarr/DefinitelyTyped,bdoss/DefinitelyTyped,harcher81/DefinitelyTyped,Seltzer/DefinitelyTyped,Fraegle/DefinitelyTyped,gyohk/DefinitelyTyped,EnableSoftware/DefinitelyTyped,xStrom/DefinitelyTyped,innerverse/DefinitelyTyped,tjoskar/DefinitelyTyped,frogcjn/DefinitelyTyped,axefrog/DefinitelyTyped,tgfjt/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,goaty92/DefinitelyTyped,teddyward/DefinitelyTyped,dmorosinotto/DefinitelyTyped,3x14159265/DefinitelyTyped,jiaz/DefinitelyTyped,blittle/DefinitelyTyped,JeremyCBrooks/DefinitelyTyped,paxibay/DefinitelyTyped,jaysoo/DefinitelyTyped,uestcNaldo/DefinitelyTyped,psnider/DefinitelyTyped,florentpoujol/DefinitelyTyped,seikichi/DefinitelyTyped,toedter/DefinitelyTyped,sandersky/DefinitelyTyped,zoetrope/DefinitelyTyped,scriby/DefinitelyTyped,zensh/DefinitelyTyped,GodsBreath/DefinitelyTyped,pinoyyid/DefinitelyTyped,borisyankov/DefinitelyTyped,scatcher/DefinitelyTyped,nojaf/DefinitelyTyped,YousefED/DefinitelyTyped,AgentME/DefinitelyTyped,dumbmatter/DefinitelyTyped,gandjustas/DefinitelyTyped,zuzusik/DefinitelyTyped,jtlan/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,fdecampredon/DefinitelyTyped,isman-usoh/DefinitelyTyped,YusukeHirao/DefinitelyTyped,axefrog/DefinitelyTyped,gandjustas/DefinitelyTyped,ajtowf/DefinitelyTyped,stephenjelfs/DefinitelyTyped,johan-gorter/DefinitelyTyped,rcchen/DefinitelyTyped,takenet/DefinitelyTyped,designxtek/DefinitelyTyped,Penryn/DefinitelyTyped,OliveTreeBible/DefinitelyTyped,3x14159265/DefinitelyTyped,quantumman/DefinitelyTyped,paulbakker/DefinitelyTyped,basp/DefinitelyTyped,danludwig/DefinitelyTyped,abbasmhd/DefinitelyTyped,shahata/DefinitelyTyped,varju/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,brettle/DefinitelyTyped,xStrom/DefinitelyTyped,ctaggart/DefinitelyTyped,OfficeDev/DefinitelyTyped,jfoliveira/DefinitelyTyped,whoeverest/DefinitelyTyped,mattblang/DefinitelyTyped,modifyink/DefinitelyTyped,Pro/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,psnider/DefinitelyTyped,dreampulse/DefinitelyTyped,dmorosinotto/DefinitelyTyped,abner/DefinitelyTyped,sventschui/DefinitelyTyped,nabeix/DefinitelyTyped,glenndierckx/DefinitelyTyped,jesseschalken/DefinitelyTyped,zoetrope/DefinitelyTyped,syuilo/DefinitelyTyped,lbguilherme/DefinitelyTyped,vincentw56/DefinitelyTyped,maglar0/DefinitelyTyped,cvrajeesh/DefinitelyTyped,mjjames/DefinitelyTyped,sclausen/DefinitelyTyped,Maplecroft/DefinitelyTyped,arma-gast/DefinitelyTyped,tgrospic/DefinitelyTyped,arcticwaters/DefinitelyTyped,olemp/DefinitelyTyped,NCARalph/DefinitelyTyped,robertbaker/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,furny/DefinitelyTyped,lcorneliussen/DefinitelyTyped,gyohk/DefinitelyTyped,Maplecroft/DefinitelyTyped,lcorneliussen/DefinitelyTyped,vote539/DefinitelyTyped,alainsahli/DefinitelyTyped,hellopao/DefinitelyTyped,JeremyCBrooks/DefinitelyTyped,davidsidlinger/DefinitelyTyped,danfma/DefinitelyTyped,Trapulo/DefinitelyTyped,bkristensen/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,greglockwood/DefinitelyTyped,Ptival/DefinitelyTyped,algorithme/DefinitelyTyped,blittle/DefinitelyTyped,ashwinr/DefinitelyTyped,florentpoujol/DefinitelyTyped,markogresak/DefinitelyTyped,magny/DefinitelyTyped,stimms/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,tan9/DefinitelyTyped,philippstucki/DefinitelyTyped,wilkerlucio/DefinitelyTyped,Almouro/DefinitelyTyped,gorcz/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,pinoyyid/DefinitelyTyped,abmohan/DefinitelyTyped,icereed/DefinitelyTyped,ArturSoler/DefinitelyTyped,wilkerlucio/DefinitelyTyped,kyo-ago/DefinitelyTyped,hor-crux/DefinitelyTyped,lightswitch05/DefinitelyTyped,OliveTreeBible/DefinitelyTyped,dragouf/DefinitelyTyped,antiveeranna/DefinitelyTyped,akonwi/DefinitelyTyped,antiveeranna/DefinitelyTyped,axefrog/DefinitelyTyped,raijinsetsu/DefinitelyTyped,rgripper/DefinitelyTyped,balassy/DefinitelyTyped,AgentME/DefinitelyTyped,RupertAvery/DefinitelyTyped,nainslie/DefinitelyTyped,bluong/DefinitelyTyped,martinduparc/DefinitelyTyped,Saneyan/DefinitelyTyped,subjectix/DefinitelyTyped,Zorgatone/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,giabao/DefinitelyTyped,rgripper/DefinitelyTyped,progre/DefinitelyTyped,mrozhin/DefinitelyTyped,philippsimon/DefinitelyTyped,anweiss/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,AgentME/DefinitelyTyped,johnnycrab/DefinitelyTyped,HPFOD/DefinitelyTyped,AGBrown/DefinitelyTyped-ABContrib,artch/DefinitelyTyped,shlomiassaf/DefinitelyTyped,jasonswearingen/DefinitelyTyped,seikichi/DefinitelyTyped,paulbakker/DefinitelyTyped,shovon/DefinitelyTyped,EnableSoftware/DefinitelyTyped,benishouga/DefinitelyTyped,gdi2290/DefinitelyTyped,pkaul/DefinitelyTyped,michaelbromley/DefinitelyTyped,jeremyhayes/DefinitelyTyped,fredgalvao/DefinitelyTyped,use-strict/DefinitelyTyped,Belelros/DefinitelyTyped,chrismbarr/DefinitelyTyped,dmoonfire/DefinitelyTyped,Asido/DefinitelyTyped,georgemarshall/DefinitelyTyped,IAPark/DefinitelyTyped,Syati/DefinitelyTyped,axefrog/DefinitelyTyped,drinchev/DefinitelyTyped,UzEE/DefinitelyTyped,docgit/DefinitelyTyped,drillbits/DefinitelyTyped,spion/DefinitelyTyped,kuon/DefinitelyTyped,arusakov/DefinitelyTyped,gerich-home/DefinitelyTyped,benishouga/DefinitelyTyped,sclausen/DefinitelyTyped,manekovskiy/DefinitelyTyped,egeland/DefinitelyTyped,fearthecowboy/DefinitelyTyped,AndrewGaspar/DefinitelyTyped,sledorze/DefinitelyTyped,egeland/DefinitelyTyped,bayitajesi/DefinitelyTyped,paypac/DefinitelyTyped,stimms/DefinitelyTyped,TyOverby/DefinitelyTyped,wbuchwalter/DefinitelyTyped,onecentlin/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,zalamtech/DefinitelyTyped,tdmckinn/DefinitelyTyped,Shiak1/DefinitelyTyped,theyelllowdart/DefinitelyTyped,ashwinr/DefinitelyTyped,bdukes/DefinitelyTyped,hastebrot/DefinitelyTyped,almstrand/DefinitelyTyped,3x14159265/DefinitelyTyped,nwolverson/DefinitelyTyped,RupertAvery/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mweststrate/DefinitelyTyped,munxar/DefinitelyTyped,danfma/DefinitelyTyped,fredgalvao/DefinitelyTyped,sorskoot/DefinitelyTyped,superduper/DefinitelyTyped,onecentlin/DefinitelyTyped,fdecampredon/DefinitelyTyped,Belelros/DefinitelyTyped,blink1073/DefinitelyTyped,MarlonFan/DefinitelyTyped,antiveeranna/DefinitelyTyped,colindembovsky/DefinitelyTyped,RupertAvery/DefinitelyTyped,MugeSo/DefinitelyTyped,Pro/DefinitelyTyped,shiwano/DefinitelyTyped,lcorneliussen/DefinitelyTyped,JoshRosen/DefinitelyTyped,duongphuhiep/DefinitelyTyped,brentonhouse/DefinitelyTyped,MugeSo/DefinitelyTyped,PawelStroinski/DefinitelyTyped,nicholashead/DefinitelyTyped,Bobjoy/DefinitelyTyped,georgemarshall/DefinitelyTyped,vsavkin/DefinitelyTyped,TiddoLangerak/DefinitelyTyped,hudon/DefinitelyTyped,nestalk/DefinitelyTyped,wcomartin/DefinitelyTyped,demerzel3/DefinitelyTyped,mhegazy/DefinitelyTyped,kyo-ago/DefinitelyTyped,zoetrope/DefinitelyTyped,44ka28ta/DefinitelyTyped,stacktracejs/DefinitelyTyped,trystanclarke/DefinitelyTyped,nakakura/DefinitelyTyped,paypac/DefinitelyTyped,modifyink/DefinitelyTyped,varju/DefinitelyTyped,gregoryagu/DefinitelyTyped,KonaTeam/DefinitelyTyped,mshmelev/DefinitelyTyped,magny/DefinitelyTyped,aciccarello/DefinitelyTyped,johnnycrab/DefinitelyTyped,JoshRosen/DefinitelyTyped,robert-voica/DefinitelyTyped,toedter/DefinitelyTyped,chocolatechipui/DefinitelyTyped,fnipo/DefinitelyTyped,muenchdo/DefinitelyTyped,mjjames/DefinitelyTyped,thSoft/DefinitelyTyped,lcorneliussen/DefinitelyTyped,Maplecroft/DefinitelyTyped,evandrewry/DefinitelyTyped,dsebastien/DefinitelyTyped,spion/DefinitelyTyped,nobuoka/DefinitelyTyped,pocesar/DefinitelyTyped,Stephanvs/DefinitelyTyped,drinchev/DefinitelyTyped,alexdresko/DefinitelyTyped,nmalaguti/DefinitelyTyped,Garciat/DefinitelyTyped,pinoyyid/DefinitelyTyped,iislucas/DefinitelyTyped,CSharpFan/DefinitelyTyped,arma-gast/DefinitelyTyped,HPFOD/DefinitelyTyped,jsaelhof/DefinitelyTyped,ryan10132/DefinitelyTyped,Karabur/DefinitelyTyped,rschmukler/DefinitelyTyped,rcchen/DefinitelyTyped,samdark/DefinitelyTyped,herrmanno/DefinitelyTyped,applesaucers/lodash-invokeMap,gcastre/DefinitelyTyped,borisyankov/DefinitelyTyped,nfriend/DefinitelyTyped,yuit/DefinitelyTyped,fdecampredon/DefinitelyTyped,mcrawshaw/DefinitelyTyped,thSoft/DefinitelyTyped,johnnycrab/DefinitelyTyped,Ridermansb/DefinitelyTyped,ajtowf/DefinitelyTyped,reppners/DefinitelyTyped,AndrewGaspar/DefinitelyTyped,pocesar/DefinitelyTyped,ml-workshare/DefinitelyTyped,Chris380/DefinitelyTyped,hastebrot/DefinitelyTyped,aciccarello/DefinitelyTyped,bayitajesi/DefinitelyTyped,miguelmq/DefinitelyTyped,gerich-home/DefinitelyTyped,bdukes/DefinitelyTyped,dydek/DefinitelyTyped,zhiyiting/DefinitelyTyped,benliddicott/DefinitelyTyped,AndrewGaspar/DefinitelyTyped,applesaucers/lodash-invokeMap,nseckinoral/DefinitelyTyped,Belelros/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,eekboom/DefinitelyTyped,sixinli/DefinitelyTyped,tan9/DefinitelyTyped,jraymakers/DefinitelyTyped,thSoft/DefinitelyTyped,aciccarello/DefinitelyTyped,unknownloner/DefinitelyTyped,hatz48/DefinitelyTyped,s093294/DefinitelyTyped,aaharu/DefinitelyTyped,Dashlane/DefinitelyTyped,psnider/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,damianog/DefinitelyTyped,OliveTreeBible/DefinitelyTyped,olemp/DefinitelyTyped,rfranco/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,pocesar/DefinitelyTyped,pkhayundi/DefinitelyTyped,gerich-home/DefinitelyTyped,timramone/DefinitelyTyped,arusakov/DefinitelyTyped,KhodeN/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,DenEwout/DefinitelyTyped,billccn/DefinitelyTyped,mcliment/DefinitelyTyped,JaminFarr/DefinitelyTyped,leoromanovsky/DefinitelyTyped,nakakura/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,algas/DefinitelyTyped,Wordenskjold/DefinitelyTyped,erosb/DefinitelyTyped,Kuniwak/DefinitelyTyped,jimthedev/DefinitelyTyped,vasek17/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,jacqt/DefinitelyTyped,varju/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,flyfishMT/DefinitelyTyped,nitintutlani/DefinitelyTyped,lekaha/DefinitelyTyped,angelobelchior8/DefinitelyTyped,ArturSoler/DefinitelyTyped,mattanja/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,docgit/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,spearhead-ea/DefinitelyTyped,one-pieces/DefinitelyTyped,AndyBursh/DefinitelyTyped,Deathspike/DefinitelyTyped,algas/DefinitelyTyped,bdukes/DefinitelyTyped,tgrospic/DefinitelyTyped,david-driscoll/DefinitelyTyped,Carreau/DefinitelyTyped,stanislavHamara/DefinitelyTyped,greglo/DefinitelyTyped,schmuli/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,biomassives/DefinitelyTyped,HereSinceres/DefinitelyTyped,michaelbromley/DefinitelyTyped,mvarblow/DefinitelyTyped,TiddoLangerak/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,richardTowers/DefinitelyTyped,danludwig/DefinitelyTyped,Zorgatone/DefinitelyTyped,mshmelev/DefinitelyTyped,Minishlink/DefinitelyTyped,Stephanvs/DefinitelyTyped,davidpricedev/DefinitelyTyped,pafflique/DefinitelyTyped,arusakov/DefinitelyTyped,mwain/DefinitelyTyped,zuzusik/DefinitelyTyped,hypno2000/typings,panuhorsmalahti/DefinitelyTyped,hellopao/DefinitelyTyped,WritingPanda/DefinitelyTyped,paulmorphy/DefinitelyTyped,subash-a/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,bdoss/DefinitelyTyped,Nemo157/DefinitelyTyped,hudon/DefinitelyTyped,anweiss/DefinitelyTyped,mattanja/DefinitelyTyped,gcastre/DefinitelyTyped,smrq/DefinitelyTyped,teves-castro/DefinitelyTyped,cherrydev/DefinitelyTyped,paulmorphy/DefinitelyTyped,mendix/DefinitelyTyped,giabao/DefinitelyTyped,dflor003/DefinitelyTyped,behzad888/DefinitelyTyped,adamcarr/DefinitelyTyped,flyfishMT/DefinitelyTyped,bennett000/DefinitelyTyped,nwolverson/DefinitelyTyped,nwolverson/DefinitelyTyped,jimthedev/DefinitelyTyped,kalloc/DefinitelyTyped,alvarorahul/DefinitelyTyped,minodisk/DefinitelyTyped,eugenpodaru/DefinitelyTyped,darkl/DefinitelyTyped,rushi216/DefinitelyTyped,pocke/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,balassy/DefinitelyTyped,spion/DefinitelyTyped,AndrewGaspar/DefinitelyTyped,tscho/DefinitelyTyped,Pipe-shen/DefinitelyTyped,bobslaede/DefinitelyTyped,nobuoka/DefinitelyTyped,Penryn/DefinitelyTyped,behzad888/DefinitelyTyped,aqua89/DefinitelyTyped,jbrantly/DefinitelyTyped,donnut/DefinitelyTyped,GregOnNet/DefinitelyTyped,JanVoracek/DefinitelyTyped,gamesbrainiac/DefinitelyTyped,minodisk/DefinitelyTyped,sventschui/DefinitelyTyped,nmalaguti/DefinitelyTyped,nicholashead/DefinitelyTyped,haskellcamargo/DefinitelyTyped,Gmulti/DefinitelyTyped | ---
+++
@@ -4,11 +4,11 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface ExtendedKeyboardEvent extends KeyboardEvent {
- returnValue: bool; // IE returnValue
+ returnValue: boolean; // IE returnValue
}
interface MousetrapStatic {
- stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => bool;
+ stopCallback: (e: ExtendedKeyboardEvent, element: Element, combo: string) => boolean;
bind(keys: string, callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void;
bind(keyArray: string[], callback: (e: ExtendedKeyboardEvent, combo: string) => any, action?: string): void; |
541211016b7c9c51384b346bf775375ed9a508f1 | packages/website-backend/src/api/auth/GithubAuth.ts | packages/website-backend/src/api/auth/GithubAuth.ts | import { Controller, Get, Use, Post } from '@tsed/common';
import passport from 'passport'; import express from 'express';
import { Request, Response, NextFunction } from 'express';
import { createToken, passportAuthenticateGithub } from '../../middleware/securityMiddleware';
import * as utils from '../../utils';
import Configuration from '../../services/Configuration';
import { AuthenticateResponse } from '@stryker-mutator/dashboard-contract';
@Controller('/auth/github')
export default class GithubAuth {
private readonly log = utils.debug(GithubAuth.name);
constructor(private readonly config: Configuration) {
}
@Get('/')
public get(request: express.Request, response: express.Response, next: express.NextFunction): void {
passport.authenticate('github', { scope: ['user:email', 'read:org', 'repo:status'] })(request, response, next);
}
@Post('/')
@Use(passportAuthenticateGithub)
public async callback(req: Request): Promise<AuthenticateResponse> {
const jwt = await createToken(req.user, this.config.jwtSecret);
this.log(`Generated JWT for user ${req.user.username}`);
return {
jwt
};
}
@Get('/logout')
public logout(req: Request, res: Response, next: NextFunction) {
const cookies = req.cookies || {};
for (const cookie in cookies) {
if (!cookies.hasOwnProperty(cookie)) {
continue;
}
res.cookie(cookie, '', { expires: new Date(0) });
}
req.logout();
res.statusCode = 204;
res.end();
}
}
| import { Controller, Get, Use, Post } from '@tsed/common';
import passport from 'passport'; import express from 'express';
import { Request, Response, NextFunction } from 'express';
import { createToken, passportAuthenticateGithub } from '../../middleware/securityMiddleware';
import * as utils from '../../utils';
import Configuration from '../../services/Configuration';
import { AuthenticateResponse } from '@stryker-mutator/dashboard-contract';
@Controller('/auth/github')
export default class GithubAuth {
private readonly log = utils.debug(GithubAuth.name);
constructor(private readonly config: Configuration) {
}
@Get('/')
public get(request: express.Request, response: express.Response, next: express.NextFunction): void {
passport.authenticate('github', { scope: ['user:email', 'read:org'] })(request, response, next);
}
@Post('/')
@Use(passportAuthenticateGithub)
public async callback(req: Request): Promise<AuthenticateResponse> {
const jwt = await createToken(req.user, this.config.jwtSecret);
this.log(`Generated JWT for user ${req.user.username}`);
return {
jwt
};
}
@Get('/logout')
public logout(req: Request, res: Response, next: NextFunction) {
const cookies = req.cookies || {};
for (const cookie in cookies) {
if (!cookies.hasOwnProperty(cookie)) {
continue;
}
res.cookie(cookie, '', { expires: new Date(0) });
}
req.logout();
res.statusCode = 204;
res.end();
}
}
| Remove access to repository from required scopes | Remove access to repository from required scopes
| TypeScript | apache-2.0 | stryker-mutator/stryker-badge,stryker-mutator/stryker-badge,stryker-mutator/stryker-badge,stryker-mutator/stryker-badge | ---
+++
@@ -16,7 +16,7 @@
@Get('/')
public get(request: express.Request, response: express.Response, next: express.NextFunction): void {
- passport.authenticate('github', { scope: ['user:email', 'read:org', 'repo:status'] })(request, response, next);
+ passport.authenticate('github', { scope: ['user:email', 'read:org'] })(request, response, next);
}
@Post('/') |
82a4ba516fa1e6c0337ce9ebeee9e54731d567a6 | src/components/SideNavigator/StorageItem/styled.tsx | src/components/SideNavigator/StorageItem/styled.tsx | import React from 'react'
import styled from '../../../lib/styled'
import { Link, LinkProps } from 'react-router-dom'
export const StyledStorageItem = styled.li`
margin: 0;
padding: 0;
`
export const StyledStorageItemHeader = styled.header`
height: 26px;
display: flex;
`
export const StyledStorageItemFolderList = styled.ul`
padding: 0;
list-style: none;
`
export const StyledStorageItemFolderItem = styled.li`
display: flex;
height: 26px;
`
export const StyledNavLink = styled(
({ active, ...props }: LinkProps & { active: boolean }) => <Link {...props} />
)<{ active: boolean }>`
line-height: 26px;
padding: 0 5px;
text-decoration: none;
width: 100%;
user-select: none;
${({ active, theme }) =>
active && `background-color: ${theme.sideNav.linkActiveBackgroundColor};`}
`
| import React from 'react'
import styled from '../../../lib/styled'
import { LinkProps, Link } from '../../../lib/router'
export const StyledStorageItem = styled.li`
margin: 0;
padding: 0;
`
export const StyledStorageItemHeader = styled.header`
height: 26px;
display: flex;
`
export const StyledStorageItemFolderList = styled.ul`
padding: 0;
list-style: none;
`
export const StyledStorageItemFolderItem = styled.li`
display: flex;
height: 26px;
`
export const StyledNavLink = styled(
({ active, ...props }: LinkProps & { active: boolean }) => <Link {...props} />
)<{ active: boolean }>`
line-height: 26px;
padding: 0 5px;
text-decoration: none;
width: 100%;
user-select: none;
${({ active, theme }) =>
active && `background-color: ${theme.sideNav.linkActiveBackgroundColor};`}
`
| Use custom Link component for SideNav | Use custom Link component for SideNav
| TypeScript | mit | Sarah-Seo/Inpad,Sarah-Seo/Inpad | ---
+++
@@ -1,6 +1,6 @@
import React from 'react'
import styled from '../../../lib/styled'
-import { Link, LinkProps } from 'react-router-dom'
+import { LinkProps, Link } from '../../../lib/router'
export const StyledStorageItem = styled.li`
margin: 0; |
7f49b1e9d6d5a299c34d9eafabda49a073595226 | ui/src/app/loadingbar.ts | ui/src/app/loadingbar.ts | declare function require(name: string): string;
import * as nprogress from "nprogress";
interface IWindow extends Window {
Loadingbar: Loadingbar;
}
export class Loadingbar {
public static Start(): void {
Loadingbar.Instance.Start();
}
public static Inc(): void {
Loadingbar.Instance.Inc();
}
public static Done(): void {
Loadingbar.Instance.Done();
}
private static get Instance() {
// attach this to the window object to make sure that there is really only one.
const w = window as IWindow;
return w.Loadingbar || (w.Loadingbar = new Loadingbar());
}
private Start(): void {
this.loadStylesheet();
nprogress.configure({
minimum: 0.3,
showSpinner: false,
trickleSpeed: 200
});
nprogress.start();
}
private loadStylesheet() {
// tslint:disable:no-submodule-imports
const css = require("nprogress/nprogress.css").toString();
const style: HTMLStyleElement = document.createElement("style");
style.type = "text/css";
style.innerHTML = css;
document.head.appendChild(style);
}
private Inc(): void {
nprogress.inc(0.6);
}
private Done(): void {
nprogress.done();
}
}
| import * as nprogress from "nprogress";
interface IWindow extends Window {
Loadingbar: Loadingbar;
}
export class Loadingbar {
public static Start(): void {
Loadingbar.Instance.Start();
}
public static Inc(): void {
Loadingbar.Instance.Inc();
}
public static Done(): void {
Loadingbar.Instance.Done();
}
private static get Instance() {
// attach this to the window object to make sure that there is really only one.
const w = window as IWindow;
return w.Loadingbar || (w.Loadingbar = new Loadingbar());
}
private Start(): void {
this.loadStylesheet();
nprogress.configure({
minimum: 0.3,
showSpinner: false,
trickleSpeed: 200
});
nprogress.start();
}
private loadStylesheet() {
// tslint:disable:no-submodule-imports
const css = require("nprogress/nprogress.css").toString();
const style: HTMLStyleElement = document.createElement("style");
style.type = "text/css";
style.innerHTML = css;
document.head.appendChild(style);
}
private Inc(): void {
nprogress.inc(0.6);
}
private Done(): void {
nprogress.done();
}
}
| Remove no longer needed declaration. | Remove no longer needed declaration.
| TypeScript | mit | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | ---
+++
@@ -1,4 +1,3 @@
-declare function require(name: string): string;
import * as nprogress from "nprogress";
interface IWindow extends Window { |
e4132180df00f23c34eda638d1f33ed6b17e1991 | test/interactions/helpers/shared.ts | test/interactions/helpers/shared.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {getBrowserAndPages, getTestServerPort, platform} from '../../shared/helper.js';
const fontsByPlatform = {
'mac': 'Helvetica Neue',
'win32': 'Tahoma',
'linux': 'Arial',
};
export const loadComponentDocExample = async (urlComponent: string) => {
const {frontend} = getBrowserAndPages();
const url = new URL(`http://localhost:${getTestServerPort()}/front_end/ui/components/docs/${urlComponent}`);
url.searchParams.set('fontFamily', fontsByPlatform[platform]);
await frontend.goto(url.toString(), {
waitUntil: 'networkidle0',
});
};
const SHOULD_GATHER_COVERAGE_INFORMATION = process.env.COVERAGE === '1';
export const preloadForCodeCoverage = (name: string) => {
if (!SHOULD_GATHER_COVERAGE_INFORMATION) {
return;
}
before(async function() {
this.timeout(0);
const {frontend} = getBrowserAndPages();
await frontend.setExtraHTTPHeaders({
'devtools-compute-coverage': '1',
});
await loadComponentDocExample(name);
await frontend.setExtraHTTPHeaders({});
});
};
| // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {getBrowserAndPages, getTestServerPort, platform} from '../../shared/helper.js';
const fontsByPlatform = {
'mac': 'Helvetica Neue',
'win32': 'Tahoma',
'linux': '"Liberation Sans"',
};
export const loadComponentDocExample = async (urlComponent: string) => {
const {frontend} = getBrowserAndPages();
const url = new URL(`http://localhost:${getTestServerPort()}/front_end/ui/components/docs/${urlComponent}`);
url.searchParams.set('fontFamily', fontsByPlatform[platform]);
await frontend.goto(url.toString(), {
waitUntil: 'networkidle0',
});
};
const SHOULD_GATHER_COVERAGE_INFORMATION = process.env.COVERAGE === '1';
export const preloadForCodeCoverage = (name: string) => {
if (!SHOULD_GATHER_COVERAGE_INFORMATION) {
return;
}
before(async function() {
this.timeout(0);
const {frontend} = getBrowserAndPages();
await frontend.setExtraHTTPHeaders({
'devtools-compute-coverage': '1',
});
await loadComponentDocExample(name);
await frontend.setExtraHTTPHeaders({});
});
};
| Set linux font for interaction tests to Liberation Sans | Set linux font for interaction tests to Liberation Sans
This font is shared between gLinux and the bots.
Bug: none;
Change-Id: I4a69bce005e876502130661e2844037638069b2d
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3168265
Reviewed-by: Paul Lewis <8915f5d5c39a08c5a3e8a8d7314756e4580816f9@chromium.org>
Commit-Queue: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -7,7 +7,7 @@
const fontsByPlatform = {
'mac': 'Helvetica Neue',
'win32': 'Tahoma',
- 'linux': 'Arial',
+ 'linux': '"Liberation Sans"',
};
export const loadComponentDocExample = async (urlComponent: string) => { |
fa372100d0ce68612df90f6f0e06c9cc58e37160 | src/fe/utils/text.ts | src/fe/utils/text.ts | import {LangId, MultiLangStringSet} from "../../definitions/auxillary/MultiLang"
import {store} from "../main"
const fallbackLangList: LangId[] = ["en", "fr"]
export function text(
s: MultiLangStringSet | string | null | undefined,
lang: LangId = store.getState().ui.lang,
fallbackLangs = fallbackLangList): string {
if (s === null || typeof s === "undefined") {
return ''
}
else if (typeof s === "string") {
console.warn("Getting raw without multilang support:", s)
return s
}
else {
const translation = s[lang]
if (translation) {
return translation
}
else {
for (let lang of fallbackLangs) {
let translation = s[lang]
if (translation) {
return translation
}
}
}
}
console.warn("Cannot convert to text: ", s)
return ''
}
export default text
| import {LangId, MultiLangStringSet} from "../../definitions/auxillary/MultiLang"
import {store} from "../main"
const fallbackLangList: LangId[] = ["en", "fr", "zh_hans"]
export function text(
s: MultiLangStringSet | string | null | undefined,
lang: LangId = store.getState().ui.lang,
fallbackLangs = fallbackLangList): string {
if (s === null || typeof s === "undefined") {
return ''
}
else if (typeof s === "string") {
console.warn("Getting raw without multilang support:", s)
return s
}
else {
const translation = s[lang]
if (translation) {
return translation
}
else {
for (let lang of fallbackLangs) {
let translation = s[lang]
if (translation) {
return translation
}
}
}
}
console.warn("Cannot convert to text: ", s)
return ''
}
export default text
| Add simplified Chinese to fallback list | Add simplified Chinese to fallback list
Signed-off-by: Andy Shu <d9a5ae79e0620530e640970c782273ccd89702f2@gmail.com>
| TypeScript | agpl-3.0 | wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate,wikimigrate/wikimigrate | ---
+++
@@ -1,7 +1,7 @@
import {LangId, MultiLangStringSet} from "../../definitions/auxillary/MultiLang"
import {store} from "../main"
-const fallbackLangList: LangId[] = ["en", "fr"]
+const fallbackLangList: LangId[] = ["en", "fr", "zh_hans"]
export function text(
s: MultiLangStringSet | string | null | undefined, |
efb8c2867c089e62593b98100bd6d84b1b5b0012 | src/api/resources/rest/data.ts | src/api/resources/rest/data.ts | import * as Rx from 'rx';
import {RESTResource} from './rest_resource';
import {Connection} from '../../connection';
import {Permissionable, getPermissions, setPermissions} from '../addons/permissions';
import * as types from '../../types/rest';
/**
* Data resource class for dealing with data endpoint.
*/
export class DataResource extends RESTResource<types.Data> implements Permissionable {
constructor(connection: Connection) {
super('data', connection);
}
/**
* Checks if data slug already exists.
*
* @param {string} Slug to check
* @return {Rx.Observable<boolean>} An observable that emits the response
*/
public slugExists(slug: string): Rx.Observable<boolean> {
return <Rx.Observable<boolean>> this.connection.get(this.getListMethodPath('slug_exists'), { name: slug });
}
/**
* Get Data object if similar already exists, otherwise create it.
*
* @param data Object attributes
* @return An observable that emits the response
*/
public getOrCreate(data: Object): Rx.Observable<types.Data> {
return this.connection.post<types.Data>(this.getListMethodPath('get_or_create'), data);
}
public getPermissions(id: number): Rx.Observable<types.ItemPermissions[]> {
return getPermissions(this, id);
}
public setPermissions(id: number, permissions: types.SetPermissionsRequest): Rx.Observable<types.ItemPermissions[]> {
return setPermissions(this, id, permissions);
}
}
| import * as Rx from 'rx';
import {RESTResource} from './rest_resource';
import {Connection} from '../../connection';
import {Permissionable, getPermissions, setPermissions} from '../addons/permissions';
import * as types from '../../types/rest';
/**
* Data resource class for dealing with data endpoint.
*/
export class DataResource extends RESTResource<types.Data> implements Permissionable {
constructor(connection: Connection) {
super('data', connection);
}
/**
* Checks if data slug already exists.
*
* @param {string} Slug to check
* @return {Rx.Observable<boolean>} An observable that emits the response
*/
public slugExists(slug: string): Rx.Observable<boolean> {
return <Rx.Observable<boolean>> this.connection.get(this.getListMethodPath('slug_exists'), { name: slug });
}
/**
* Get Data object with the same inputs if it already exists, otherwise
* create it.
*
* Note: Consider sorting arrays in the inputs, to prevent needlessly
* creating the same Data objects.
*/
public getOrCreate(data: Object): Rx.Observable<types.Data> {
return this.connection.post<types.Data>(this.getListMethodPath('get_or_create'), data);
}
public getPermissions(id: number): Rx.Observable<types.ItemPermissions[]> {
return getPermissions(this, id);
}
public setPermissions(id: number, permissions: types.SetPermissionsRequest): Rx.Observable<types.ItemPermissions[]> {
return setPermissions(this, id, permissions);
}
}
| Add a note about sorting inputs in Data.getOrCreate | Add a note about sorting inputs in Data.getOrCreate
| TypeScript | apache-2.0 | hadalin/resolwe-js,hadalin/resolwe-js,genialis/resolwe-js,genialis/resolwe-js | ---
+++
@@ -25,10 +25,11 @@
}
/**
- * Get Data object if similar already exists, otherwise create it.
+ * Get Data object with the same inputs if it already exists, otherwise
+ * create it.
*
- * @param data Object attributes
- * @return An observable that emits the response
+ * Note: Consider sorting arrays in the inputs, to prevent needlessly
+ * creating the same Data objects.
*/
public getOrCreate(data: Object): Rx.Observable<types.Data> {
return this.connection.post<types.Data>(this.getListMethodPath('get_or_create'), data); |
15da0fa8044c564873be4972759814404947aa44 | packages/mongoose/src/decorators/schemaIgnore.ts | packages/mongoose/src/decorators/schemaIgnore.ts | import {Schema} from "@tsed/mongoose";
/**
* Do not apply this property to schema (create virtual property)
*
* ### Example
*
* ```typescript
* @Model()
* @SchemaIgnore()
* @Property()
* kind: string;
*
* ```
*
* @returns {Function}
* @decorator
* @mongoose
* @class
*/
export function SchemaIgnore(): Function {
return Schema({schemaIgnore: true});
}
| import {Schema} from "./schema";
/**
* Do not apply this property to schema (create virtual property)
*
* ### Example
*
* ```typescript
* @Model()
* @SchemaIgnore()
* @Property()
* kind: string;
*
* ```
*
* @returns {Function}
* @decorator
* @mongoose
* @class
*/
export function SchemaIgnore(): Function {
return Schema({schemaIgnore: true});
}
| Fix automatic import to lib style | Fix automatic import to lib style
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,4 +1,4 @@
-import {Schema} from "@tsed/mongoose";
+import {Schema} from "./schema";
/**
* Do not apply this property to schema (create virtual property) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.