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
|
---|---|---|---|---|---|---|---|---|---|---|
c456248294415fec6542897b7fddd7e5c491fffb | src/app/models/workout.ts | src/app/models/workout.ts | import { Tag } from './tag';
import { Sport } from './sport';
import { Address } from './address';
import { Image } from './image';
export class Workout {
public id: number;
public startdate: Date;
public enddate: Date;
public duration: string;
public placeType: string;
public nbTicketAvailable: number;
public nbTicketBooked: number;
public soldOut: boolean;
public price: number;
public coach: number;
public sport: any;
public soloTraining: boolean;
public subsport: string;
public difficulty: string;
public notation: number;
public address: any;
public description: string;
public tags: any[];
public addedExistingTags: Tag[];
public addedNewTags: Tag[];
public title: string;
public photo: any;
public favorite: boolean;
constructor(
) {
this.sport = new Sport();
this.address = new Address();
this.startdate = new Date();
this.enddate = new Date();
this.tags = new Array();
this.addedExistingTags = new Array();
this.addedNewTags = new Array();
this.photo = new Image();
}
}
| import { Tag } from './tag';
import { Sport } from './sport';
import { Address } from './address';
import { Image } from './image';
export class Workout {
public id: number;
public startdate: Date;
public enddate: Date;
public duration: string;
public placeType: string;
public nbTicketAvailable: number;
public nbTicketBooked: number;
public soldOut: boolean;
public price: number;
public coach: number;
public sport: any;
public soloTraining: boolean;
public subsport: string;
public difficulty: string;
public notation: number;
public address: any;
public description: string;
public outfit: string;
public notice: string;
public tags: any[];
public addedExistingTags: Tag[];
public addedNewTags: Tag[];
public title: string;
public photo: any;
public favorite: boolean;
constructor(
) {
this.sport = new Sport();
this.address = new Address();
this.startdate = new Date();
this.enddate = new Date();
this.tags = new Array();
this.addedExistingTags = new Array();
this.addedNewTags = new Array();
this.photo = new Image();
}
}
| Add new attributes to give more information to user | Add new attributes to give more information to user
| TypeScript | mit | XavierGuichet/bemoove-front,XavierGuichet/bemoove-front,XavierGuichet/bemoove-front | ---
+++
@@ -21,6 +21,8 @@
public notation: number;
public address: any;
public description: string;
+ public outfit: string;
+ public notice: string;
public tags: any[];
public addedExistingTags: Tag[];
public addedNewTags: Tag[]; |
eb2dcd559d3af878626c261c07494270f5c12ff7 | extensions/TLDRPages/src/PageDatabase.jest.ts | extensions/TLDRPages/src/PageDatabase.jest.ts | /*
* Copyright 2020 Simon Edwards <[email protected]>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import { PageDatabase } from "./PageDatabase.js";
test("Scan", async () => {
const db = new PageDatabase("./data/pages");
await db.loadIndex();
const commandNames = db.getCommandNames();
expect(commandNames).not.toBe(0);
expect(commandNames.indexOf("ack")).not.toBe(-1);
const info = await db.getPageInfoByName("cd", "windows");
expect(info.examples.length).toBe(4);
expect(info.examples[0].commandLine).toMatch(/^[^`].*[^`]$/);
expect(info.examples[0].description).toMatch(/^.*[^:]$/);
});
| /*
* Copyright 2020 Simon Edwards <[email protected]>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import { PageDatabase } from "./PageDatabase.js";
test("Scan", async () => {
const db = new PageDatabase("./data/pages");
await db.loadIndex();
const commandNames = db.getCommandNames();
expect(commandNames).not.toBe(0);
expect(commandNames.indexOf("ack")).not.toBe(-1);
const info = await db.getPageInfoByName("cd", "windows");
expect(info.examples.length).toBe(5);
expect(info.examples[0].commandLine).toMatch(/^[^`].*[^`]$/);
expect(info.examples[0].description).toMatch(/^.*[^:]$/);
});
| Update a unit test because the TL;DR database changed slighty | Update a unit test because the TL;DR database changed slighty
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -17,7 +17,7 @@
const info = await db.getPageInfoByName("cd", "windows");
- expect(info.examples.length).toBe(4);
+ expect(info.examples.length).toBe(5);
expect(info.examples[0].commandLine).toMatch(/^[^`].*[^`]$/);
expect(info.examples[0].description).toMatch(/^.*[^:]$/);
}); |
62094499f6ad6b48229f06201b4c5fefee560c23 | functions/src/twitter/firestore-data.ts | functions/src/twitter/firestore-data.ts | export interface Tweet {
id: string
text: string
createdAt: Date
displayTextRange: [number, number]
user: User
entities: {
hashtags: Hashtag[]
media: Media[]
urls: Url[]
userMentions: UserMention[]
}
}
export interface User {
id: string
name: string
screenName: string
profileImageUrl: string
}
export interface Hashtag {
start: number
end: number
text: string
}
export interface Media {
displayUrl: string
start: number
end: number
id: string
mediaUrl: string
expandedUrl: string
type: "photo"
url: string
}
export interface Url {
displayUrl: string
url: string
expandedUrl: string
start: number
end: number
}
export interface UserMention {
start: number
end: number
id: string
name: string
screenName: string
}
| export interface FirestoreTweet {
id: string
text: string
createdAt: Date
displayTextRange: [number, number]
user: FirestoreUser
entities: {
hashtags: FirestoreHashtag[]
media: FirestoreMedia[]
urls: FirestoreUrl[]
userMentions: FirestoreUserMention[]
}
}
export interface FirestoreUser {
id: string
name: string
screenName: string
profileImageUrl: string
}
export interface FirestoreHashtag {
start: number
end: number
text: string
}
export interface FirestoreMedia {
displayUrl: string
start: number
end: number
id: string
mediaUrl: string
expandedUrl: string
type: string
url: string
}
export interface FirestoreUrl {
displayUrl: string
url: string
expandedUrl: string
start: number
end: number
}
export interface FirestoreUserMention {
start: number
end: number
id: string
name: string
screenName: string
}
| Tweak Twitter Firestore model names | Tweak Twitter Firestore model names
| TypeScript | apache-2.0 | squanchy-dev/squanchy-firebase,squanchy-dev/squanchy-firebase | ---
+++
@@ -1,42 +1,42 @@
-export interface Tweet {
+export interface FirestoreTweet {
id: string
text: string
createdAt: Date
displayTextRange: [number, number]
- user: User
+ user: FirestoreUser
entities: {
- hashtags: Hashtag[]
- media: Media[]
- urls: Url[]
- userMentions: UserMention[]
+ hashtags: FirestoreHashtag[]
+ media: FirestoreMedia[]
+ urls: FirestoreUrl[]
+ userMentions: FirestoreUserMention[]
}
}
-export interface User {
+export interface FirestoreUser {
id: string
name: string
screenName: string
profileImageUrl: string
}
-export interface Hashtag {
+export interface FirestoreHashtag {
start: number
end: number
text: string
}
-export interface Media {
+export interface FirestoreMedia {
displayUrl: string
start: number
end: number
id: string
mediaUrl: string
expandedUrl: string
- type: "photo"
+ type: string
url: string
}
-export interface Url {
+export interface FirestoreUrl {
displayUrl: string
url: string
expandedUrl: string
@@ -44,7 +44,7 @@
end: number
}
-export interface UserMention {
+export interface FirestoreUserMention {
start: number
end: number
id: string |
713bc3281fe491dfafc65b2b15b497422a75d206 | src/xrm-mock/organizationsettings/organizationsettings.mock.ts | src/xrm-mock/organizationsettings/organizationsettings.mock.ts | export class OrganizationSettingsMock implements Xrm.OrganizationSettings {
public baseCurrencyId: string;
public defaultCountryCode: string;
public isAutoSaveEnabled: boolean;
public languageId: number;
public organizationId: string;
public uniqueName: string;
public useSkypeProtocol: boolean;
constructor(components: IOrganizationSettingsComponents) {
this.baseCurrencyId = components.baseCurrencyId;
this.defaultCountryCode = components.defaultCountryCode;
this.isAutoSaveEnabled = components.isAutoSaveEnabled;
this.languageId = components.languageId;
this.organizationId = components.organizationId;
this.uniqueName = components.uniqueName;
this.useSkypeProtocol = components.useSkypeProtocol;
}
}
export interface IOrganizationSettingsComponents {
baseCurrencyId?: string;
defaultCountryCode?: string;
isAutoSaveEnabled?: boolean;
languageId?: number;
organizationId?: string;
uniqueName?: string;
useSkypeProtocol?: boolean;
}
| export class OrganizationSettingsMock implements Xrm.OrganizationSettings {
public baseCurrencyId: string;
public defaultCountryCode: string;
public isAutoSaveEnabled: boolean;
public languageId: number;
public organizationId: string;
public uniqueName: string;
public useSkypeProtocol: boolean;
public baseCurrency: Xrm.LookupValue;
public attributes: any;
constructor(components: IOrganizationSettingsComponents) {
this.baseCurrencyId = components.baseCurrencyId;
this.defaultCountryCode = components.defaultCountryCode;
this.isAutoSaveEnabled = components.isAutoSaveEnabled;
this.languageId = components.languageId;
this.organizationId = components.organizationId;
this.uniqueName = components.uniqueName;
this.useSkypeProtocol = components.useSkypeProtocol;
this.baseCurrency = components.baseCurrency;
this.attributes = components.attributes;
}
}
export interface IOrganizationSettingsComponents {
baseCurrencyId?: string;
defaultCountryCode?: string;
isAutoSaveEnabled?: boolean;
languageId?: number;
organizationId?: string;
uniqueName?: string;
useSkypeProtocol?: boolean;
baseCurrency?: Xrm.LookupValue;
attributes?: any;
}
| Add missing properties in getGlobalContext.organizationSettings | Add missing properties in getGlobalContext.organizationSettings
| TypeScript | mit | camelCaseDave/xrm-mock,camelCaseDave/xrm-mock | ---
+++
@@ -6,6 +6,8 @@
public organizationId: string;
public uniqueName: string;
public useSkypeProtocol: boolean;
+ public baseCurrency: Xrm.LookupValue;
+ public attributes: any;
constructor(components: IOrganizationSettingsComponents) {
this.baseCurrencyId = components.baseCurrencyId;
@@ -15,6 +17,8 @@
this.organizationId = components.organizationId;
this.uniqueName = components.uniqueName;
this.useSkypeProtocol = components.useSkypeProtocol;
+ this.baseCurrency = components.baseCurrency;
+ this.attributes = components.attributes;
}
}
@@ -26,4 +30,6 @@
organizationId?: string;
uniqueName?: string;
useSkypeProtocol?: boolean;
+ baseCurrency?: Xrm.LookupValue;
+ attributes?: any;
} |
394ebd8b7ac2a8ee96475372fc458858c8e44974 | src/graphql/GraphQLUser.ts | src/graphql/GraphQLUser.ts | import {
UserProfileType,
} from './GraphQLUserProfile'
import {
CVType,
} from './GraphQLCV'
import {
GraphQLObjectType,
} from 'graphql'
import {
CVActions,
CVActionsImpl,
} from './../controllers'
const cvCtrl: CVActions = new CVActionsImpl()
export const UserType = new GraphQLObjectType({
name : 'User',
fields : {
profile: { type: UserProfileType },
cv: {
type: CVType,
resolve(user, b, { req }) {
return cvCtrl.getCV(user.id)
},
},
},
})
| import {
UserProfileType,
} from './GraphQLUserProfile'
import {
CVType,
} from './GraphQLCV'
import {
GraphQLObjectType,
} from 'graphql'
import {
CVActions,
CVActionsImpl,
} from './../controllers'
const cvCtrl: CVActions = new CVActionsImpl()
export const UserType = new GraphQLObjectType({
name : 'User',
fields : {
profile: { type: UserProfileType },
cv: {
type: CVType,
resolve(user, b, { req }) {
return req.isAuthenticated()
? cvCtrl.getCV(user.id)
: undefined
},
},
},
})
| Return null for cv if not authenticated | Return null for cv if not authenticated
| TypeScript | mit | studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord,studieresan/overlord | ---
+++
@@ -21,7 +21,9 @@
cv: {
type: CVType,
resolve(user, b, { req }) {
- return cvCtrl.getCV(user.id)
+ return req.isAuthenticated()
+ ? cvCtrl.getCV(user.id)
+ : undefined
},
},
}, |
f7f09115bd49172f9869e2910eff055b544b63aa | app/src/ui/preferences/advanced.tsx | app/src/ui/preferences/advanced.tsx | import * as React from 'react'
import { Dispatcher } from '../../lib/dispatcher'
import { DialogContent } from '../dialog'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
interface IAdvancedPreferencesProps {
readonly dispatcher: Dispatcher
}
interface IAdvancedPreferencesState {
readonly reportingOptOut: boolean,
}
export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> {
public constructor(props: IAdvancedPreferencesProps) {
super(props)
this.state = {
reportingOptOut: false,
}
}
public componentDidMount() {
const optOut = this.props.dispatcher.getStatsOptOut()
this.setState({
reportingOptOut: optOut,
})
}
private onChange = (event: React.FormEvent<HTMLInputElement>) => {
const value = event.currentTarget.checked
this.props.dispatcher.setStatsOptOut(!value)
this.setState({
reportingOptOut: !value,
})
}
public render() {
return (
<DialogContent>
<Checkbox
label='Opt-out of usage reporting'
value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On}
onChange={this.onChange} />
</DialogContent>
)
}
}
| import * as React from 'react'
import { Dispatcher } from '../../lib/dispatcher'
import { DialogContent } from '../dialog'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
import { LinkButton } from '../lib/link-button'
interface IAdvancedPreferencesProps {
readonly dispatcher: Dispatcher
}
interface IAdvancedPreferencesState {
readonly reportingOptOut: boolean,
}
const SamplesURL = 'https://desktop.github.com/samples/'
export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> {
public constructor(props: IAdvancedPreferencesProps) {
super(props)
this.state = {
reportingOptOut: false,
}
}
public componentDidMount() {
const optOut = this.props.dispatcher.getStatsOptOut()
this.setState({
reportingOptOut: optOut,
})
}
private onChange = (event: React.FormEvent<HTMLInputElement>) => {
const value = event.currentTarget.checked
this.props.dispatcher.setStatsOptOut(!value)
this.setState({
reportingOptOut: !value,
})
}
public render() {
return (
<DialogContent>
<div>
Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>?
</div>
<Checkbox
label='Yes, submit anonymized usage data'
value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On}
onChange={this.onChange} />
</DialogContent>
)
}
}
| Make label text make sense | Make label text make sense
| TypeScript | mit | shiftkey/desktop,hjobrien/desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,artivilla/desktop,gengjiawen/desktop,gengjiawen/desktop,BugTesterTest/desktops,desktop/desktop,desktop/desktop,hjobrien/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,BugTesterTest/desktops,j-f1/forked-desktop,say25/desktop,gengjiawen/desktop,desktop/desktop,BugTesterTest/desktops,kactus-io/kactus,hjobrien/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,j-f1/forked-desktop,hjobrien/desktop,artivilla/desktop,shiftkey/desktop | ---
+++
@@ -2,6 +2,7 @@
import { Dispatcher } from '../../lib/dispatcher'
import { DialogContent } from '../dialog'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
+import { LinkButton } from '../lib/link-button'
interface IAdvancedPreferencesProps {
readonly dispatcher: Dispatcher
@@ -10,6 +11,8 @@
interface IAdvancedPreferencesState {
readonly reportingOptOut: boolean,
}
+
+const SamplesURL = 'https://desktop.github.com/samples/'
export class Advanced extends React.Component<IAdvancedPreferencesProps, IAdvancedPreferencesState> {
public constructor(props: IAdvancedPreferencesProps) {
@@ -41,8 +44,12 @@
public render() {
return (
<DialogContent>
+ <div>
+ Would you like to help us improve GitHub Desktop by periodically submitting <LinkButton uri={SamplesURL}>anonymous usage data</LinkButton>?
+ </div>
+
<Checkbox
- label='Opt-out of usage reporting'
+ label='Yes, submit anonymized usage data'
value={this.state.reportingOptOut ? CheckboxValue.Off : CheckboxValue.On}
onChange={this.onChange} />
</DialogContent> |
8b1e28d6e9a440ff1b1538d3754d0e43e02cc18a | src/v2/Apps/Consign/Routes/SubmissionFlow/ThankYou/ThankYou.tsx | src/v2/Apps/Consign/Routes/SubmissionFlow/ThankYou/ThankYou.tsx | import { FC } from "react";
import { Button, Flex, Text, Spacer, Box } from "@artsy/palette"
import { FAQ } from "../../MarketingLanding/Components/FAQ"
import { SoldRecentlyQueryRenderer } from "../../MarketingLanding/Components/SoldRecently"
import { RouterLink } from "v2/System/Router/RouterLink"
export const ThankYou: FC = () => {
return (
<>
<Text variant="xxl" mt={4}>
Thank you for submitting a work
</Text>
<Box maxWidth="720px" mt={4}>
<Text variant="lg">
We’ll email you within 1–3 business days to let you know the status of
your submission.
</Text>
<Text variant="lg" mt={2}>
In the meantime, feel free to submit another work—and benefit from
Artsy’s low fees, informed pricing, and multiple selling options.
</Text>
</Box>
<Flex py={[2, 4]} mt={4} alignItems="center">
<RouterLink to="/consign/submission2">
<Button
data-test-id="submit-another-work"
size="medium"
variant="primaryBlack"
>
Submit Another Work
</Button>
</RouterLink>
<RouterLink to="/" ml={150} data-test-id="go-to-artsy-homepage">
Back to Artsy Homepage
</RouterLink>
</Flex>
<SoldRecentlyQueryRenderer />
<Spacer mt={6} />
<FAQ />
</>
)
}
| import { Button, Flex, Text, Spacer, Box } from "@artsy/palette"
import { FAQ } from "../../MarketingLanding/Components/FAQ"
import { SoldRecentlyQueryRenderer } from "../../MarketingLanding/Components/SoldRecently"
import { RouterLink } from "v2/System/Router/RouterLink"
export const ThankYou: React.FC = () => {
return (
<>
<Text variant="xxl" mt={4}>
Thank you for submitting a work
</Text>
<Box maxWidth="720px" mt={4}>
<Text variant="lg">
We’ll email you within 1–3 business days to let you know the status of
your submission.
</Text>
<Text variant="lg" mt={2}>
In the meantime, feel free to submit another work—and benefit from
Artsy’s low fees, informed pricing, and multiple selling options.
</Text>
</Box>
<Flex py={[2, 4]} mt={4} alignItems="center">
<RouterLink to="/consign/submission2/artwork-details">
<Button
data-test-id="submit-another-work"
size="medium"
variant="primaryBlack"
>
Submit Another Work
</Button>
</RouterLink>
<RouterLink to="/" ml={150} data-test-id="go-to-artsy-homepage">
Back to Artsy Homepage
</RouterLink>
</Flex>
<SoldRecentlyQueryRenderer />
<Spacer mt={6} />
<FAQ />
</>
)
}
| Fix pageview event double fires | Fix pageview event double fires
| TypeScript | mit | artsy/force-public,artsy/force,artsy/force,artsy/force,artsy/force-public,artsy/force | ---
+++
@@ -1,10 +1,9 @@
-import { FC } from "react";
import { Button, Flex, Text, Spacer, Box } from "@artsy/palette"
import { FAQ } from "../../MarketingLanding/Components/FAQ"
import { SoldRecentlyQueryRenderer } from "../../MarketingLanding/Components/SoldRecently"
import { RouterLink } from "v2/System/Router/RouterLink"
-export const ThankYou: FC = () => {
+export const ThankYou: React.FC = () => {
return (
<>
<Text variant="xxl" mt={4}>
@@ -22,7 +21,7 @@
</Box>
<Flex py={[2, 4]} mt={4} alignItems="center">
- <RouterLink to="/consign/submission2">
+ <RouterLink to="/consign/submission2/artwork-details">
<Button
data-test-id="submit-another-work"
size="medium" |
0d84e5b5bf4cbd198a80e51979552980d2c28fc5 | 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';
import { User } from './models/user.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user: User = new User('Godson', '[email protected]', '+234-809-613-2999');
constructor() {}
}
| Create user model for Demo | chore(User): Create user model for Demo
| TypeScript | mit | gottsohn/md-input-inline,gottsohn/md-input-inline,gottsohn/md-input-inline | ---
+++
@@ -1,10 +1,13 @@
import { Component } from '@angular/core';
+import { User } from './models/user.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
+
export class AppComponent {
- title = 'app works!';
+ user: User = new User('Godson', '[email protected]', '+234-809-613-2999');
+ constructor() {}
} |
eb73d9d45efaa8f6daef2a6fbae7afd25b8dd378 | client/Encounter/UpdateLegacySavedEncounter.ts | client/Encounter/UpdateLegacySavedEncounter.ts | import { CombatantState } from "../../common/CombatantState";
import { EncounterState } from "../../common/EncounterState";
import { probablyUniqueString } from "../../common/Toolbox";
function updateLegacySavedCreature(savedCreature: any) {
if (!savedCreature.StatBlock) {
savedCreature.StatBlock = savedCreature["Statblock"];
}
if (!savedCreature.Id) {
savedCreature.Id = probablyUniqueString();
}
if (savedCreature.MaxHP) {
savedCreature.StatBlock.HP.Value = savedCreature.MaxHP;
}
}
export function UpdateLegacySavedEncounter(
savedEncounter: any
): EncounterState<CombatantState> {
savedEncounter.Combatants =
savedEncounter.Combatants || savedEncounter.Creatures;
savedEncounter.ActiveCombatantId =
savedEncounter.ActiveCombatantId || savedEncounter.ActiveCreatureId;
savedEncounter.Path = savedEncounter.Path || "";
savedEncounter.Combatants.forEach(updateLegacySavedCreature);
const legacyCombatantIndex = savedEncounter.ActiveCreatureIndex;
if (legacyCombatantIndex !== undefined && legacyCombatantIndex != -1) {
savedEncounter.ActiveCombatantId =
savedEncounter.Combatants[legacyCombatantIndex].Id;
}
return savedEncounter;
}
| import { CombatantState } from "../../common/CombatantState";
import { EncounterState } from "../../common/EncounterState";
import { probablyUniqueString } from "../../common/Toolbox";
import { AccountClient } from "../Account/AccountClient";
function updateLegacySavedCreature(savedCreature: any) {
if (!savedCreature.StatBlock) {
savedCreature.StatBlock = savedCreature["Statblock"];
}
if (!savedCreature.Id) {
savedCreature.Id = probablyUniqueString();
}
if (savedCreature.MaxHP) {
savedCreature.StatBlock.HP.Value = savedCreature.MaxHP;
}
}
export function UpdateLegacySavedEncounter(
savedEncounter: any
): EncounterState<CombatantState> {
savedEncounter.Combatants =
savedEncounter.Combatants || savedEncounter.Creatures;
savedEncounter.ActiveCombatantId =
savedEncounter.ActiveCombatantId || savedEncounter.ActiveCreatureId;
savedEncounter.Path = savedEncounter.Path || "";
savedEncounter.Id =
savedEncounter.Id ||
AccountClient.MakeId(savedEncounter.Name || probablyUniqueString());
savedEncounter.Combatants.forEach(updateLegacySavedCreature);
const legacyCombatantIndex = savedEncounter.ActiveCreatureIndex;
if (legacyCombatantIndex !== undefined && legacyCombatantIndex != -1) {
savedEncounter.ActiveCombatantId =
savedEncounter.Combatants[legacyCombatantIndex].Id;
}
return savedEncounter;
}
| Apply Id if SavedEncounter is missing one | Apply Id if SavedEncounter is missing one
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,6 +1,7 @@
import { CombatantState } from "../../common/CombatantState";
import { EncounterState } from "../../common/EncounterState";
import { probablyUniqueString } from "../../common/Toolbox";
+import { AccountClient } from "../Account/AccountClient";
function updateLegacySavedCreature(savedCreature: any) {
if (!savedCreature.StatBlock) {
@@ -22,6 +23,9 @@
savedEncounter.ActiveCombatantId =
savedEncounter.ActiveCombatantId || savedEncounter.ActiveCreatureId;
savedEncounter.Path = savedEncounter.Path || "";
+ savedEncounter.Id =
+ savedEncounter.Id ||
+ AccountClient.MakeId(savedEncounter.Name || probablyUniqueString());
savedEncounter.Combatants.forEach(updateLegacySavedCreature);
|
2d4d8626f2a03e3101d48ea79f07be6c127bcae6 | coffee-chats/src/main/webapp/src/util/fetch.ts | coffee-chats/src/main/webapp/src/util/fetch.ts | import React from "react";
interface ResponseRaceDetect {
response: Response;
json: any;
raceOccurred: boolean;
}
const fetchAndDetectRaces: (url: string) => Promise<ResponseRaceDetect> = (() => {
let requestId = 0;
return async (url: string) => {
const currentRequestId = ++requestId;
const response = await fetch(url);
const json = await response.json();
const raceOccurred = requestId != currentRequestId;
return {response, json, raceOccurred};
}
})();
/**
* A hook that fetches JSON data from a URL using a GET request
*
* @param url: URL to fetch data from
*/
export function useFetch(url: string): any {
const [data, setData] = React.useState(null);
React.useEffect(() => {
(async () => {
const {response, json, raceOccurred} = await fetchAndDetectRaces(url);
if (raceOccurred) {
return;
}
if (!response.ok && json.loginUrl) {
window.location.href = json.loginUrl;
} else {
setData(json);
}
})();
}, [url]);
return data;
}
| import React from "react";
/**
* A hook that fetches JSON data from a URL using a GET request
*
* @param url: URL to fetch data from
*/
export function useFetch(url: string): any {
const [data, setData] = React.useState(null);
const requestId = React.useRef(0);
React.useEffect(() => {
(async () => {
const currentRequestId = ++requestId.current;
const response = await fetch(url);
const json = await response.json();
const raceOccurred = requestId.current !== currentRequestId;
if (raceOccurred) {
return;
}
if (!response.ok && json.loginUrl) {
window.location.href = json.loginUrl;
} else {
setData(json);
}
})();
}, [url]);
return data;
}
| Use useRef for race detection in useFetch | Use useRef for race detection in useFetch
| TypeScript | apache-2.0 | googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020,googleinterns/step250-2020 | ---
+++
@@ -1,24 +1,4 @@
import React from "react";
-
-interface ResponseRaceDetect {
- response: Response;
- json: any;
- raceOccurred: boolean;
-}
-
-const fetchAndDetectRaces: (url: string) => Promise<ResponseRaceDetect> = (() => {
- let requestId = 0;
-
- return async (url: string) => {
- const currentRequestId = ++requestId;
-
- const response = await fetch(url);
- const json = await response.json();
- const raceOccurred = requestId != currentRequestId;
-
- return {response, json, raceOccurred};
- }
-})();
/**
* A hook that fetches JSON data from a URL using a GET request
@@ -27,10 +7,14 @@
*/
export function useFetch(url: string): any {
const [data, setData] = React.useState(null);
+ const requestId = React.useRef(0);
React.useEffect(() => {
(async () => {
- const {response, json, raceOccurred} = await fetchAndDetectRaces(url);
+ const currentRequestId = ++requestId.current;
+ const response = await fetch(url);
+ const json = await response.json();
+ const raceOccurred = requestId.current !== currentRequestId;
if (raceOccurred) {
return; |
ac671654c98c60ae736db51dcaed3c7c073c1198 | apps/ui-tests-app/nordic/nordic.ts | apps/ui-tests-app/nordic/nordic.ts | var vmModule = require("./main-view-model");
function pageLoaded(args) {
var page = args.object;
page.getViewById("label").text = "æøå";
}
exports.pageLoaded = pageLoaded; | function pageLoaded(args) {
var page = args.object;
page.getViewById("label").text = "æøå";
}
exports.pageLoaded = pageLoaded; | Remove unnecessary require in ui-tests-app. | Remove unnecessary require in ui-tests-app.
| TypeScript | mit | NativeScript/NativeScript,NativeScript/NativeScript,NativeScript/NativeScript,NativeScript/NativeScript,NativeScript/NativeScript,hdeshev/NativeScript,hdeshev/NativeScript,hdeshev/NativeScript | ---
+++
@@ -1,5 +1,4 @@
-var vmModule = require("./main-view-model");
-function pageLoaded(args) {
+function pageLoaded(args) {
var page = args.object;
page.getViewById("label").text = "æøå";
} |
b6b49f736fa3f4d72e3ec7909a2332562da0a436 | response-time/response-time-tests.ts | response-time/response-time-tests.ts |
import express = require('express');
import responseTime = require('response-time');
var app = express();
app.use(responseTime());
app.use(responseTime({
digits: 3,
header: 'X-Response-Time',
suffix: true
}));
| import responseTime = require('response-time');
////////////////////////////////////////////////////////////////////////////////////
// expressconnect tests https://github.com/expressjs/response-time#expressconnect //
////////////////////////////////////////////////////////////////////////////////////
import express = require('express')
namespace express_connect_tests {
const app = express()
app.use(responseTime())
}
//////////////////////////////////////////////////////////////////////////////////////////////
// vanilla http server tests https://github.com/expressjs/response-time#vanilla-http-server //
//////////////////////////////////////////////////////////////////////////////////////////////
import http = require('http')
namespace vanilla_http_server_tests {
// create "middleware"
var _responseTime = responseTime()
http.createServer(function (req, res) {
_responseTime(req, res, function (err) {
if (err) return console.log(err);
// respond to request
res.setHeader('content-type', 'text/plain')
res.end('hello, world!')
})
})
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// response time metrics tests https://github.com/expressjs/response-time#response-time-metrics //
//////////////////////////////////////////////////////////////////////////////////////////////////
namespace response_time_metrics_tests {
const app = express()
app.use(responseTime(function (req, res, time) {
let num: number = time;
}));
}
| Use official examples as tests | Use official examples as tests | TypeScript | mit | alexdresko/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,georgemarshall/DefinitelyTyped,zuzusik/DefinitelyTyped,aciccarello/DefinitelyTyped,magny/DefinitelyTyped,martinduparc/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,schmuli/DefinitelyTyped,YousefED/DefinitelyTyped,isman-usoh/DefinitelyTyped,benliddicott/DefinitelyTyped,benishouga/DefinitelyTyped,rolandzwaga/DefinitelyTyped,arusakov/DefinitelyTyped,shlomiassaf/DefinitelyTyped,martinduparc/DefinitelyTyped,mcliment/DefinitelyTyped,hellopao/DefinitelyTyped,one-pieces/DefinitelyTyped,AgentME/DefinitelyTyped,abbasmhd/DefinitelyTyped,minodisk/DefinitelyTyped,aciccarello/DefinitelyTyped,smrq/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,psnider/DefinitelyTyped,ashwinr/DefinitelyTyped,use-strict/DefinitelyTyped,chrootsu/DefinitelyTyped,borisyankov/DefinitelyTyped,sledorze/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,sledorze/DefinitelyTyped,benishouga/DefinitelyTyped,borisyankov/DefinitelyTyped,smrq/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,scriby/DefinitelyTyped,AgentME/DefinitelyTyped,isman-usoh/DefinitelyTyped,johan-gorter/DefinitelyTyped,benishouga/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,progre/DefinitelyTyped,jimthedev/DefinitelyTyped,jimthedev/DefinitelyTyped,minodisk/DefinitelyTyped,subash-a/DefinitelyTyped,psnider/DefinitelyTyped,schmuli/DefinitelyTyped,use-strict/DefinitelyTyped,micurs/DefinitelyTyped,QuatroCode/DefinitelyTyped,pocesar/DefinitelyTyped,nycdotnet/DefinitelyTyped,shlomiassaf/DefinitelyTyped,YousefED/DefinitelyTyped,chrootsu/DefinitelyTyped,mcrawshaw/DefinitelyTyped,dsebastien/DefinitelyTyped,aciccarello/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,martinduparc/DefinitelyTyped,scriby/DefinitelyTyped,arusakov/DefinitelyTyped,pocesar/DefinitelyTyped,ashwinr/DefinitelyTyped,alvarorahul/DefinitelyTyped,chrismbarr/DefinitelyTyped,progre/DefinitelyTyped,rolandzwaga/DefinitelyTyped,subash-a/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,jimthedev/DefinitelyTyped,mcrawshaw/DefinitelyTyped,zuzusik/DefinitelyTyped,hellopao/DefinitelyTyped,amir-arad/DefinitelyTyped,nycdotnet/DefinitelyTyped,chrismbarr/DefinitelyTyped,abbasmhd/DefinitelyTyped,psnider/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,schmuli/DefinitelyTyped,alvarorahul/DefinitelyTyped,hellopao/DefinitelyTyped,johan-gorter/DefinitelyTyped,pocesar/DefinitelyTyped | ---
+++
@@ -1,11 +1,41 @@
+import responseTime = require('response-time');
-import express = require('express');
-import responseTime = require('response-time');
-var app = express();
-app.use(responseTime());
-app.use(responseTime({
- digits: 3,
- header: 'X-Response-Time',
- suffix: true
-}));
+////////////////////////////////////////////////////////////////////////////////////
+// expressconnect tests https://github.com/expressjs/response-time#expressconnect //
+////////////////////////////////////////////////////////////////////////////////////
+import express = require('express')
+namespace express_connect_tests {
+ const app = express()
+ app.use(responseTime())
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////
+// vanilla http server tests https://github.com/expressjs/response-time#vanilla-http-server //
+//////////////////////////////////////////////////////////////////////////////////////////////
+import http = require('http')
+namespace vanilla_http_server_tests {
+ // create "middleware"
+ var _responseTime = responseTime()
+ http.createServer(function (req, res) {
+ _responseTime(req, res, function (err) {
+ if (err) return console.log(err);
+
+ // respond to request
+ res.setHeader('content-type', 'text/plain')
+ res.end('hello, world!')
+ })
+ })
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+// response time metrics tests https://github.com/expressjs/response-time#response-time-metrics //
+//////////////////////////////////////////////////////////////////////////////////////////////////
+namespace response_time_metrics_tests {
+ const app = express()
+ app.use(responseTime(function (req, res, time) {
+ let num: number = time;
+ }));
+} |
49f815c4aa51326dc712815f540ef1b21291485d | packages/auth/src/commands/auth/2fa/disable.ts | packages/auth/src/commands/auth/2fa/disable.ts | import {Command} from '@heroku-cli/command'
import * as Heroku from '@heroku-cli/schema'
import ux from 'cli-ux'
export default class Auth2faGenerate extends Command {
static description = 'disables 2fa on account'
static aliases = [
'twofactor:disable',
'2fa:disable',
]
static example = `$ heroku auth:2fa:disable
Disabling 2fa on [email protected]... done`
async run() {
ux.action.start('Disabling 2fa')
const {body: account} = await this.heroku.get<Heroku.Account>('/account')
ux.action.start(`Disabling 2fa on ${account.email}`)
if (!account.two_factor_authentication) this.error('2fa is already disabled')
const password = await ux.prompt('Password', {type: 'hide'})
await this.heroku.patch('/account', {body: {password, two_factor_authentication: false}})
}
}
| import {Command} from '@heroku-cli/command'
import * as Heroku from '@heroku-cli/schema'
import ux from 'cli-ux'
export default class Auth2faGenerate extends Command {
static description = 'disables 2fa on account'
static aliases = [
'twofactor:disable',
'2fa:disable',
]
static example = `$ heroku auth:2fa:disable
Disabling 2fa on [email protected]... done`
async run() {
ux.action.start('Disabling 2fa')
const {body: account} = await this.heroku.get<Heroku.Account>('/account'), {
headers: {
Accept: 'application/vnd.heroku+json; version=3.with_vaas_info',
}
}
ux.action.start(`Disabling 2fa on ${account.email}`)
if (account.vaas_enrolled) this.error('Cannot disable 2fa via CLI\nPlease visit your Account page on the Heroku Dashboad to manage 2fa')
if (!account.two_factor_authentication) this.error('2fa is already disabled')
const password = await ux.prompt('Password', {type: 'hide'})
await this.heroku.patch('/account', {body: {password, two_factor_authentication: false}})
}
}
| Add helpful error message for VaaS MFA users | Add helpful error message for VaaS MFA users
* Soon, we will roll out a beta where users can have MFA/2FA for their
Heroku Accounts using VaaS (verification as a service), a Salesforce
platform that all clouds are adopting.
* In the next few months, we will migrate all existing Heroku 2FA users
over to VaaS. The login experience will still be very similar for
these users, but they will be verifying themselves via the VaaS redirect
interface rather than on the Heroku home-grown 2FA flow.
* Users who are migrated over may not even know it, so they may attempt
to disable MFA via CLI. While technically we could do some trickery
with the VaaS Admin API to make this possible, the intent of VaaS is
that users go into the VaaS manage page, which is accessible via the
Heroku Dashboard, to do all verifier management.
* This CLI command is used very rarely but we figure it doesn't hurt to
add a helpful error message here rather than confusingly telling users
with VaaS MFA enabled that they do not have 2FA enabled (because they
do...it's just a *different* 2FA).
* https://gus.my.salesforce.com/a07B0000008TzijIAC
| TypeScript | isc | heroku/cli,heroku/heroku-cli,heroku/cli,heroku/heroku-cli,heroku/cli,heroku/heroku-cli,heroku/heroku-cli,heroku/cli | ---
+++
@@ -15,8 +15,13 @@
async run() {
ux.action.start('Disabling 2fa')
- const {body: account} = await this.heroku.get<Heroku.Account>('/account')
+ const {body: account} = await this.heroku.get<Heroku.Account>('/account'), {
+ headers: {
+ Accept: 'application/vnd.heroku+json; version=3.with_vaas_info',
+ }
+ }
ux.action.start(`Disabling 2fa on ${account.email}`)
+ if (account.vaas_enrolled) this.error('Cannot disable 2fa via CLI\nPlease visit your Account page on the Heroku Dashboad to manage 2fa')
if (!account.two_factor_authentication) this.error('2fa is already disabled')
const password = await ux.prompt('Password', {type: 'hide'})
await this.heroku.patch('/account', {body: {password, two_factor_authentication: false}}) |
69dc47668310c9e3f6c4a78723d39fc047c55a2e | test/property-decorators/min.spec.ts | test/property-decorators/min.spec.ts | import { Min } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (greater or equals than min value)', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 5;
expect(testClass.myNumber).toEqual(5);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 3;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (less than min value)', () => {
class TestClassMinValue {
@Min(5, true)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 10;
testClass.myNumber = 3;
expect(testClass.myNumber).toEqual(10);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMinValue {
@Min(5, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMinValue();
expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
});
}); | import { Min } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (greater or equals than min value)', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
let valueToAssign = 5;
testClass.myNumber = valueToAssign;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 3;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (less than min value)', () => {
class TestClassMinValue {
@Min(5, true)
myNumber: number;
}
let testClass = new TestClassMinValue();
let validValueToAssign = 10;
testClass.myNumber = validValueToAssign;
testClass.myNumber = 3;
expect(testClass.myNumber).toEqual(validValueToAssign);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMinValue {
@Min(5, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMinValue();
expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
});
}); | Add unit tests for min decorator | Add unit tests for min decorator
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -9,8 +9,9 @@
}
let testClass = new TestClassMinValue();
- testClass.myNumber = 5;
- expect(testClass.myNumber).toEqual(5);
+ let valueToAssign = 5;
+ testClass.myNumber = valueToAssign;
+ expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
@@ -31,9 +32,10 @@
}
let testClass = new TestClassMinValue();
- testClass.myNumber = 10;
+ let validValueToAssign = 10;
+ testClass.myNumber = validValueToAssign;
testClass.myNumber = 3;
- expect(testClass.myNumber).toEqual(10);
+ expect(testClass.myNumber).toEqual(validValueToAssign);
});
it('should throw an error when the value assigned is invalid', () => { |
f645ddb31ad034f672312713955d30964acf2ee7 | 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:[email protected]">email</a> (
<a href="https://keys.openpgp.org/[email protected]">PGP key</a>).</p>
</footer>
</>
)
}
| import Head from 'next/head'
import Link from 'next/link'
export default function Layout({
children,
title
}: {
children: React.ReactNode
title?: string
}) {
const github = <a href="https://github.com/kplattret/kevinplattret.com">GitHub</a>
const email = <a href="mailto:[email protected]">email</a>
const pgpKey = <a href="https://keys.openpgp.org/[email protected]">PGP key</a>
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 {github}.
Feel free to reach out via {email} ({pgpKey}).</p>
</footer>
</>
)
}
| Store footer links in constances | Store footer links in constances
It can be a bit tricky to format the code within an HTML elements in the
`return` function, especially when using nested elements. This moves
`<a>` tags outside of the footer and stores them in constances, which
helps keep the code neat and tidy.
| TypeScript | mit | kplattret/kplattret.github.io,kplattret/kplattret.github.io | ---
+++
@@ -8,6 +8,10 @@
children: React.ReactNode
title?: string
}) {
+ const github = <a href="https://github.com/kplattret/kevinplattret.com">GitHub</a>
+ const email = <a href="mailto:[email protected]">email</a>
+ const pgpKey = <a href="https://keys.openpgp.org/[email protected]">PGP key</a>
+
return (
<>
<Head>
@@ -31,10 +35,8 @@
<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:[email protected]">email</a> (
- <a href="https://keys.openpgp.org/[email protected]">PGP key</a>).</p>
+ <p>Written by Kevin Plattret in London and other places. Source code available on {github}.
+ Feel free to reach out via {email} ({pgpKey}).</p>
</footer>
</>
) |
e347c3711cc4b85eda34f1aba844e1a6576ff40c | tests/cases/fourslash/jsDocGenerics1.ts | tests/cases/fourslash/jsDocGenerics1.ts | ///<reference path="fourslash.ts" />
// @allowNonTsExtensions: true
// @Filename: Foo.js
//// /** @type {Array<number>} */
//// var v;
//// v[0]./**/
goTo.marker();
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
| ///<reference path="fourslash.ts" />
// @allowNonTsExtensions: true
// @Filename: ref.d.ts
//// namespace Thing {
//// export interface Thung {
//// a: number;
//// ]
//// ]
// @Filename: Foo.js
////
//// /** @type {Array<number>} */
//// var v;
//// v[0]./*1*/
////
//// /** @type {{x: Array<Array<number>>}} */
//// var w;
//// w.x[0][0]./*2*/
////
//// /** @type {Array<Thing.Thung>} */
//// var x;
//// x[0].a./*3*/
goTo.marker('1');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
goTo.marker('2');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
goTo.marker('3');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
| Add more complex test scenarios | Add more complex test scenarios
| TypeScript | apache-2.0 | blakeembrey/TypeScript,plantain-00/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,nycdotnet/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,minestarks/TypeScript,erikmcc/TypeScript,kitsonk/TypeScript,vilic/TypeScript,synaptek/TypeScript,jwbay/TypeScript,Eyas/TypeScript,chuckjaz/TypeScript,TukekeSoft/TypeScript,donaldpipowitch/TypeScript,ziacik/TypeScript,RyanCavanaugh/TypeScript,evgrud/TypeScript,evgrud/TypeScript,kpreisser/TypeScript,nojvek/TypeScript,jwbay/TypeScript,SaschaNaz/TypeScript,evgrud/TypeScript,jeremyepling/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,nycdotnet/TypeScript,jwbay/TypeScript,kpreisser/TypeScript,plantain-00/TypeScript,Microsoft/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,thr0w/Thr0wScript,SaschaNaz/TypeScript,microsoft/TypeScript,samuelhorwitz/typescript,mihailik/TypeScript,weswigham/TypeScript,thr0w/Thr0wScript,nycdotnet/TypeScript,erikmcc/TypeScript,DLehenbauer/TypeScript,basarat/TypeScript,blakeembrey/TypeScript,jeremyepling/TypeScript,samuelhorwitz/typescript,chuckjaz/TypeScript,evgrud/TypeScript,samuelhorwitz/typescript,kpreisser/TypeScript,thr0w/Thr0wScript,TukekeSoft/TypeScript,jeremyepling/TypeScript,samuelhorwitz/typescript,kitsonk/TypeScript,nojvek/TypeScript,chuckjaz/TypeScript,RyanCavanaugh/TypeScript,donaldpipowitch/TypeScript,alexeagle/TypeScript,ziacik/TypeScript,chuckjaz/TypeScript,Eyas/TypeScript,vilic/TypeScript,plantain-00/TypeScript,synaptek/TypeScript,donaldpipowitch/TypeScript,ziacik/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,plantain-00/TypeScript,synaptek/TypeScript,TukekeSoft/TypeScript,mihailik/TypeScript,basarat/TypeScript,Microsoft/TypeScript,erikmcc/TypeScript,DLehenbauer/TypeScript,SaschaNaz/TypeScript,weswigham/TypeScript,microsoft/TypeScript,basarat/TypeScript,Microsoft/TypeScript,mihailik/TypeScript,DLehenbauer/TypeScript,kitsonk/TypeScript,synaptek/TypeScript,blakeembrey/TypeScript,thr0w/Thr0wScript,minestarks/TypeScript,vilic/TypeScript,Eyas/TypeScript,nycdotnet/TypeScript,DLehenbauer/TypeScript,jwbay/TypeScript,erikmcc/TypeScript,blakeembrey/TypeScript,mihailik/TypeScript,microsoft/TypeScript,Eyas/TypeScript,ziacik/TypeScript | ---
+++
@@ -1,10 +1,34 @@
///<reference path="fourslash.ts" />
// @allowNonTsExtensions: true
+// @Filename: ref.d.ts
+//// namespace Thing {
+//// export interface Thung {
+//// a: number;
+//// ]
+//// ]
+
+
// @Filename: Foo.js
+////
//// /** @type {Array<number>} */
//// var v;
-//// v[0]./**/
+//// v[0]./*1*/
+////
+//// /** @type {{x: Array<Array<number>>}} */
+//// var w;
+//// w.x[0][0]./*2*/
+////
+//// /** @type {Array<Thing.Thung>} */
+//// var x;
+//// x[0].a./*3*/
-goTo.marker();
+
+goTo.marker('1');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
+
+goTo.marker('2');
+verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
+
+goTo.marker('3');
+verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); |
cda76a556d5b408cbc3c434260f2b550aee4e754 | packages/react-day-picker/src/hooks/useSelection/useSelectRange.ts | packages/react-day-picker/src/hooks/useSelection/useSelectRange.ts | import { useState } from 'react';
import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types';
import { DateRange } from '../../types/DateRange';
import { addToRange } from './utils/addToRange';
export type RangeSelectionHandler = (day: Date) => void;
export type UseRangeSelect = {
selected: DateRange | undefined;
onDayClick: DayClickEventHandler;
reset: () => void;
};
export type UseRangeCallback = (
range: DateRange | undefined,
day: Date,
modifiers: ModifierStatus,
e: React.MouseEvent
) => void;
/** Hook to handle range selections. */
export function useRangeSelect(
mode: SelectMode,
defaultValue?: unknown,
required = false,
callback?: UseRangeCallback
): UseRangeSelect {
const initialValue =
mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined;
const [selected, setSelected] = useState(initialValue);
const onDayClick: DayClickEventHandler = (day, modifiers, e) => {
setSelected((currentValue) => {
const newValue = addToRange(day, currentValue, required);
callback?.(newValue, day, modifiers, e);
setSelected(newValue);
return newValue;
});
return;
};
const reset = () => {
setSelected(initialValue || undefined);
};
return { selected, onDayClick, reset };
}
| import { useState } from 'react';
import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types';
import { DateRange } from '../../types/DateRange';
import { addToRange } from './utils/addToRange';
export type UseRangeSelect = {
selected: DateRange | undefined;
onDayClick: DayClickEventHandler;
reset: () => void;
};
export type RangeSelectionHandler = (
range: DateRange | undefined,
day: Date,
modifiers: ModifierStatus,
e: React.MouseEvent
) => void;
/** Hook to handle range selections. */
export function useRangeSelect(
mode: SelectMode,
defaultValue?: unknown,
required = false,
callback?: RangeSelectionHandler
): UseRangeSelect {
const initialValue =
mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined;
const [selected, setSelected] = useState(initialValue);
const onDayClick: DayClickEventHandler = (day, modifiers, e) => {
setSelected((currentValue) => {
const newValue = addToRange(day, currentValue, required);
callback?.(newValue, day, modifiers, e);
setSelected(newValue);
return newValue;
});
return;
};
const reset = () => {
setSelected(initialValue || undefined);
};
return { selected, onDayClick, reset };
}
| Fix wrong type in callback | Fix wrong type in callback
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -3,8 +3,6 @@
import { DayClickEventHandler, ModifierStatus, SelectMode } from '../../types';
import { DateRange } from '../../types/DateRange';
import { addToRange } from './utils/addToRange';
-
-export type RangeSelectionHandler = (day: Date) => void;
export type UseRangeSelect = {
selected: DateRange | undefined;
@@ -12,7 +10,7 @@
reset: () => void;
};
-export type UseRangeCallback = (
+export type RangeSelectionHandler = (
range: DateRange | undefined,
day: Date,
modifiers: ModifierStatus,
@@ -24,7 +22,7 @@
mode: SelectMode,
defaultValue?: unknown,
required = false,
- callback?: UseRangeCallback
+ callback?: RangeSelectionHandler
): UseRangeSelect {
const initialValue =
mode === 'range' && defaultValue ? (defaultValue as DateRange) : undefined; |
48ded60d03501333d9e2d1983e7808feeefff5b0 | app/src/lib/fix-emoji-spacing.ts | app/src/lib/fix-emoji-spacing.ts | // This module renders an element with an emoji using
// a non system-default font to workaround an Chrome
// issue that causes unexpected spacing on emojis.
// More info:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1113293
const container = document.createElement('div')
container.setAttribute(
'style',
'visibility: hidden; font-family: Arial !important;'
)
// Keep this array synced with the font size variables
// in _variables.scss
const fontSizes = [
'--font-size',
'--font-size-sm',
'--font-size-md',
'--font-size-lg',
'--font-size-xl',
'--font-size-xxl',
'--font-size-xs',
]
for (const fontSize of fontSizes) {
const span = document.createElement('span')
span.setAttribute('style', `font-size: var(${fontSize});`)
span.textContent = '🤦🏿♀️'
container.appendChild(span)
}
document.body.appendChild(container)
// Read the dimensions of the element to force the browser to do a layout.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
container.offsetHeight
// Browser has rendered the emojis, now we can remove them.
document.body.removeChild(container)
| // This module renders an element with an emoji using
// a non system-default font to workaround an Chrome
// issue that causes unexpected spacing on emojis.
// More info:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1113293
const container = document.createElement('div')
container.setAttribute(
'style',
'visibility: hidden; font-family: Arial !important;'
)
// Keep this array synced with the font size variables
// in _variables.scss
const fontSizes = [
'--font-size',
'--font-size-sm',
'--font-size-md',
'--font-size-lg',
'--font-size-xl',
'--font-size-xxl',
'--font-size-xs',
]
for (const fontSize of fontSizes) {
const span = document.createElement('span')
span.style.setProperty('fontSize', `var(${fontSize}`)
span.style.setProperty('font-family', 'Arial', 'important')
span.textContent = '🤦🏿♀️'
container.appendChild(span)
}
document.body.appendChild(container)
// Read the dimensions of the element to force the browser to do a layout.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
container.offsetHeight
// Browser has rendered the emojis, now we can remove them.
document.body.removeChild(container)
| Use `style.setProperty()` method to apply style | Use `style.setProperty()` method to apply style
Co-authored-by: Markus Olsson <[email protected]> | TypeScript | mit | shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,say25/desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,desktop/desktop,shiftkey/desktop | ---
+++
@@ -24,7 +24,8 @@
for (const fontSize of fontSizes) {
const span = document.createElement('span')
- span.setAttribute('style', `font-size: var(${fontSize});`)
+ span.style.setProperty('fontSize', `var(${fontSize}`)
+ span.style.setProperty('font-family', 'Arial', 'important')
span.textContent = '🤦🏿♀️'
container.appendChild(span)
} |
1ed46d21d7b8847eeb13f410e9e8207d9d166f1c | src/test/runTests.ts | src/test/runTests.ts | import { resolve } from "path";
import { runTests } from "vscode-test";
import { TestOptions } from "vscode-test/out/runTest";
(async function main()
{
let environmentPath = resolve(__dirname, "..", "..", "src", "test");
let commonOptions: TestOptions = {
extensionDevelopmentPath: resolve(__dirname, "..", ".."),
extensionTestsPath: resolve(__dirname, "..", "..", "lib", "test")
};
try
{
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "common"
}
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "single-file"
},
launchArgs: [
resolve(environmentPath, "single-file", "Test.md")
]
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "single-folder"
},
launchArgs: [
resolve(environmentPath, "single-folder")
]
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "workspace"
},
launchArgs: [
resolve(environmentPath, "workspace", "workspace.code-workspace")
]
});
}
catch (exception)
{
console.error(exception);
console.error("Failed to run tests");
process.exit(1);
}
})();
| import { resolve } from "path";
import { runTests } from "vscode-test";
import { TestOptions } from "vscode-test/out/runTest";
(async function main()
{
let environmentPath = resolve(__dirname, "..", "..", "src", "test");
let commonArgs: string[] = [
"--disable-gpu",
"--headless",
"--no-sandbox"
];
let commonOptions: TestOptions = {
extensionDevelopmentPath: resolve(__dirname, "..", ".."),
extensionTestsPath: resolve(__dirname, "..", "..", "lib", "test")
};
try
{
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "common"
}
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "single-file"
},
launchArgs: [
...commonArgs,
resolve(environmentPath, "single-file", "Test.md")
]
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "single-folder"
},
launchArgs: [
...commonArgs,
resolve(environmentPath, "single-folder")
]
});
await runTests(
{
...commonOptions,
extensionTestsEnv: {
TEST_SUITE: "workspace"
},
launchArgs: [
...commonArgs,
resolve(environmentPath, "workspace", "workspace.code-workspace")
]
});
}
catch (exception)
{
console.error(exception);
console.error("Failed to run tests");
process.exit(1);
}
})();
| Add arguments for enabling headless vscode testing | Add arguments for enabling headless vscode testing
| TypeScript | mit | manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter | ---
+++
@@ -5,6 +5,12 @@
(async function main()
{
let environmentPath = resolve(__dirname, "..", "..", "src", "test");
+
+ let commonArgs: string[] = [
+ "--disable-gpu",
+ "--headless",
+ "--no-sandbox"
+ ];
let commonOptions: TestOptions = {
extensionDevelopmentPath: resolve(__dirname, "..", ".."),
@@ -28,6 +34,7 @@
TEST_SUITE: "single-file"
},
launchArgs: [
+ ...commonArgs,
resolve(environmentPath, "single-file", "Test.md")
]
});
@@ -39,6 +46,7 @@
TEST_SUITE: "single-folder"
},
launchArgs: [
+ ...commonArgs,
resolve(environmentPath, "single-folder")
]
});
@@ -50,6 +58,7 @@
TEST_SUITE: "workspace"
},
launchArgs: [
+ ...commonArgs,
resolve(environmentPath, "workspace", "workspace.code-workspace")
]
}); |
f92a95a7574d0196ac8f77bc07273212d7cb4225 | packages/components/components/v2/input/PasswordInput.tsx | packages/components/components/v2/input/PasswordInput.tsx | import { useState } from 'react';
import { c } from 'ttag';
import Icon from '../../icon/Icon';
import InputTwo, { InputTwoProps } from './Input';
const PasswordInputTwo = ({ disabled, ...rest }: Omit<InputTwoProps, 'type'>) => {
const [type, setType] = useState('password');
const toggle = () => {
setType(type === 'password' ? 'text' : 'password');
};
return (
<InputTwo
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
spellCheck="false"
{...rest}
type={type}
disabled={disabled}
suffix={
<button
title={type === 'password' ? c('Label').t`Reveal password` : c('Label').t`Hide password`}
className="inline-flex flex-item-noshrink"
tabIndex={-1}
disabled={disabled}
type="button"
onClick={toggle}
>
<Icon className="mauto" name={type === 'password' ? 'eye' : 'eye-slash'} />
</button>
}
/>
);
};
export default PasswordInputTwo;
| import { useState } from 'react';
import { c } from 'ttag';
import Icon from '../../icon/Icon';
import InputTwo, { InputTwoProps } from './Input';
type PasswordType = 'password' | 'text';
interface Props extends Omit<InputTwoProps, 'type'> {
defaultType?: PasswordType;
}
const PasswordInputTwo = ({ disabled, defaultType = 'password', ...rest }: Props) => {
const [type, setType] = useState<PasswordType>(defaultType);
const toggle = () => {
setType(type === 'password' ? 'text' : 'password');
};
return (
<InputTwo
autoComplete="off"
autoCapitalize="off"
autoCorrect="off"
spellCheck="false"
{...rest}
type={type}
disabled={disabled}
suffix={
<button
title={type === 'password' ? c('Label').t`Reveal password` : c('Label').t`Hide password`}
className="inline-flex flex-item-noshrink"
tabIndex={-1}
disabled={disabled}
type="button"
onClick={toggle}
>
<Icon className="mauto" name={type === 'password' ? 'eye' : 'eye-slash'} />
</button>
}
/>
);
};
export default PasswordInputTwo;
| Add default type on inputs | Add default type on inputs
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -4,8 +4,14 @@
import Icon from '../../icon/Icon';
import InputTwo, { InputTwoProps } from './Input';
-const PasswordInputTwo = ({ disabled, ...rest }: Omit<InputTwoProps, 'type'>) => {
- const [type, setType] = useState('password');
+type PasswordType = 'password' | 'text';
+
+interface Props extends Omit<InputTwoProps, 'type'> {
+ defaultType?: PasswordType;
+}
+
+const PasswordInputTwo = ({ disabled, defaultType = 'password', ...rest }: Props) => {
+ const [type, setType] = useState<PasswordType>(defaultType);
const toggle = () => {
setType(type === 'password' ? 'text' : 'password');
}; |
ec0bef50908f9c6dfd7de2bc5c02bf667c0fe452 | src/fuzzerFactory/__tests__/FunctionFuzzerFactory.spec.ts | src/fuzzerFactory/__tests__/FunctionFuzzerFactory.spec.ts | import {FunctionFuzzer} from "../../fuzzer/FunctionFuzzer";
import {fuzz} from "../../index";
import {sum} from "../__mocks__/sum.mock";
import {FunctionFuzzerFactory} from "../FunctionFuzzerFactory";
describe("FunctionFuzzerFactory", () => {
const sumFuzzerFactory = fuzz(sum);
test("functionFuzzer should create function fuzzer instance", () => {
expect(sumFuzzerFactory instanceof FunctionFuzzerFactory).toBe(true);
});
test("functionFuzzer should create fuzzer with internal func", () => {
expect((sumFuzzerFactory as any).func).toBe(sum);
});
test("factory methods should creates fuzzer without error", () => {
const methodNames: Array<keyof FunctionFuzzerFactory> = [
"boolean", "booleanArray", "number", "numberArray", "string", "stringArray", "all",
];
methodNames.forEach(method => {
expect((sumFuzzerFactory as any)[method]() instanceof FunctionFuzzer).toBe(true);
expect(() => (sumFuzzerFactory as any)[method]()).not.toThrow();
});
});
});
| import {FunctionFuzzer} from "../../fuzzer/FunctionFuzzer";
import {fuzz} from "../../index";
import {sum} from "../__mocks__/sum.mock";
import {FunctionFuzzerFactory} from "../FunctionFuzzerFactory";
describe("FunctionFuzzerFactory", () => {
const sumFuzzerFactory = fuzz(sum);
test("functionFuzzer should create function fuzzer instance", () => {
expect(sumFuzzerFactory instanceof FunctionFuzzerFactory).toBe(true);
});
test("functionFuzzer should create fuzzer with internal func", () => {
expect((sumFuzzerFactory as any).func).toBe(sum);
});
const methodNames: Array<keyof FunctionFuzzerFactory> = [
"boolean", "booleanArray", "number", "numberArray", "string", "stringArray", "all",
];
methodNames.forEach(method => {
test(`factory method: ${method} should creates fuzzer without error`, () => {
expect((sumFuzzerFactory as any)[method]() instanceof FunctionFuzzer).toBe(true);
expect(() => (sumFuzzerFactory as any)[method]()).not.toThrow();
});
});
test("should create snapshots with correct error descriptions", () => {
const errors = fuzz(sum)
.string()
.all();
expect(errors).toMatchSnapshot();
});
});
| Add snapshot testing for sum function | Add snapshot testing for sum function
| TypeScript | mit | usehotkey/fuzzing | ---
+++
@@ -14,14 +14,23 @@
expect((sumFuzzerFactory as any).func).toBe(sum);
});
- test("factory methods should creates fuzzer without error", () => {
- const methodNames: Array<keyof FunctionFuzzerFactory> = [
- "boolean", "booleanArray", "number", "numberArray", "string", "stringArray", "all",
- ];
+
+ const methodNames: Array<keyof FunctionFuzzerFactory> = [
+ "boolean", "booleanArray", "number", "numberArray", "string", "stringArray", "all",
+ ];
- methodNames.forEach(method => {
+ methodNames.forEach(method => {
+ test(`factory method: ${method} should creates fuzzer without error`, () => {
expect((sumFuzzerFactory as any)[method]() instanceof FunctionFuzzer).toBe(true);
expect(() => (sumFuzzerFactory as any)[method]()).not.toThrow();
});
});
+
+ test("should create snapshots with correct error descriptions", () => {
+ const errors = fuzz(sum)
+ .string()
+ .all();
+
+ expect(errors).toMatchSnapshot();
+ });
}); |
9de7ea79edbfb770b46c8c48041a87e4fa836a9c | app/src/ui/notification/new-commits-banner.tsx | app/src/ui/notification/new-commits-banner.tsx | import * as React from 'react'
import { ButtonGroup } from '../lib/button-group'
import { Button } from '../lib/button'
import { Ref } from '../lib/ref'
import { Octicon, OcticonSymbol } from '../octicons'
interface NewCommitsBannerProps {
readonly numCommits: number
readonly ref: string
}
export class NewCommitsBanner extends React.Component<
NewCommitsBannerProps,
{}
> {
public render() {
return (
<div className="notification-banner diverge-banner">
<div className="notification-banner-content">
<p>
Your branch is <strong>{this.props.numCommits} commits</strong>{' '}
behind <Ref>{this.props.ref}</Ref>
</p>
<a className="close" aria-label="Dismiss banner">
<Octicon symbol={OcticonSymbol.x} />
</a>
</div>
<ButtonGroup>
<Button type="submit" onClick={this.noOp}>
Merge...
</Button>
<Button onClick={this.noOp}>Compare</Button>
</ButtonGroup>
</div>
)
}
private noOp = () => {}
}
| import * as React from 'react'
import { ButtonGroup } from '../lib/button-group'
import { Button } from '../lib/button'
import { Ref } from '../lib/ref'
import { Octicon, OcticonSymbol } from '../octicons'
interface NewCommitsBannerProps {
readonly numCommits: number
readonly ref: string
}
export class NewCommitsBanner extends React.Component<
NewCommitsBannerProps,
{}
> {
public render() {
return (
<div className="notification-banner diverge-banner">
<div className="notification-banner-content">
<p>
Your branch is <strong>{this.props.numCommits} commits</strong>{' '}
behind <Ref>{this.props.ref}</Ref>
</p>
<a className="close" aria-label="Dismiss banner">
<Octicon symbol={OcticonSymbol.x} />
</a>
</div>
<ButtonGroup>
<Button type="submit" onClick={this.noOp}>
Compare
</Button>
<Button onClick={this.noOp}>Merge...</Button>
</ButtonGroup>
</div>
)
}
private noOp = () => {}
}
| Set the correct primary button | Set the correct primary button
Co-Authored-By: Don Okuda <[email protected]>
| TypeScript | mit | artivilla/desktop,j-f1/forked-desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,desktop/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop | ---
+++
@@ -29,10 +29,10 @@
<ButtonGroup>
<Button type="submit" onClick={this.noOp}>
- Merge...
+ Compare
</Button>
- <Button onClick={this.noOp}>Compare</Button>
+ <Button onClick={this.noOp}>Merge...</Button>
</ButtonGroup>
</div>
) |
67d35ad418c818ad7556f2d3d35ceaf13356b06c | build/azure-pipelines/common/computeNodeModulesCacheKey.ts | build/azure-pipelines/common/computeNodeModulesCacheKey.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
const { dirs } = require('../../npm/dirs');
const ROOT = path.join(__dirname, '../../../');
const shasum = crypto.createHash('sha1');
shasum.update(fs.readFileSync(path.join(ROOT, 'build/.cachesalt')));
shasum.update(fs.readFileSync(path.join(ROOT, '.yarnrc')));
shasum.update(fs.readFileSync(path.join(ROOT, 'remote/.yarnrc')));
// Add `yarn.lock` files
for (let dir of dirs) {
const yarnLockPath = path.join(ROOT, dir, 'yarn.lock');
shasum.update(fs.readFileSync(yarnLockPath));
}
// Add any other command line arguments
for (let i = 2; i < process.argv.length; i++) {
shasum.update(process.argv[i]);
}
process.stdout.write(shasum.digest('hex'));
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as fs from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
const { dirs } = require('../../npm/dirs');
const ROOT = path.join(__dirname, '../../../');
const shasum = crypto.createHash('sha1');
shasum.update(fs.readFileSync(path.join(ROOT, 'build/.cachesalt')));
shasum.update(fs.readFileSync(path.join(ROOT, '.yarnrc')));
shasum.update(fs.readFileSync(path.join(ROOT, 'remote/.yarnrc')));
// Add `package.json` and `yarn.lock` files
for (let dir of dirs) {
const packageJsonPath = path.join(ROOT, dir, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
const relevantPackageJsonSections = {
dependencies: packageJson.dependencies,
devDependencies: packageJson.devDependencies,
optionalDependencies: packageJson.optionalDependencies,
resolutions: packageJson.resolutions
};
shasum.update(JSON.stringify(relevantPackageJsonSections));
const yarnLockPath = path.join(ROOT, dir, 'yarn.lock');
shasum.update(fs.readFileSync(yarnLockPath));
}
// Add any other command line arguments
for (let i = 2; i < process.argv.length; i++) {
shasum.update(process.argv[i]);
}
process.stdout.write(shasum.digest('hex'));
| Use relevant sections from `package.json` in the cache key computation | Use relevant sections from `package.json` in the cache key computation
| TypeScript | mit | microsoft/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode | ---
+++
@@ -18,8 +18,18 @@
shasum.update(fs.readFileSync(path.join(ROOT, '.yarnrc')));
shasum.update(fs.readFileSync(path.join(ROOT, 'remote/.yarnrc')));
-// Add `yarn.lock` files
+// Add `package.json` and `yarn.lock` files
for (let dir of dirs) {
+ const packageJsonPath = path.join(ROOT, dir, 'package.json');
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
+ const relevantPackageJsonSections = {
+ dependencies: packageJson.dependencies,
+ devDependencies: packageJson.devDependencies,
+ optionalDependencies: packageJson.optionalDependencies,
+ resolutions: packageJson.resolutions
+ };
+ shasum.update(JSON.stringify(relevantPackageJsonSections));
+
const yarnLockPath = path.join(ROOT, dir, 'yarn.lock');
shasum.update(fs.readFileSync(yarnLockPath));
} |
53fc0c68b23621b302b2d29d68a1e1fa4c3c76e7 | polygerrit-ui/app/services/flags/flags_test.ts | polygerrit-ui/app/services/flags/flags_test.ts | /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../../test/common-test-setup-karma';
import {FlagsServiceImplementation} from './flags_impl';
suite('flags tests', () => {
let originalEnabledExperiments: string[];
let flags: FlagsServiceImplementation;
suiteSetup(() => {
originalEnabledExperiments = window.ENABLED_EXPERIMENTS;
window.ENABLED_EXPERIMENTS = ['a', 'a'];
flags = new FlagsServiceImplementation();
});
suiteTeardown(() => {
window.ENABLED_EXPERIMENTS = originalEnabledExperiments;
});
test('isEnabled', () => {
assert.equal(flags.isEnabled('a'), true);
assert.equal(flags.isEnabled('random'), false);
});
test('enabledExperiments', () => {
assert.deepEqual(flags.enabledExperiments, ['a']);
});
});
| /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '../../test/common-test-setup-karma';
import {FlagsServiceImplementation} from './flags_impl';
suite('flags tests', () => {
let originalEnabledExperiments: string[];
let flags: FlagsServiceImplementation;
suiteSetup(() => {
originalEnabledExperiments = window.ENABLED_EXPERIMENTS;
window.ENABLED_EXPERIMENTS = ['a', 'a'];
flags = new FlagsServiceImplementation();
});
suiteTeardown(() => {
window.ENABLED_EXPERIMENTS = originalEnabledExperiments;
});
test('isEnabled', () => {
assert.equal(flags.isEnabled('a'), true);
assert.equal(flags.isEnabled('random'), false);
});
test('enabledExperiments', () => {
assert.deepEqual(flags.enabledExperiments, ['a']);
});
});
| Fix some Code Style issue | Fix some Code Style issue
This somehow triggers in go/grev/308953 which does not even touch this
file.
:
Change-Id: If48813ef9360f6acb28b943e1484c2e77007768b
| TypeScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -41,4 +41,3 @@
assert.deepEqual(flags.enabledExperiments, ['a']);
});
});
- |
abee08ec189f0ea50e16d4b82c37fdf16a799517 | piwik-tracker/piwik-tracker-tests.ts | piwik-tracker/piwik-tracker-tests.ts | /// <reference path="../node/node.d.ts" />
/// <reference path="piwik-tracker.d.ts" />
// Example code taken from https://www.npmjs.com/package/piwik-tracker
var PiwikTracker = require('piwik-tracker');
// Initialize with your site ID and Piwik URL
var piwik = new PiwikTracker(1, 'http://mywebsite.com/piwik.php');
// Optional: Respond to tracking errors
piwik.on('error', function(err) {
console.log('error tracking request: ', err)
})
// Track a request URL:
// Either as a simple string …
piwik.track('http://example.com/track/this/url');
// … or provide further options:
piwik.track({
url: 'http://example.com/track/this/url',
action_name: 'This will be shown in your dashboard',
ua: 'Node.js v0.10.24',
cvar: JSON.stringify({
'1': ['custom variable name', 'custom variable value']
})
});
| /// <reference path="../node/node.d.ts" />
/// <reference path="piwik-tracker.d.ts" />
// Example code taken from https://www.npmjs.com/package/piwik-tracker
var PiwikTracker = require('piwik-tracker');
// Initialize with your site ID and Piwik URL
var piwik = new PiwikTracker(1, 'http://mywebsite.com/piwik.php');
// Optional: Respond to tracking errors
piwik.on('error', function(err : Error) {
console.log('error tracking request: ', err)
})
// Track a request URL:
// Either as a simple string …
piwik.track('http://example.com/track/this/url');
// … or provide further options:
piwik.track({
url: 'http://example.com/track/this/url',
action_name: 'This will be shown in your dashboard',
ua: 'Node.js v0.10.24',
cvar: JSON.stringify({
'1': ['custom variable name', 'custom variable value']
})
});
| Fix parameter type (implicity any) | piwik-tracker-test: Fix parameter type (implicity any) | TypeScript | mit | sergey-buturlakin/DefinitelyTyped,TildaLabs/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,georgemarshall/DefinitelyTyped,lucyhe/DefinitelyTyped,forumone/DefinitelyTyped,timjk/DefinitelyTyped,manekovskiy/DefinitelyTyped,lekaha/DefinitelyTyped,robert-voica/DefinitelyTyped,Trapulo/DefinitelyTyped,Dominator008/DefinitelyTyped,bencoveney/DefinitelyTyped,AgentME/DefinitelyTyped,mattblang/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,jacqt/DefinitelyTyped,Seikho/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,CSharpFan/DefinitelyTyped,masonkmeyer/DefinitelyTyped,ducin/DefinitelyTyped,mrk21/DefinitelyTyped,zalamtech/DefinitelyTyped,mszczepaniak/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,RX14/DefinitelyTyped,takenet/DefinitelyTyped,Chris380/DefinitelyTyped,optical/DefinitelyTyped,xStrom/DefinitelyTyped,robl499/DefinitelyTyped,gandjustas/DefinitelyTyped,greglo/DefinitelyTyped,igorsechyn/DefinitelyTyped,newclear/DefinitelyTyped,drinchev/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,stacktracejs/DefinitelyTyped,mhegazy/DefinitelyTyped,DenEwout/DefinitelyTyped,nseckinoral/DefinitelyTyped,raijinsetsu/DefinitelyTyped,adamcarr/DefinitelyTyped,omidkrad/DefinitelyTyped,billccn/DefinitelyTyped,ajtowf/DefinitelyTyped,opichals/DefinitelyTyped,Carreau/DefinitelyTyped,adammartin1981/DefinitelyTyped,musakarakas/DefinitelyTyped,alvarorahul/DefinitelyTyped,subash-a/DefinitelyTyped,abmohan/DefinitelyTyped,bpowers/DefinitelyTyped,PascalSenn/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,maxlang/DefinitelyTyped,Zenorbi/DefinitelyTyped,vagarenko/DefinitelyTyped,gcastre/DefinitelyTyped,mweststrate/DefinitelyTyped,vincentw56/DefinitelyTyped,alexdresko/DefinitelyTyped,sclausen/DefinitelyTyped,Syati/DefinitelyTyped,stylelab-io/DefinitelyTyped,UzEE/DefinitelyTyped,nmalaguti/DefinitelyTyped,stephenjelfs/DefinitelyTyped,progre/DefinitelyTyped,amanmahajan7/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,alextkachman/DefinitelyTyped,laball/DefinitelyTyped,dragouf/DefinitelyTyped,Syati/DefinitelyTyped,yuit/DefinitelyTyped,wilfrem/DefinitelyTyped,nainslie/DefinitelyTyped,algorithme/DefinitelyTyped,onecentlin/DefinitelyTyped,whoeverest/DefinitelyTyped,jeremyhayes/DefinitelyTyped,hatz48/DefinitelyTyped,mattanja/DefinitelyTyped,arusakov/DefinitelyTyped,Penryn/DefinitelyTyped,trystanclarke/DefinitelyTyped,optical/DefinitelyTyped,minodisk/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,tan9/DefinitelyTyped,donnut/DefinitelyTyped,robertbaker/DefinitelyTyped,mareek/DefinitelyTyped,davidpricedev/DefinitelyTyped,tan9/DefinitelyTyped,lightswitch05/DefinitelyTyped,jimthedev/DefinitelyTyped,dmoonfire/DefinitelyTyped,OfficeDev/DefinitelyTyped,bardt/DefinitelyTyped,Deathspike/DefinitelyTyped,magny/DefinitelyTyped,paulmorphy/DefinitelyTyped,aciccarello/DefinitelyTyped,nakakura/DefinitelyTyped,wkrueger/DefinitelyTyped,arma-gast/DefinitelyTyped,tdmckinn/DefinitelyTyped,DeadAlready/DefinitelyTyped,benishouga/DefinitelyTyped,damianog/DefinitelyTyped,glenndierckx/DefinitelyTyped,pkhayundi/DefinitelyTyped,esperco/DefinitelyTyped,JaminFarr/DefinitelyTyped,tboyce/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,emanuelhp/DefinitelyTyped,mcliment/DefinitelyTyped,bilou84/DefinitelyTyped,tinganho/DefinitelyTyped,wcomartin/DefinitelyTyped,icereed/DefinitelyTyped,use-strict/DefinitelyTyped,abner/DefinitelyTyped,sandersky/DefinitelyTyped,jimthedev/DefinitelyTyped,martinduparc/DefinitelyTyped,chocolatechipui/DefinitelyTyped,gildorwang/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,micurs/DefinitelyTyped,benliddicott/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,Zzzen/DefinitelyTyped,magny/DefinitelyTyped,subjectix/DefinitelyTyped,rushi216/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,smrq/DefinitelyTyped,nmalaguti/DefinitelyTyped,HereSinceres/DefinitelyTyped,sclausen/DefinitelyTyped,basp/DefinitelyTyped,syntax42/DefinitelyTyped,ashwinr/DefinitelyTyped,vagarenko/DefinitelyTyped,Dominator008/DefinitelyTyped,blink1073/DefinitelyTyped,georgemarshall/DefinitelyTyped,pocesar/DefinitelyTyped,digitalpixies/DefinitelyTyped,jimthedev/DefinitelyTyped,gyohk/DefinitelyTyped,arma-gast/DefinitelyTyped,xStrom/DefinitelyTyped,fredgalvao/DefinitelyTyped,arcticwaters/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,takfjt/DefinitelyTyped,zensh/DefinitelyTyped,stephenjelfs/DefinitelyTyped,syuilo/DefinitelyTyped,jtlan/DefinitelyTyped,frogcjn/DefinitelyTyped,bennett000/DefinitelyTyped,giggio/DefinitelyTyped,UzEE/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,amir-arad/DefinitelyTyped,borisyankov/DefinitelyTyped,schmuli/DefinitelyTyped,nodeframe/DefinitelyTyped,mhegazy/DefinitelyTyped,wbuchwalter/DefinitelyTyped,rolandzwaga/DefinitelyTyped,progre/DefinitelyTyped,QuatroCode/DefinitelyTyped,pafflique/DefinitelyTyped,jaysoo/DefinitelyTyped,xswordsx/DefinitelyTyped,RX14/DefinitelyTyped,mjjames/DefinitelyTyped,Minishlink/DefinitelyTyped,Ridermansb/DefinitelyTyped,tarruda/DefinitelyTyped,behzad888/DefinitelyTyped,evandrewry/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,nitintutlani/DefinitelyTyped,tomtarrot/DefinitelyTyped,martinduparc/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,tscho/DefinitelyTyped,dsebastien/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,theyelllowdart/DefinitelyTyped,mvarblow/DefinitelyTyped,TheBay0r/DefinitelyTyped,mendix/DefinitelyTyped,GodsBreath/DefinitelyTyped,fredgalvao/DefinitelyTyped,EnableSoftware/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,fnipo/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,mshmelev/DefinitelyTyped,nabeix/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,benishouga/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,drinchev/DefinitelyTyped,hesselink/DefinitelyTyped,aroder/DefinitelyTyped,teddyward/DefinitelyTyped,zhiyiting/DefinitelyTyped,YousefED/DefinitelyTyped,schmuli/DefinitelyTyped,ErykB2000/DefinitelyTyped,furny/DefinitelyTyped,tigerxy/DefinitelyTyped,AgentME/DefinitelyTyped,Dashlane/DefinitelyTyped,chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,maglar0/DefinitelyTyped,martinduparc/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,QuatroCode/DefinitelyTyped,flyfishMT/DefinitelyTyped,ashwinr/DefinitelyTyped,lbesson/DefinitelyTyped,EnableSoftware/DefinitelyTyped,davidsidlinger/DefinitelyTyped,mshmelev/DefinitelyTyped,munxar/DefinitelyTyped,richardTowers/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,zuzusik/DefinitelyTyped,rcchen/DefinitelyTyped,rschmukler/DefinitelyTyped,shlomiassaf/DefinitelyTyped,ajtowf/DefinitelyTyped,ecramer89/DefinitelyTyped,abbasmhd/DefinitelyTyped,nfriend/DefinitelyTyped,aldo-roman/DefinitelyTyped,alainsahli/DefinitelyTyped,psnider/DefinitelyTyped,gyohk/DefinitelyTyped,paulmorphy/DefinitelyTyped,elisee/DefinitelyTyped,Zorgatone/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,muenchdo/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,georgemarshall/DefinitelyTyped,bdoss/DefinitelyTyped,Pro/DefinitelyTyped,trystanclarke/DefinitelyTyped,borisyankov/DefinitelyTyped,use-strict/DefinitelyTyped,applesaucers/lodash-invokeMap,nakakura/DefinitelyTyped,WritingPanda/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,alexdresko/DefinitelyTyped,egeland/DefinitelyTyped,gregoryagu/DefinitelyTyped,arusakov/DefinitelyTyped,nainslie/DefinitelyTyped,georgemarshall/DefinitelyTyped,OpenMaths/DefinitelyTyped,behzad888/DefinitelyTyped,mcrawshaw/DefinitelyTyped,dumbmatter/DefinitelyTyped,pocesar/DefinitelyTyped,spearhead-ea/DefinitelyTyped,dpsthree/DefinitelyTyped,alvarorahul/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,abner/DefinitelyTyped,teves-castro/DefinitelyTyped,bluong/DefinitelyTyped,Kuniwak/DefinitelyTyped,frogcjn/DefinitelyTyped,benishouga/DefinitelyTyped,DustinWehr/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mwain/DefinitelyTyped,jasonswearingen/DefinitelyTyped,aciccarello/DefinitelyTyped,Ptival/DefinitelyTyped,subash-a/DefinitelyTyped,bruennijs/DefinitelyTyped,nycdotnet/DefinitelyTyped,hellopao/DefinitelyTyped,Zzzen/DefinitelyTyped,bjfletcher/DefinitelyTyped,tjoskar/DefinitelyTyped,schmuli/DefinitelyTyped,MugeSo/DefinitelyTyped,shahata/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,Mek7/DefinitelyTyped,jesseschalken/DefinitelyTyped,xica/DefinitelyTyped,innerverse/DefinitelyTyped,stanislavHamara/DefinitelyTyped,ryan10132/DefinitelyTyped,MugeSo/DefinitelyTyped,wilfrem/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,daptiv/DefinitelyTyped,dydek/DefinitelyTyped,hellopao/DefinitelyTyped,danfma/DefinitelyTyped,gandjustas/DefinitelyTyped,aindlq/DefinitelyTyped,musicist288/DefinitelyTyped,rerezz/DefinitelyTyped,nelsonmorais/DefinitelyTyped,hellopao/DefinitelyTyped,mattanja/DefinitelyTyped,johan-gorter/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,AgentME/DefinitelyTyped,kmeurer/DefinitelyTyped,newclear/DefinitelyTyped,jraymakers/DefinitelyTyped,RedSeal-co/DefinitelyTyped,Penryn/DefinitelyTyped,unknownloner/DefinitelyTyped,teves-castro/DefinitelyTyped,nojaf/DefinitelyTyped,corps/DefinitelyTyped,smrq/DefinitelyTyped,applesaucers/lodash-invokeMap,angelobelchior8/DefinitelyTyped,brainded/DefinitelyTyped,dmoonfire/DefinitelyTyped,mareek/DefinitelyTyped,emanuelhp/DefinitelyTyped,bkristensen/DefinitelyTyped,scriby/DefinitelyTyped,one-pieces/DefinitelyTyped,timramone/DefinitelyTyped,chbrown/DefinitelyTyped,davidpricedev/DefinitelyTyped,greglockwood/DefinitelyTyped,acepoblete/DefinitelyTyped,moonpyk/DefinitelyTyped,jsaelhof/DefinitelyTyped,shovon/DefinitelyTyped,kuon/DefinitelyTyped,HPFOD/DefinitelyTyped,minodisk/DefinitelyTyped,almstrand/DefinitelyTyped,Karabur/DefinitelyTyped,Pipe-shen/DefinitelyTyped,MarlonFan/DefinitelyTyped,olemp/DefinitelyTyped,reppners/DefinitelyTyped,LordJZ/DefinitelyTyped,dsebastien/DefinitelyTyped,gcastre/DefinitelyTyped,axelcostaspena/DefinitelyTyped,M-Zuber/DefinitelyTyped,YousefED/DefinitelyTyped,lseguin42/DefinitelyTyped,mattblang/DefinitelyTyped,nycdotnet/DefinitelyTyped,jsaelhof/DefinitelyTyped,johan-gorter/DefinitelyTyped,biomassives/DefinitelyTyped,chadoliver/DefinitelyTyped,hx0day/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,nitintutlani/DefinitelyTyped,Nemo157/DefinitelyTyped,chrismbarr/DefinitelyTyped,aciccarello/DefinitelyTyped,Lorisu/DefinitelyTyped,KonaTeam/DefinitelyTyped,gedaiu/DefinitelyTyped,zuzusik/DefinitelyTyped,isman-usoh/DefinitelyTyped,egeland/DefinitelyTyped,chrismbarr/DefinitelyTyped,abbasmhd/DefinitelyTyped,HPFOD/DefinitelyTyped,rockclimber90/DefinitelyTyped,onecentlin/DefinitelyTyped,fearthecowboy/DefinitelyTyped,GregOnNet/DefinitelyTyped,yuit/DefinitelyTyped,drillbits/DefinitelyTyped,dariajung/DefinitelyTyped,scsouthw/DefinitelyTyped,hor-crux/DefinitelyTyped,isman-usoh/DefinitelyTyped,igorraush/DefinitelyTyped,glenndierckx/DefinitelyTyped,pwelter34/DefinitelyTyped,scatcher/DefinitelyTyped,goaty92/DefinitelyTyped,ayanoin/DefinitelyTyped,zuzusik/DefinitelyTyped,Bobjoy/DefinitelyTyped,florentpoujol/DefinitelyTyped,philippstucki/DefinitelyTyped,samwgoldman/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,felipe3dfx/DefinitelyTyped,jiaz/DefinitelyTyped,sledorze/DefinitelyTyped,brettle/DefinitelyTyped,Shiak1/DefinitelyTyped,shlomiassaf/DefinitelyTyped,psnider/DefinitelyTyped,rcchen/DefinitelyTyped,Gmulti/DefinitelyTyped,esperco/DefinitelyTyped,Seltzer/DefinitelyTyped,eugenpodaru/DefinitelyTyped,dreampulse/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,olivierlemasle/DefinitelyTyped,Almouro/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,Karabur/DefinitelyTyped,PopSugar/DefinitelyTyped,NCARalph/DefinitelyTyped,laco0416/DefinitelyTyped,dydek/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,raijinsetsu/DefinitelyTyped,DeluxZ/DefinitelyTyped,scriby/DefinitelyTyped,donnut/DefinitelyTyped,markogresak/DefinitelyTyped,stacktracejs/DefinitelyTyped,IAPark/DefinitelyTyped,chrilith/DefinitelyTyped,hiraash/DefinitelyTyped,kanreisa/DefinitelyTyped,danfma/DefinitelyTyped,mcrawshaw/DefinitelyTyped,Litee/DefinitelyTyped,takenet/DefinitelyTyped,nobuoka/DefinitelyTyped,pocesar/DefinitelyTyped,vpineda1996/DefinitelyTyped,olemp/DefinitelyTyped,eekboom/DefinitelyTyped,brentonhouse/DefinitelyTyped,jbrantly/DefinitelyTyped,gorcz/DefinitelyTyped,jeffbcross/DefinitelyTyped,leoromanovsky/DefinitelyTyped,cvrajeesh/DefinitelyTyped,bennett000/DefinitelyTyped,deeleman/DefinitelyTyped,syuilo/DefinitelyTyped,aqua89/DefinitelyTyped,MidnightDesign/DefinitelyTyped,quantumman/DefinitelyTyped,kalloc/DefinitelyTyped,pocke/DefinitelyTyped,Saneyan/DefinitelyTyped,Garciat/DefinitelyTyped,jraymakers/DefinitelyTyped,musically-ut/DefinitelyTyped,pwelter34/DefinitelyTyped,zuohaocheng/DefinitelyTyped,jasonswearingen/DefinitelyTyped,Zorgatone/DefinitelyTyped,grahammendick/DefinitelyTyped,duongphuhiep/DefinitelyTyped,elisee/DefinitelyTyped,Litee/DefinitelyTyped,superduper/DefinitelyTyped,uestcNaldo/DefinitelyTyped,michalczukm/DefinitelyTyped,psnider/DefinitelyTyped,bdoss/DefinitelyTyped,Fraegle/DefinitelyTyped,philippstucki/DefinitelyTyped,amanmahajan7/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,alextkachman/DefinitelyTyped,flyfishMT/DefinitelyTyped,mjjames/DefinitelyTyped,Jwsonic/DefinitelyTyped,erosb/DefinitelyTyped,hatz48/DefinitelyTyped,reppners/DefinitelyTyped,paxibay/DefinitelyTyped,nobuoka/DefinitelyTyped,vsavkin/DefinitelyTyped,Dashlane/DefinitelyTyped,dwango-js/DefinitelyTyped,dflor003/DefinitelyTyped,Pro/DefinitelyTyped,lbguilherme/DefinitelyTyped,sledorze/DefinitelyTyped,damianog/DefinitelyTyped,hafenr/DefinitelyTyped,florentpoujol/DefinitelyTyped,greglo/DefinitelyTyped,Riron/DefinitelyTyped,ml-workshare/DefinitelyTyped,ciriarte/DefinitelyTyped,sixinli/DefinitelyTyped,arcticwaters/DefinitelyTyped,herrmanno/DefinitelyTyped,vasek17/DefinitelyTyped,OpenMaths/DefinitelyTyped,Ptival/DefinitelyTyped,rschmukler/DefinitelyTyped | ---
+++
@@ -9,7 +9,7 @@
var piwik = new PiwikTracker(1, 'http://mywebsite.com/piwik.php');
// Optional: Respond to tracking errors
-piwik.on('error', function(err) {
+piwik.on('error', function(err : Error) {
console.log('error tracking request: ', err)
})
|
0cbb935ef133f176d5692ffe37c40e82b3c1aaa1 | e2e/app.e2e-spec.ts | e2e/app.e2e-spec.ts | import { KnownForWebPage } from './app.po';
describe('known-for-web App', function() {
let page: KnownForWebPage;
beforeEach(() => {
page = new KnownForWebPage();
});
it('should display website title', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Known For');
});
it('should show a person\'s name', () => {
page.navigateTo();
expect(page.getActorName()).not.toBeNull();
});
it('should show three movies the person is known for', () => {
page.navigateTo();
expect(page.getMovieCount()).toEqual(3);
});
it('should show a "Who?" button to change the displayed actor', () => {
page.navigateTo();
let lastActor = page.getActorName();
page.clickSkipButton();
expect(page.getActorName()).not.toEqual(lastActor);
});
});
| import { KnownForWebPage } from './app.po';
describe('known-for-web App', function() {
let page: KnownForWebPage;
beforeEach(() => {
page = new KnownForWebPage();
});
it('should display website title', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Known For');
});
it('should show a person\'s name', () => {
page.navigateTo();
expect(page.getActorName()).not.toBeNull();
});
it('should show up to three movies the person is known for', () => {
page.navigateTo();
expect(page.getMovieCount()).toBeGreaterThan(0);
});
it('should show a "Who?" button to change the displayed actor', () => {
page.navigateTo();
let lastActor = page.getActorName();
page.clickSkipButton();
expect(page.getActorName()).not.toEqual(lastActor);
});
});
| Handle actors with fewer than three featured films | Handle actors with fewer than three featured films
| TypeScript | isc | textbook/known-for-web,textbook/known-for-web,textbook/known-for-web | ---
+++
@@ -17,9 +17,9 @@
expect(page.getActorName()).not.toBeNull();
});
- it('should show three movies the person is known for', () => {
+ it('should show up to three movies the person is known for', () => {
page.navigateTo();
- expect(page.getMovieCount()).toEqual(3);
+ expect(page.getMovieCount()).toBeGreaterThan(0);
});
it('should show a "Who?" button to change the displayed actor', () => { |
8eea0846157df029faf46759d2bf514240f363fd | A2/quickstart/src/app/models/mocks.ts | A2/quickstart/src/app/models/mocks.ts | // mocks.ts
import { RacePart } from "./race-part.model";
export const RACE_PARTS: RacePart[] = [{
"id": 1,
"name": "Daytona Thunderdome",
"date": new Date('2512-01-04T14:00:00'),
"about": "Race through the ruins of an ancient Florida battle arena.",
"entryFee": 3200
}, {
"id": 2,
"name": "San Francisco Ruins",
"date": new Date('2512-07-03T20:00:00'),
"about": "Drift down the streets of a city almost sunk under the ocean.",
"entryFee": 4700
}, {
"id": 3,
"name": "New York City Skyline",
"date": new Date('2512-07-12T21:00:00'),
"about": "Fly between buildings in the electronic sky.",
"entryFee": 0
}];
| // mocks.ts
import { RacePart } from "./race-part.model";
export const RACE_PARTS: RacePart[] = [{
"id": 1,
"name": "Daytona Thunderdome",
"date": new Date('2512-01-04T14:00:00'),
"about": "Race through the ruins of an ancient Florida battle arena.",
"entryFee": 3200,
"isRacing": false,
"image": "/images/daytona_thunderdome.jpg",
"imageDescription": "Race track with laser lanes"
}, {
"id": 2,
"name": "San Francisco Ruins",
"date": new Date('2512-07-03T20:00:00'),
"about": "Drift down the streets of a city almost sunk under the ocean.",
"entryFee": 4700,
"isRacing": true,
"image": "/images/san_francisco_ruins.jpg",
"imageDescription": "Golden Gate Bridge with lasers"
}, {
"id": 3,
"name": "New York City Skyline",
"date": new Date('2512-07-12T21:00:00'),
"about": "Fly between buildings in the electronic sky.",
"entryFee": 4300,
"isRacing": true,
"image": "/images/new_york_city_skyline.jpg",
"imageDescription": "Bridge overlooking New York City"
}];
| Add new fields to mock | Add new fields to mock
| TypeScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -7,17 +7,26 @@
"name": "Daytona Thunderdome",
"date": new Date('2512-01-04T14:00:00'),
"about": "Race through the ruins of an ancient Florida battle arena.",
- "entryFee": 3200
+ "entryFee": 3200,
+ "isRacing": false,
+ "image": "/images/daytona_thunderdome.jpg",
+ "imageDescription": "Race track with laser lanes"
}, {
"id": 2,
"name": "San Francisco Ruins",
"date": new Date('2512-07-03T20:00:00'),
"about": "Drift down the streets of a city almost sunk under the ocean.",
- "entryFee": 4700
+ "entryFee": 4700,
+ "isRacing": true,
+ "image": "/images/san_francisco_ruins.jpg",
+ "imageDescription": "Golden Gate Bridge with lasers"
}, {
"id": 3,
"name": "New York City Skyline",
"date": new Date('2512-07-12T21:00:00'),
"about": "Fly between buildings in the electronic sky.",
- "entryFee": 0
+ "entryFee": 4300,
+ "isRacing": true,
+ "image": "/images/new_york_city_skyline.jpg",
+ "imageDescription": "Bridge overlooking New York City"
}]; |
f8fcadb47a0247427ee395d10f91db565a39efed | src/extension.ts | src/extension.ts | 'use strict';
import * as vscode from 'vscode';
import {PathAutocomplete} from './features/PathAutoCompleteProvider';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('*', new PathAutocomplete(), '/'));
}
// this method is called when your extension is deactivated
export function deactivate() {
}
| 'use strict';
import * as vscode from 'vscode';
import {PathAutocomplete} from './features/PathAutocompleteProvider';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('*', new PathAutocomplete(), '/'));
}
// this method is called when your extension is deactivated
export function deactivate() {
}
| Fix import issue due to case-sensitivity | Fix import issue due to case-sensitivity
| TypeScript | mit | ionutvmi/path-autocomplete,ionutvmi/path-autocomplete | ---
+++
@@ -1,6 +1,6 @@
'use strict';
import * as vscode from 'vscode';
-import {PathAutocomplete} from './features/PathAutoCompleteProvider';
+import {PathAutocomplete} from './features/PathAutocompleteProvider';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.languages.registerCompletionItemProvider('*', new PathAutocomplete(), '/')); |
2346c74bb6e5554dbb28daef304cfa79f59f025d | src/Store.ts | src/Store.ts | import { Flow } from './Flow';
import { Soak, completeSoak } from './Soak';
import { Observable, Subject } from 'rxjs';
/**
* The dispatch and state that comprises a dw Store.
*/
export type Store<State, Action> = {
dispatch$: Subject<Action>;
state$: Observable<State>;
};
/**
* Links a flow, soak and initial state to create a store object.
* Objects passed to the dispatch function will be filtered through the flow
* then scanned to apply state changes defined by the soak, starting with the initial state.
*
* @param flow the transformations to the action stream
* @param soak the transformations to state based on actions
* @param initialState the initial state prior to any applied soaks.
*/
export const createStore = <State, Action>(
flow: Flow<Action>,
soak: Soak<State, Action>,
initialState?: State
): Store<State, Action> => {
const subject$ = new Subject<Action>();
const fullSoak = completeSoak(soak);
return {
dispatch$: subject$,
state$: flow(subject$).scan<Action, State>(fullSoak, initialState).share()
};
};
export default createStore; | import { Flow } from './Flow';
import { Soak, completeSoak } from './Soak';
import { Observable, Subject } from 'rxjs';
/**
* The dispatch and state that comprises a dw Store.
*/
export type Store<State, Action> = {
/** dispatch actions into the store */
dispatch$: Subject<Action>;
/** observable of actions after flows applied */
flow$: Observable<Action>
/** observable of state after flows and soaks applied */
state$: Observable<State>;
};
/**
* Links a flow, soak and initial state to create a store object.
* Objects passed to the dispatch function will be filtered through the flow
* then scanned to apply state changes defined by the soak, starting with the initial state.
*
* @param flow the transformations to the action stream
* @param soak the transformations to state based on actions
* @param initialState the initial state prior to any applied soaks.
*/
export const createStore = <State, Action>(
flow: Flow<Action>,
soak: Soak<State, Action>,
initialState?: State
): Store<State, Action> => {
// insert
const subject$ = new Subject<Action>();
// flow
const flow$ = flow(subject$).share();
// soak
const fullSoak = completeSoak(soak);
const scan$ = flow$.scan<Action, State>(fullSoak, initialState);
// state
const state$ = (initialState
? Observable.concat(Observable.of(initialState), scan$)
: scan$).share();
const store = {
dispatch$: subject$,
flow$: flow$,
state$: state$
};
// empty action through to trigger any initial states.
return store;
};
export default createStore; | Apply initial state (concact) if provided so that even if no actions sent yet, the initial state is provided to subscribers. | Apply initial state (concact) if provided so that even if no actions sent yet, the initial state is provided to subscribers.
Also publish the end of the flow observable as some components etc. might want to work purely off the action stream (e.g. notifications)
| TypeScript | apache-2.0 | elhedran/rxjs-dew,elhedran/rxjs-dew | ---
+++
@@ -6,7 +6,11 @@
* The dispatch and state that comprises a dw Store.
*/
export type Store<State, Action> = {
+ /** dispatch actions into the store */
dispatch$: Subject<Action>;
+ /** observable of actions after flows applied */
+ flow$: Observable<Action>
+ /** observable of state after flows and soaks applied */
state$: Observable<State>;
};
@@ -24,12 +28,25 @@
soak: Soak<State, Action>,
initialState?: State
): Store<State, Action> => {
+ // insert
const subject$ = new Subject<Action>();
+ // flow
+ const flow$ = flow(subject$).share();
+ // soak
const fullSoak = completeSoak(soak);
- return {
+ const scan$ = flow$.scan<Action, State>(fullSoak, initialState);
+ // state
+ const state$ = (initialState
+ ? Observable.concat(Observable.of(initialState), scan$)
+ : scan$).share();
+
+ const store = {
dispatch$: subject$,
- state$: flow(subject$).scan<Action, State>(fullSoak, initialState).share()
+ flow$: flow$,
+ state$: state$
};
+ // empty action through to trigger any initial states.
+ return store;
};
export default createStore; |
18c8be74d0f57490192ebcfb63400574e01adf87 | src/moves.ts | src/moves.ts | export function getMoves(grid: boolean[]): number[] {
return grid
.map((value, index) => value == undefined ? index : undefined)
.filter(value => value != undefined);
}
| import { Grid, Move } from './definitions';
export function getMoves(grid: Grid): Move[] {
return grid
.map((value, index) => value == undefined ? index : undefined)
.filter(value => value != undefined);
}
| Make getMoves function use Grid and Move | Make getMoves function use Grid and Move
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -1,4 +1,6 @@
-export function getMoves(grid: boolean[]): number[] {
+import { Grid, Move } from './definitions';
+
+export function getMoves(grid: Grid): Move[] {
return grid
.map((value, index) => value == undefined ? index : undefined)
.filter(value => value != undefined); |
1d390997f601ca78331ca844779a3a5ea73b38e0 | packages/language-server-ruby/src/util/TreeSitterFactory.ts | packages/language-server-ruby/src/util/TreeSitterFactory.ts | import path from 'path';
import Parser from 'web-tree-sitter';
const TREE_SITTER_RUBY_WASM = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
const TreeSitterFactory = {
language: null,
async initalize(): Promise<void> {
await Parser.init();
console.debug(`Loading Ruby tree-sitter syntax from ${TREE_SITTER_RUBY_WASM}`);
this.language = await Parser.Language.load(TREE_SITTER_RUBY_WASM);
},
build(): Parser {
const parser = new Parser();
parser.setLanguage(this.language);
return parser;
},
};
export default TreeSitterFactory;
| import path from 'path';
import fs from 'fs';
import Parser from 'web-tree-sitter';
const TREE_SITTER_RUBY_WASM = ((): string => {
let wasmPath = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
if (!fs.existsSync(wasmPath)) {
wasmPath = path.resolve(__dirname, '..', 'tree-sitter-ruby.wasm');
}
return wasmPath;
})();
const TreeSitterFactory = {
language: null,
async initalize(): Promise<void> {
await Parser.init();
console.debug(`Loading Ruby tree-sitter syntax from ${TREE_SITTER_RUBY_WASM}`);
this.language = await Parser.Language.load(TREE_SITTER_RUBY_WASM);
},
build(): Parser {
const parser = new Parser();
parser.setLanguage(this.language);
return parser;
},
};
export default TreeSitterFactory;
| Tweak resolving location of tree-sitter-ruby.wasm | Tweak resolving location of tree-sitter-ruby.wasm
| TypeScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -1,7 +1,15 @@
import path from 'path';
+import fs from 'fs';
import Parser from 'web-tree-sitter';
-const TREE_SITTER_RUBY_WASM = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
+const TREE_SITTER_RUBY_WASM = ((): string => {
+ let wasmPath = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
+ if (!fs.existsSync(wasmPath)) {
+ wasmPath = path.resolve(__dirname, '..', 'tree-sitter-ruby.wasm');
+ }
+
+ return wasmPath;
+})();
const TreeSitterFactory = {
language: null, |
696c27d0feb38072c54a231c5b960eef5c95a0bf | src/Components/Authentication/Mobile/ForgotPasswordForm.tsx | src/Components/Authentication/Mobile/ForgotPasswordForm.tsx | import {
Error,
Footer,
FormContainer as Form,
MobileContainer,
MobileHeader,
MobileInnerWrapper,
SubmitButton,
} from "Components/Authentication/commonElements"
import Input from "Components/Input"
import { Formik, FormikProps } from "formik"
import React from "react"
import { FormComponentType, InputValues } from "../Types"
import { ForgotPasswordValidator } from "../Validators"
export const MobileForgotPasswordForm: FormComponentType = props => {
return (
<Formik
initialValues={props.values}
onSubmit={props.handleSubmit}
validationSchema={ForgotPasswordValidator}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
isValid,
status,
}: FormikProps<InputValues>) => {
return (
<MobileContainer>
<MobileInnerWrapper>
<Form onSubmit={handleSubmit} height={270}>
<MobileHeader>Reset your password</MobileHeader>
<Input
block
quick
error={errors.email}
placeholder="Enter your email address"
name="email"
label="Email"
type="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
{status &&
!status.success && <Error show>{status.error}</Error>}
<SubmitButton disabled={isSubmitting}>Next</SubmitButton>
<Footer
handleTypeChange={props.handleTypeChange}
mode="forgot"
/>
</Form>
</MobileInnerWrapper>
</MobileContainer>
)
}}
</Formik>
)
}
| import {
Error,
Footer,
FormContainer as Form,
MobileContainer,
MobileHeader,
MobileInnerWrapper,
SubmitButton,
} from "Components/Authentication/commonElements"
import Input from "Components/Input"
import { Formik, FormikProps } from "formik"
import React from "react"
import { FormComponentType, InputValues } from "../Types"
import { ForgotPasswordValidator } from "../Validators"
export const MobileForgotPasswordForm: FormComponentType = props => {
return (
<Formik
initialValues={props.values}
onSubmit={props.handleSubmit}
validationSchema={ForgotPasswordValidator}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
isValid,
status,
}: FormikProps<InputValues>) => {
return (
<MobileContainer>
<MobileInnerWrapper>
<Form onSubmit={handleSubmit} height={270}>
<MobileHeader>Reset your password</MobileHeader>
<Input
block
quick
error={errors.email}
placeholder="Enter your email address"
name="email"
label="Email"
type="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
{status &&
!status.success && <Error show>{status.error}</Error>}
<SubmitButton disabled={isSubmitting}>
Send me reset instructions
</SubmitButton>
<Footer
handleTypeChange={props.handleTypeChange}
mode="forgot"
/>
</Form>
</MobileInnerWrapper>
</MobileContainer>
)
}}
</Formik>
)
}
| Change reset password button copy | Change reset password button copy
| TypeScript | mit | xtina-starr/reaction,artsy/reaction,artsy/reaction,artsy/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -50,7 +50,9 @@
/>
{status &&
!status.success && <Error show>{status.error}</Error>}
- <SubmitButton disabled={isSubmitting}>Next</SubmitButton>
+ <SubmitButton disabled={isSubmitting}>
+ Send me reset instructions
+ </SubmitButton>
<Footer
handleTypeChange={props.handleTypeChange}
mode="forgot" |
c7e884d0544daaa55cba9aabdd11316d0f5a02c8 | src/resources/interfaces.ts | src/resources/interfaces.ts | interface Parameter {
name: string;
type: string;
example_values: string[];
comment: string;
required: boolean;
}
interface Action {
name: string;
method: string;
path: string;
comment: string;
params?: Parameter[];
}
interface Resource {
name: string;
comment: string;
templates: any[];
properties: any[];
actions: Action[];
}
| interface Parameter {
name: string;
type: string;
example_values?: string[];
comment: string;
required?: boolean;
}
interface Action {
name: string;
method: string;
path: string;
comment: string;
params?: Parameter[];
}
interface Resource {
name: string;
comment: string;
templates: any[];
properties: any[];
actions: Action[];
}
| Make Parameter interface less strict | Make Parameter interface less strict
| TypeScript | mit | Asana/api-explorer,Asana/api-explorer | ---
+++
@@ -1,9 +1,9 @@
interface Parameter {
name: string;
type: string;
- example_values: string[];
+ example_values?: string[];
comment: string;
- required: boolean;
+ required?: boolean;
}
interface Action { |
0ee644c4ab9f17915e902cf16d68b63ee01322d4 | src/app/core/configuration/boot/config-reader.ts | src/app/core/configuration/boot/config-reader.ts | import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {MDInternal} from '../../../components/messages/md-internal';
@Injectable()
/**
* @author Daniel de Oliveira
* @author Thomas Kleinke
*/
export class ConfigReader {
constructor(private http: HttpClient) {}
public read(path: string): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get(path).subscribe((data_: any) => {
let data;
try {
data = data_;
} catch(e) {
reject([MDInternal.CONFIG_READER_ERROR_INVALID_JSON, path]);
}
try {
resolve(data);
} catch(e) {
console.error(e);
}
});
});
}
} | import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {MDInternal} from '../../../components/messages/md-internal';
@Injectable()
/**
* @author Daniel de Oliveira
* @author Thomas Kleinke
*/
export class ConfigReader {
constructor(private http: HttpClient) {}
public read(path: string): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get(path).subscribe(
(data: any) => resolve(data),
(error: any) => {
console.error(error);
reject([MDInternal.CONFIG_READER_ERROR_INVALID_JSON, path]);
}
);
});
}
}
| Fix error handling in config reader | Fix error handling in config reader
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -16,21 +16,13 @@
return new Promise((resolve, reject) => {
- this.http.get(path).subscribe((data_: any) => {
-
- let data;
- try {
- data = data_;
- } catch(e) {
+ this.http.get(path).subscribe(
+ (data: any) => resolve(data),
+ (error: any) => {
+ console.error(error);
reject([MDInternal.CONFIG_READER_ERROR_INVALID_JSON, path]);
}
-
- try {
- resolve(data);
- } catch(e) {
- console.error(e);
- }
- });
+ );
});
}
} |
5e001c896a7d5f632b6cd9e9ce7447cad90f64d2 | client/Settings/components/CommandInfo.ts | client/Settings/components/CommandInfo.ts | export const CommandInfoById = {
"start-encounter": "The first combatant in the initiative order will become active"
} | export const CommandInfoById = {
"start-encounter":
"The first combatant in the initiative order will become active.",
"clear-encounter":
"Remove all combatants, including player characters, and end the encounter.",
"clean-encounter": "Remove all creatures and NPCs, and end the encounter.",
"quick-add":
"Add a simple combatant with just the basics: Name, HP, AC, and Initiative Modifier.",
"player-window":
"You can share the URL of your player view so players can follow your combat on any other device.",
"apply-temporary-hp":
"Temporary HP follows the D&D 5e rules. When a combatant is granted THP, it won't stack with existing THP.",
"add-tag":
"Tags can be used to track conditions like \"Stunned\" or \"Concentrating\". " +
"You can set a timer to automatically remove a tag after a set number of rounds have passed.",
"update-notes":
"You can keep long-form notes to track things like illnesses, inventory, and spell slots. " +
"These notes will persist across encounters when they are set on Characters.",
"edit-statblock":
"If you edit a creature's statblock, it will only affect this combatant. " +
"If you edit a character's statblock, it will persist across encounters.",
"link-initiative":
"Creatures in an initiative group will keep the same initiative count. " +
"Group members keep their initiative in sync when you roll or edit " +
"initiative, and you can unlink individual members."
};
| Add info for several commands | Add info for several commands
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -1,3 +1,26 @@
export const CommandInfoById = {
- "start-encounter": "The first combatant in the initiative order will become active"
-}
+ "start-encounter":
+ "The first combatant in the initiative order will become active.",
+ "clear-encounter":
+ "Remove all combatants, including player characters, and end the encounter.",
+ "clean-encounter": "Remove all creatures and NPCs, and end the encounter.",
+ "quick-add":
+ "Add a simple combatant with just the basics: Name, HP, AC, and Initiative Modifier.",
+ "player-window":
+ "You can share the URL of your player view so players can follow your combat on any other device.",
+ "apply-temporary-hp":
+ "Temporary HP follows the D&D 5e rules. When a combatant is granted THP, it won't stack with existing THP.",
+ "add-tag":
+ "Tags can be used to track conditions like \"Stunned\" or \"Concentrating\". " +
+ "You can set a timer to automatically remove a tag after a set number of rounds have passed.",
+ "update-notes":
+ "You can keep long-form notes to track things like illnesses, inventory, and spell slots. " +
+ "These notes will persist across encounters when they are set on Characters.",
+ "edit-statblock":
+ "If you edit a creature's statblock, it will only affect this combatant. " +
+ "If you edit a character's statblock, it will persist across encounters.",
+ "link-initiative":
+ "Creatures in an initiative group will keep the same initiative count. " +
+ "Group members keep their initiative in sync when you roll or edit " +
+ "initiative, and you can unlink individual members."
+}; |
65d411e510df73b98a5c27e035d74ec606d041da | src/boot.ts | src/boot.ts | import "angular";
import "angular-animate";
import "angular-material";
import "../node_modules/angular-aria/angular-aria.js";
//import "MainController";
import {MainController} from "./controllers/mainController.ts";
angular.module('projectTemplateApp', ['ngMaterial'])
.controller('mainController', MainController); | import "angular";
import "angular-animate";
import "angular-material";
import "../node_modules/angular-aria/angular-aria.js";
import {MainController} from "./controllers/mainController.ts";
angular.module('projectTemplateApp', ['ngMaterial'])
.controller('mainController', MainController); | Remove old controller import statement… | Remove old controller import statement…
| TypeScript | mit | rsparrow/angular-material-typescript-webpack,rsparrow/angular-material-typescript-webpack,rsparrow/angular-material-typescript-webpack | ---
+++
@@ -1,10 +1,10 @@
import "angular";
import "angular-animate";
+
+
import "angular-material";
import "../node_modules/angular-aria/angular-aria.js";
-
-//import "MainController";
import {MainController} from "./controllers/mainController.ts";
|
7a79953f0222dc033aafac70169477305d62fb5f | test/e2e/security/security_test.ts | test/e2e/security/security_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {reloadDevTools} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {closeSecurityTab, navigateToSecurityTab, openSecurityPanelFromCommandMenu, openSecurityPanelFromMoreTools, securityPanelContentIsLoaded, securityTabDoesNotExist, securityTabExists} from '../helpers/security-helpers.js';
describe('The Security Panel', async () => {
it('is open by default when devtools initializes', async () => {
await navigateToSecurityTab();
});
it('closes without crashing and stays closed after reloading tools', async () => {
await closeSecurityTab();
await reloadDevTools();
await securityTabDoesNotExist();
});
it('appears under More tools after being closed', async () => {
await closeSecurityTab();
await openSecurityPanelFromMoreTools();
await reloadDevTools({selectedPanel: {name: 'security'}});
await securityTabExists();
});
// Test flaky on Windows
it.skipOnPlatforms(['win32'], '[crbug.com/1183304]: can be opened from command menu after being closed', async () => {
await closeSecurityTab();
await openSecurityPanelFromCommandMenu();
});
it('opens if the query param "panel" is set', async () => {
await closeSecurityTab();
await reloadDevTools({queryParams: {panel: 'security'}});
await securityTabExists();
await securityPanelContentIsLoaded();
});
});
| // 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 {reloadDevTools} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {closeSecurityTab, navigateToSecurityTab, openSecurityPanelFromCommandMenu, openSecurityPanelFromMoreTools, securityPanelContentIsLoaded, securityTabDoesNotExist, securityTabExists} from '../helpers/security-helpers.js';
describe('The Security Panel', async () => {
it('is open by default when devtools initializes', async () => {
await navigateToSecurityTab();
});
it('closes without crashing and stays closed after reloading tools', async () => {
await closeSecurityTab();
await reloadDevTools();
await securityTabDoesNotExist();
});
it('appears under More tools after being closed', async () => {
await closeSecurityTab();
await openSecurityPanelFromMoreTools();
await reloadDevTools({selectedPanel: {name: 'security'}});
await securityTabExists();
});
it('can be opened from command menu after being closed', async () => {
await closeSecurityTab();
await openSecurityPanelFromCommandMenu();
});
it('opens if the query param "panel" is set', async () => {
await closeSecurityTab();
await reloadDevTools({queryParams: {panel: 'security'}});
await securityTabExists();
await securityPanelContentIsLoaded();
});
});
| Enable a security panel test | Enable a security panel test
Fixed: 1183304
Change-Id: Ib9a5e423d74448428ad7aed8fa1555c449cd0272
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3598791
Reviewed-by: Simon Zünd <[email protected]>
Commit-Queue: Alex Rudenko <[email protected]>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -24,8 +24,7 @@
await securityTabExists();
});
- // Test flaky on Windows
- it.skipOnPlatforms(['win32'], '[crbug.com/1183304]: can be opened from command menu after being closed', async () => {
+ it('can be opened from command menu after being closed', async () => {
await closeSecurityTab();
await openSecurityPanelFromCommandMenu();
}); |
dc42be5a79e9dbd3056697351bd7e76d8fef6f59 | addons/contexts/src/preview/frameworks/preact.ts | addons/contexts/src/preview/frameworks/preact.ts | import Preact from 'preact';
import { createAddonDecorator, Render } from '../../index';
import { ContextsPreviewAPI } from '../ContextsPreviewAPI';
/**
* This is the framework specific bindings for Preact.
* '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode'.
*/
export const renderPreact: Render<Preact.VNode> = (contextNodes, propsMap, getStoryVNode) => {
const { getRendererFrom } = ContextsPreviewAPI();
return getRendererFrom(Preact.h)(contextNodes, propsMap, getStoryVNode);
};
export const withContexts = createAddonDecorator(renderPreact);
| import { h, VNode } from 'preact';
import { createAddonDecorator, Render } from '../../index';
import { ContextsPreviewAPI } from '../ContextsPreviewAPI';
/**
* This is the framework specific bindings for Preact.
* '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode'.
*/
export const renderPreact: Render<VNode> = (contextNodes, propsMap, getStoryVNode) => {
const { getRendererFrom } = ContextsPreviewAPI();
return getRendererFrom(h)(contextNodes, propsMap, getStoryVNode);
};
export const withContexts = createAddonDecorator(renderPreact);
| Fix 'cannot read property h of undefined' | Fix 'cannot read property h of undefined'
| TypeScript | mit | storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook | ---
+++
@@ -1,4 +1,4 @@
-import Preact from 'preact';
+import { h, VNode } from 'preact';
import { createAddonDecorator, Render } from '../../index';
import { ContextsPreviewAPI } from '../ContextsPreviewAPI';
@@ -6,9 +6,9 @@
* This is the framework specific bindings for Preact.
* '@storybook/preact' expects the returning object from a decorator to be a 'Preact vNode'.
*/
-export const renderPreact: Render<Preact.VNode> = (contextNodes, propsMap, getStoryVNode) => {
+export const renderPreact: Render<VNode> = (contextNodes, propsMap, getStoryVNode) => {
const { getRendererFrom } = ContextsPreviewAPI();
- return getRendererFrom(Preact.h)(contextNodes, propsMap, getStoryVNode);
+ return getRendererFrom(h)(contextNodes, propsMap, getStoryVNode);
};
export const withContexts = createAddonDecorator(renderPreact); |
25c132b5193d7fbecd3317feb443a68ae5698b5d | 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
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");
| 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
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();
counterActions.increment.next();
nameActions.appName.next("Foo");
counterActions.decrement.next(5);
counterActions.increment.next(8);
nameActions.appName.next("Bar");
| Edit example to show default argument usage | Edit example to show default argument usage
| TypeScript | mit | Dynalon/redux-pattern-with-rx,Dynalon/redux-pattern-with-rx | ---
+++
@@ -35,8 +35,8 @@
});
// dispatch some actions
-counterActions.increment.next(1);
-counterActions.increment.next(1);
+counterActions.increment.next();
+counterActions.increment.next();
nameActions.appName.next("Foo");
counterActions.decrement.next(5);
counterActions.increment.next(8); |
86e2288e1a0288c8fd720f558693efa35ff8de7f | typescript/sorting/merge-sort.ts | typescript/sorting/merge-sort.ts | // Top-down implementation with lists
function merge<T>(left: T[], right: T[]): T[] {
const merged = [];
let firstLeft = left[0];
let firstRight = right[0];
while (left.length && right.length) {
if (firstLeft <= firstRight) {
merged.push(firstLeft);
left.shift();
firstLeft = left[0];
} else {
merged.push(firstRight);
right.shift();
firstRight = right[0];
}
}
while (left.length) {
merged.push(left.shift());
}
while (right.length) {
merged.push(right.shift());
}
return merged;
}
export function mergeSort<T>(arr: T[]): T[] {
if (arr.length <= 1) {
return arr;
}
let left = [];
let right = [];
const mid = arr.length / 2;
for (let i = 0; i < arr.length; i++) {
const el = arr[i];
if (i < mid) {
left.push(el);
} else {
right.push(el);
}
}
left = mergeSort(left);
right = mergeSort(right);
return merge<T>(left, right);
}
// Demo:
let arr = [3, 7, 6, 1, 2, 9, 1];
arr = mergeSort<number>(arr);
console.log(arr);
| // Top-down implementation with lists
function merge<T>(left: T[], right: T[]): T[] {
const merged = [];
let firstLeft = left[0];
let firstRight = right[0];
while (left.length && right.length) {
if (firstLeft <= firstRight) {
merged.push(firstLeft);
left.shift();
firstLeft = left[0];
} else {
merged.push(firstRight);
right.shift();
firstRight = right[0];
}
}
while (left.length) {
merged.push(left.shift());
}
while (right.length) {
merged.push(right.shift());
}
return merged;
}
export function mergeSort<T>(arr: T[]): T[] {
if (arr.length <= 1) {
return arr;
}
const mid = arr.length / 2;
let left = arr.slice(0, mid);
let right = arr.slice(mid, arr.length);
left = mergeSort(left);
right = mergeSort(right);
return merge<T>(left, right);
}
// Demo:
let arr = [3, 7, 6, 1, 2, 9, 1];
arr = mergeSort<number>(arr);
console.log(arr);
| Simplify TS merge sort code | Simplify TS merge sort code
| TypeScript | mit | hAWKdv/DataStructures,hAWKdv/DataStructures | ---
+++
@@ -33,18 +33,9 @@
return arr;
}
- let left = [];
- let right = [];
const mid = arr.length / 2;
-
- for (let i = 0; i < arr.length; i++) {
- const el = arr[i];
- if (i < mid) {
- left.push(el);
- } else {
- right.push(el);
- }
- }
+ let left = arr.slice(0, mid);
+ let right = arr.slice(mid, arr.length);
left = mergeSort(left);
right = mergeSort(right); |
5c22232fd949908963229409444f6893b169604d | app/components/resources/view/operation-views.ts | app/components/resources/view/operation-views.ts | import {ViewDefinition} from 'idai-components-2/configuration';
/**
* @author Thomas Kleinke
* @author Daniel de Oliveira
*/
export class OperationViews {
constructor(
private _: any
) {
if (!_) _ = [];
}
public get() {
return this._;
}
public getLabelForName(name: any) {
for (let view of this._) {
if (view.name == name) return view.mainTypeLabel;
}
return undefined;
}
public getTypeForName(name: any) {
for (let view of this._) {
if (view.name == name) return view.operationSubtype;
}
return undefined;
}
public getViewNameForOperationSubtype(operationSubtypeName: string): string|undefined {
const viewDefinitions: Array<ViewDefinition> = this._;
let viewName: string|undefined = undefined;
for (let view of viewDefinitions) {
if (view.operationSubtype == operationSubtypeName) {
viewName = view.name;
break;
}
}
return viewName;
}
} | import {ViewDefinition} from 'idai-components-2/configuration';
/**
* @author Thomas Kleinke
* @author Daniel de Oliveira
*/
export class OperationViews {
constructor(
private _: any
) {
if (!_) _ = [];
}
public get() {
return this._;
}
public getLabelForName(name: string) {
const view = this.namedView(name);
return (view) ? view.mainTypeLabel : undefined;
}
public getTypeForName(name: string) {
const view = this.namedView(name);
return (view) ? view.operationSubtype : undefined;
}
private namedView = (name: string) => this._.find(this.sameViewName(name));
private sameViewName = (name: string) => (view: any) => name == view.name;
public getViewNameForOperationSubtype(operationSubtypeName: string): string|undefined {
const viewDefinitions: Array<ViewDefinition> = this._;
let viewName: string|undefined = undefined;
for (let view of viewDefinitions) {
if (view.operationSubtype == operationSubtypeName) {
viewName = view.name;
break;
}
}
return viewName;
}
} | Use fp and find method | Use fp and find method
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -20,22 +20,24 @@
}
- public getLabelForName(name: any) {
+ public getLabelForName(name: string) {
- for (let view of this._) {
- if (view.name == name) return view.mainTypeLabel;
- }
- return undefined;
+ const view = this.namedView(name);
+ return (view) ? view.mainTypeLabel : undefined;
}
- public getTypeForName(name: any) {
+ public getTypeForName(name: string) {
- for (let view of this._) {
- if (view.name == name) return view.operationSubtype;
- }
- return undefined;
+ const view = this.namedView(name);
+ return (view) ? view.operationSubtype : undefined;
}
+
+
+ private namedView = (name: string) => this._.find(this.sameViewName(name));
+
+
+ private sameViewName = (name: string) => (view: any) => name == view.name;
public getViewNameForOperationSubtype(operationSubtypeName: string): string|undefined { |
6d5da9d0b3a4d40ef432ce7edb4dcef432b5906a | helpers/coreInterfaces.ts | helpers/coreInterfaces.ts | /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: String
password: String
loginDetails?: Object
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectToServerOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
/**
* Shorter name, less typing :-)
*/
export interface ConnectOptions extends ConnectToServerOptions {
}
export interface ConnectionMap {
[name:string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectToServerOptions(options?:any):ConnectToServerOptions {
var defaults = <ConnectToServerOptions> {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
var opts = options || {};
return angular.extend(defaults, opts);
}
export function createConnectOptions(options?:any) {
return <ConnectOptions> createConnectToServerOptions(options);
}
}
| /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: String
password: String
loginDetails?: Object
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
export interface ConnectionMap {
[name: string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectOptions(options?: any): ConnectOptions {
let defaults: ConnectOptions = {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
let opts = options || {};
return angular.extend(defaults, opts);
}
}
| Remove ConnectToServerOptions interface in favor of shorter ConnectOptions | Remove ConnectToServerOptions interface in favor of shorter ConnectOptions
| TypeScript | apache-2.0 | hawtio/hawtio-utilities,hawtio/hawtio-utilities,hawtio/hawtio-utilities | ---
+++
@@ -14,7 +14,7 @@
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
- export interface ConnectToServerOptions {
+ export interface ConnectOptions {
scheme: String;
host?: String;
port?: Number;
@@ -28,23 +28,16 @@
secure: boolean;
}
- /**
- * Shorter name, less typing :-)
- */
- export interface ConnectOptions extends ConnectToServerOptions {
-
- }
-
export interface ConnectionMap {
- [name:string]: ConnectOptions;
+ [name: string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
- export function createConnectToServerOptions(options?:any):ConnectToServerOptions {
- var defaults = <ConnectToServerOptions> {
+ export function createConnectOptions(options?: any): ConnectOptions {
+ let defaults: ConnectOptions = {
scheme: 'http',
host: null,
port: null,
@@ -57,13 +50,8 @@
name: null,
secure: false
};
- var opts = options || {};
+ let opts = options || {};
return angular.extend(defaults, opts);
}
- export function createConnectOptions(options?:any) {
- return <ConnectOptions> createConnectToServerOptions(options);
- }
-
-
} |
afbc89ba69b86563653b9a314872b2e509b4c619 | saleor/static/dashboard-next/components/DateFormatter/DateFormatter.tsx | saleor/static/dashboard-next/components/DateFormatter/DateFormatter.tsx | import Tooltip from "@material-ui/core/Tooltip";
import * as moment from "moment-timezone";
import * as React from "react";
import ReactMoment from "react-moment";
import { LocaleConsumer } from "../Locale";
import { TimezoneConsumer } from "../Timezone";
import { Consumer } from "./DateContext";
interface DateFormatterProps {
date: string;
}
const DateFormatter: React.StatelessComponent<DateFormatterProps> = ({
date
}) => {
return (
<LocaleConsumer>
{locale => (
<TimezoneConsumer>
{tz => (
<Consumer>
{currentDate => (
<Tooltip
title={moment(date)
.locale(locale)
.tz(tz)
.toLocaleString()}
>
<ReactMoment from={currentDate} locale={locale} tz={tz}>
{date}
</ReactMoment>
</Tooltip>
)}
</Consumer>
)}
</TimezoneConsumer>
)}
</LocaleConsumer>
);
};
export default DateFormatter;
| import Tooltip from "@material-ui/core/Tooltip";
import * as moment from "moment-timezone";
import * as React from "react";
import ReactMoment from "react-moment";
import { LocaleConsumer } from "../Locale";
import { TimezoneConsumer } from "../Timezone";
import { Consumer } from "./DateContext";
interface DateFormatterProps {
date: string;
}
const DateFormatter: React.StatelessComponent<DateFormatterProps> = ({
date
}) => {
const getTitle = (value: string, locale?: string, tz?: string) => {
let date = moment(value).locale(locale);
if (tz !== undefined) {
date = date.tz(tz);
}
return date.toLocaleString();
};
return (
<LocaleConsumer>
{locale => (
<TimezoneConsumer>
{tz => (
<Consumer>
{currentDate => (
<Tooltip title={getTitle(date, locale, tz)}>
<ReactMoment from={currentDate} locale={locale} tz={tz}>
{date}
</ReactMoment>
</Tooltip>
)}
</Consumer>
)}
</TimezoneConsumer>
)}
</LocaleConsumer>
);
};
export default DateFormatter;
| Fix date formatting when timezone is missing | Fix date formatting when timezone is missing
| TypeScript | bsd-3-clause | mociepka/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor | ---
+++
@@ -14,6 +14,13 @@
const DateFormatter: React.StatelessComponent<DateFormatterProps> = ({
date
}) => {
+ const getTitle = (value: string, locale?: string, tz?: string) => {
+ let date = moment(value).locale(locale);
+ if (tz !== undefined) {
+ date = date.tz(tz);
+ }
+ return date.toLocaleString();
+ };
return (
<LocaleConsumer>
{locale => (
@@ -21,12 +28,7 @@
{tz => (
<Consumer>
{currentDate => (
- <Tooltip
- title={moment(date)
- .locale(locale)
- .tz(tz)
- .toLocaleString()}
- >
+ <Tooltip title={getTitle(date, locale, tz)}>
<ReactMoment from={currentDate} locale={locale} tz={tz}>
{date}
</ReactMoment> |
3c01fce00cf8dc7ee2275cd4ae5c9b0cb401673c | src/app/patient-dashboard/patient-dashboard.component.spec.ts | src/app/patient-dashboard/patient-dashboard.component.spec.ts | /* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { PatientDashboardComponent } from './patient-dashboard.component';
describe('Component: PatientDashboard', () => {
it('should create an instance', () => {
let component = new PatientDashboardComponent();
expect(component).toBeTruthy();
});
});
| /* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { Observable } from 'rxjs/Rx';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { DynamicRoutesService } from '../shared/services/dynamic-routes.service';
import { PatientDashboardComponent } from './patient-dashboard.component';
class MockRouter {
navigate = jasmine.createSpy('navigate');
}
class MockActivatedRoute { 'params': Observable.from([{ 'id': 1 }]) }
describe('Component: PatientDashboard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: Router, useClass: MockRouter }, { provide: ActivatedRoute, useClass: MockActivatedRoute }, DynamicRoutesService
]
});
});
it('should create an instance', () => {
let router: Router = TestBed.get(Router);
let route: ActivatedRoute = TestBed.get(ActivatedRoute);
let dynamicRoutesService: DynamicRoutesService = TestBed.get(DynamicRoutesService);
let component = new PatientDashboardComponent(router, route, dynamicRoutesService);
expect(component).toBeTruthy();
});
});
| Fix patient dash board test | Fix patient dash board test
| TypeScript | mit | AMPATH/ng2-amrs,AMPATH/ng2-amrs,AMPATH/ng2-amrs,AMPATH/ng2-amrs | ---
+++
@@ -1,11 +1,30 @@
/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
+import { Observable } from 'rxjs/Rx';
+import { Router, ActivatedRoute, Params } from '@angular/router';
+
+import { DynamicRoutesService } from '../shared/services/dynamic-routes.service';
import { PatientDashboardComponent } from './patient-dashboard.component';
+class MockRouter {
+ navigate = jasmine.createSpy('navigate');
+}
+class MockActivatedRoute { 'params': Observable.from([{ 'id': 1 }]) }
describe('Component: PatientDashboard', () => {
+
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ providers: [
+ { provide: Router, useClass: MockRouter }, { provide: ActivatedRoute, useClass: MockActivatedRoute }, DynamicRoutesService
+ ]
+ });
+ });
it('should create an instance', () => {
- let component = new PatientDashboardComponent();
+ let router: Router = TestBed.get(Router);
+ let route: ActivatedRoute = TestBed.get(ActivatedRoute);
+ let dynamicRoutesService: DynamicRoutesService = TestBed.get(DynamicRoutesService);
+ let component = new PatientDashboardComponent(router, route, dynamicRoutesService);
expect(component).toBeTruthy();
});
}); |
b4186bb75b9a1663e69ef8efb9e5bd14ddff47c4 | src/Services/error-message.service.spec.ts | src/Services/error-message.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { ErrorMessageService } from './error-message.service';
describe('ErrorMessageService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ErrorMessageService]
});
});
it('should ...', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service).toBeTruthy();
}));
});
| import {inject, TestBed} from "@angular/core/testing";
import {ErrorMessageService} from "./error-message.service";
import {CUSTOM_ERROR_MESSAGES} from "../Tokens/tokens";
import {errorMessageService} from "../ng-bootstrap-form-validation.module";
describe('ErrorMessageService', () => {
const customRequiredErrorMessage = {
error: 'required',
format: function (label, error) {
return `${label} IS DEFINITELY REQUIRED!!!`;
}
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: ErrorMessageService,
useFactory: errorMessageService,
deps: [CUSTOM_ERROR_MESSAGES]
},
{
provide: CUSTOM_ERROR_MESSAGES,
useValue: [
customRequiredErrorMessage
]
}
]
});
});
it('should inject ErrorMessageService', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service).toBeTruthy();
}));
describe('errorMessages()', () => {
it('should return custom errors before default errors', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service.errorMessages[0]).toEqual(customRequiredErrorMessage);
}));
});
});
| Add error message service test | Add error message service test
| TypeScript | mit | third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation,third774/ng-bootstrap-form-validation | ---
+++
@@ -1,15 +1,42 @@
-import { TestBed, inject } from '@angular/core/testing';
+import {inject, TestBed} from "@angular/core/testing";
-import { ErrorMessageService } from './error-message.service';
+import {ErrorMessageService} from "./error-message.service";
+import {CUSTOM_ERROR_MESSAGES} from "../Tokens/tokens";
+import {errorMessageService} from "../ng-bootstrap-form-validation.module";
describe('ErrorMessageService', () => {
- beforeEach(() => {
- TestBed.configureTestingModule({
- providers: [ErrorMessageService]
+ const customRequiredErrorMessage = {
+ error: 'required',
+ format: function (label, error) {
+ return `${label} IS DEFINITELY REQUIRED!!!`;
+ }
+ };
+
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ providers: [
+ {
+ provide: ErrorMessageService,
+ useFactory: errorMessageService,
+ deps: [CUSTOM_ERROR_MESSAGES]
+ },
+ {
+ provide: CUSTOM_ERROR_MESSAGES,
+ useValue: [
+ customRequiredErrorMessage
+ ]
+ }
+ ]
+ });
});
- });
- it('should ...', inject([ErrorMessageService], (service: ErrorMessageService) => {
- expect(service).toBeTruthy();
- }));
+ it('should inject ErrorMessageService', inject([ErrorMessageService], (service: ErrorMessageService) => {
+ expect(service).toBeTruthy();
+ }));
+
+ describe('errorMessages()', () => {
+ it('should return custom errors before default errors', inject([ErrorMessageService], (service: ErrorMessageService) => {
+ expect(service.errorMessages[0]).toEqual(customRequiredErrorMessage);
+ }));
+ });
}); |
26de55028c0c54548e0546f62c02839efdcb2da4 | src/renderers/MuiTableRenderer.tsx | src/renderers/MuiTableRenderer.tsx | import * as React from 'react'
import {
Table,
TableHeaderColumn,
TableRow,
TableHeader,
TableRowColumn,
TableBody,
CircularProgress,
} from 'material-ui'
import {
TableColumnData,
DataTableState,
} from '../components'
export function renderTableHeader(
data: TableColumnData[]
) {
return (
<TableRow>
{data.map((headerData, index) => {
const { cellData } = headerData
return (
<TableHeaderColumn key={`col-${index}`}>
{cellData}
</TableHeaderColumn>
)
})}
</TableRow>
)
}
export function renderTableRow(
data: TableColumnData[],
rowIndex: number
) {
return (
<TableRow key={rowIndex}>
{data.map((columnData, index) => {
const { cellData } = columnData
return (
<TableRowColumn key={`col-${index}`}>
{cellData}
</TableRowColumn>
)
})}
</TableRow>
)
}
export function renderTable(
tableHeader: JSX.Element,
tableRows: JSX.Element[],
rendererProps: any,
tableStates: DataTableState
) {
return (
<Table selectable={false}>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}
enableSelectAll={false}
>
{tableHeader}
</TableHeader>
<TableBody displayRowCheckbox={false}>
{tableRows}
</TableBody>
</Table>
)
}
| import * as React from 'react'
import {
Table,
TableHeaderColumn,
TableRow,
TableHeader,
TableRowColumn,
TableBody,
} from 'material-ui'
import {
TableColumnData,
DataTableState,
} from '../components'
export module MuiTable {
export const renderTableHeader = (
data: TableColumnData[]
) => (
<TableRow>
{data.map((headerData, index) => {
const { cellData } = headerData
return (
<TableHeaderColumn key={`col-${index}`}>
{cellData}
</TableHeaderColumn>
)
})}
</TableRow>
)
export const renderTableRow = (
data: TableColumnData[],
rowIndex: number
) => (
<TableRow key={rowIndex}>
{data.map((columnData, index) => {
const { cellData } = columnData
return (
<TableRowColumn key={`col-${index}`}>
{cellData}
</TableRowColumn>
)
})}
</TableRow>
)
export const renderTable = (
tableHeader: JSX.Element,
tableRows: JSX.Element[],
rendererProps: any,
tableStates: DataTableState
) => (
<Table selectable={false}>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}
enableSelectAll={false}
>
{tableHeader}
</TableHeader>
<TableBody displayRowCheckbox={false}>
{tableRows}
</TableBody>
</Table>
)
export const sortableHeader = (
cellData: any, onSortChange: Function
) => (
<div onClick={onSortChange}>{cellData}</div>
)
}
| Update material-ui style table renderer | Update material-ui style table renderer
| TypeScript | mit | zhenwenc/rc-box,zhenwenc/rc-box,zhenwenc/rc-box | ---
+++
@@ -7,17 +7,18 @@
TableHeader,
TableRowColumn,
TableBody,
- CircularProgress,
} from 'material-ui'
+
import {
TableColumnData,
DataTableState,
} from '../components'
-export function renderTableHeader(
- data: TableColumnData[]
-) {
- return (
+export module MuiTable {
+
+ export const renderTableHeader = (
+ data: TableColumnData[]
+ ) => (
<TableRow>
{data.map((headerData, index) => {
const { cellData } = headerData
@@ -29,13 +30,11 @@
})}
</TableRow>
)
-}
-export function renderTableRow(
- data: TableColumnData[],
- rowIndex: number
-) {
- return (
+ export const renderTableRow = (
+ data: TableColumnData[],
+ rowIndex: number
+ ) => (
<TableRow key={rowIndex}>
{data.map((columnData, index) => {
const { cellData } = columnData
@@ -47,15 +46,13 @@
})}
</TableRow>
)
-}
-export function renderTable(
- tableHeader: JSX.Element,
- tableRows: JSX.Element[],
- rendererProps: any,
- tableStates: DataTableState
-) {
- return (
+ export const renderTable = (
+ tableHeader: JSX.Element,
+ tableRows: JSX.Element[],
+ rendererProps: any,
+ tableStates: DataTableState
+ ) => (
<Table selectable={false}>
<TableHeader
adjustForCheckbox={false}
@@ -69,4 +66,11 @@
</TableBody>
</Table>
)
+
+ export const sortableHeader = (
+ cellData: any, onSortChange: Function
+ ) => (
+ <div onClick={onSortChange}>{cellData}</div>
+ )
+
} |
8badf641563e20beb56eba24794caa70c457b24d | app/components/resources/view/state/navigation-path-segment.ts | app/components/resources/view/state/navigation-path-segment.ts | import {Document} from 'idai-components-2/core';
import {IdaiFieldDocument} from 'idai-components-2/field';
import {ViewContext} from './view-context';
import {to} from 'tsfun';
/**
* @author Thomas Kleinke
* @author Daniel de Oliveira
*/
export interface NavigationPathSegment extends ViewContext {
readonly document: IdaiFieldDocument;
}
export module NavigationPathSegment {
export async function isValid(
mainTypeDocumentResourceId: string|undefined,
segment: NavigationPathSegment,
segments: Array<NavigationPathSegment>,
exists: (_: string) => Promise<boolean>): Promise<boolean> {
return await exists(segment.document.resource.id)
&& hasValidRelation(mainTypeDocumentResourceId, segment, segments);
}
function hasValidRelation(mainTypeDocumentResourceId: string|undefined, segment: NavigationPathSegment,
segments: Array<NavigationPathSegment>): boolean {
const index = segments.indexOf(segment);
return (index === 0)
? mainTypeDocumentResourceId !== undefined && Document.hasRelationTarget(segment.document,
'isRecordedIn', mainTypeDocumentResourceId)
: Document.hasRelationTarget(segment.document,
'liesWithin', segments[index - 1].document.resource.id);
}
}
export const toResourceId = to('document.resource.id');
// TODO use comparator from tsfun
export const differentFrom = (a: NavigationPathSegment) => (b: NavigationPathSegment) =>
a.document.resource.id !== b.document.resource.id; | import {Document} from 'idai-components-2/core';
import {IdaiFieldDocument} from 'idai-components-2/field';
import {ViewContext} from './view-context';
import {to, differentFromBy, on} from 'tsfun';
/**
* @author Thomas Kleinke
* @author Daniel de Oliveira
*/
export interface NavigationPathSegment extends ViewContext {
readonly document: IdaiFieldDocument;
}
export module NavigationPathSegment {
export async function isValid(
mainTypeDocumentResourceId: string|undefined,
segment: NavigationPathSegment,
segments: Array<NavigationPathSegment>,
exists: (_: string) => Promise<boolean>): Promise<boolean> {
return await exists(segment.document.resource.id)
&& hasValidRelation(mainTypeDocumentResourceId, segment, segments);
}
function hasValidRelation(mainTypeDocumentResourceId: string|undefined, segment: NavigationPathSegment,
segments: Array<NavigationPathSegment>): boolean {
const index = segments.indexOf(segment);
return (index === 0)
? mainTypeDocumentResourceId !== undefined && Document.hasRelationTarget(segment.document,
'isRecordedIn', mainTypeDocumentResourceId)
: Document.hasRelationTarget(segment.document,
'liesWithin', segments[index - 1].document.resource.id);
}
}
export const toResourceId = to('document.resource.id');
export const differentFrom = differentFromBy(on('document.resource.id')); | Make use of differentFromBy and on | Make use of differentFromBy and on
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,7 +1,7 @@
import {Document} from 'idai-components-2/core';
import {IdaiFieldDocument} from 'idai-components-2/field';
import {ViewContext} from './view-context';
-import {to} from 'tsfun';
+import {to, differentFromBy, on} from 'tsfun';
/**
@@ -44,6 +44,4 @@
export const toResourceId = to('document.resource.id');
-// TODO use comparator from tsfun
-export const differentFrom = (a: NavigationPathSegment) => (b: NavigationPathSegment) =>
- a.document.resource.id !== b.document.resource.id;
+export const differentFrom = differentFromBy(on('document.resource.id')); |
ceae9deddc847d49983f57f01748d25f40bf85cc | src/Bibliotheca.Client.Web/src/app/components/footer/footer.component.ts | src/Bibliotheca.Client.Web/src/app/components/footer/footer.component.ts | import { Component, Input } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AppConfigService } from '../../services/app-config.service'
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html'
})
export class FooterComponent {
protected siteUrl: string = null;
protected siteName: string = null;
protected version: string = null;
protected build: string = null;
constructor(private appConfig: AppConfigService) {
this.siteUrl = appConfig.footerUrl;
this.siteName = appConfig.footerName;
this.version = appConfig.version;
this.build = appConfig.build;
}
} | import { Component, Input } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AppConfigService } from '../../services/app-config.service'
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html'
})
export class FooterComponent {
protected siteUrl: string = null;
protected siteName: string = null;
protected version: string = null;
protected build: string = null;
constructor(private appConfig: AppConfigService) {
this.siteUrl = appConfig.footerUrl;
this.siteName = appConfig.footerName;
this.version = appConfig.version;
this.build = appConfig.build.substr(0, 7);
}
} | Build number should have max 7 chars. | Build number should have max 7 chars.
| TypeScript | mit | BibliothecaTeam/Bibliotheca.Client,BibliothecaTeam/Bibliotheca.Client,BibliothecaTeam/Bibliotheca.Client | ---
+++
@@ -17,6 +17,6 @@
this.siteUrl = appConfig.footerUrl;
this.siteName = appConfig.footerName;
this.version = appConfig.version;
- this.build = appConfig.build;
+ this.build = appConfig.build.substr(0, 7);
}
} |
72f331790b3b4e3e4cff4addae8acd54281bba35 | packages/components/components/sidebar/SidebarPrimaryButton.tsx | packages/components/components/sidebar/SidebarPrimaryButton.tsx | import { forwardRef, Ref } from 'react';
import Button, { ButtonProps } from '../button/Button';
import { classnames } from '../../helpers';
const SidebarPrimaryButton = ({ children, className = '', ...rest }: ButtonProps, ref: Ref<HTMLButtonElement>) => {
return (
<Button
color="norm"
size="large"
className={classnames(['text-bold mt0-25 w100', className])}
ref={ref}
{...rest}
>
{children}
</Button>
);
};
export default forwardRef<HTMLButtonElement, ButtonProps>(SidebarPrimaryButton);
| import { forwardRef, Ref } from 'react';
import Button, { ButtonProps } from '../button/Button';
import { classnames } from '../../helpers';
const SidebarPrimaryButton = ({ children, className = '', ...rest }: ButtonProps, ref: Ref<HTMLButtonElement>) => {
return (
<Button color="norm" size="large" className={classnames(['mt0-25 w100', className])} ref={ref} {...rest}>
{children}
</Button>
);
};
export default forwardRef<HTMLButtonElement, ButtonProps>(SidebarPrimaryButton);
| Remove bold on sidebar primary button | Remove bold on sidebar primary button
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -4,13 +4,7 @@
const SidebarPrimaryButton = ({ children, className = '', ...rest }: ButtonProps, ref: Ref<HTMLButtonElement>) => {
return (
- <Button
- color="norm"
- size="large"
- className={classnames(['text-bold mt0-25 w100', className])}
- ref={ref}
- {...rest}
- >
+ <Button color="norm" size="large" className={classnames(['mt0-25 w100', className])} ref={ref} {...rest}>
{children}
</Button>
); |
913534010dde9f54426286668fda36d3dfa42958 | packages/linter/src/rules/BoilerplateIsRemoved.ts | packages/linter/src/rules/BoilerplateIsRemoved.ts | import { Context } from "../index";
import { Rule } from "../rule";
import { isTransformedAmp } from "../helper";
/**
* Check if the AMP Optimizer removed the AMP Boilerplate.
*/
export class BoilerplateIsRemoved extends Rule {
run({ $ }: Context) {
if (!isTransformedAmp($)) {
// this check is only relevant for transformed amp pages
return this.pass();
}
const boilerplate = $("html[i-amphtml-no-boilerplate]");
if (boilerplate.length > 0) {
// The desired result: boilerplate is removed
return this.pass();
}
const fixedBlockingElements = $(
"script[custom-element='amp-story'],script[custom-element='amp-audio']"
);
if (fixedBlockingElements.length > 0) {
// with these elements the boilerplate cannot be removed and there are no options
return this.pass();
}
const optionalBlockingElements = $(
"script[custom-element='amp-experiment'],script[custom-element='amp-dynamic-css-styles']"
);
if (optionalBlockingElements.length > 0) {
return this.info(
"Avoid amp-experiment and amp-dynamic-css-styles if possible to allow AMP Boilerplate removal"
);
}
return this.warn(
"AMP Boilerplate not removed. Check for AMP Optimizer updates"
);
}
meta() {
return {
url:
"https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/",
title: "AMP Boilerplate is removed",
info: "",
};
}
}
| import { Context } from "../index";
import { Rule } from "../rule";
import { isTransformedAmp } from "../helper";
/**
* Check if the AMP Optimizer removed the AMP Boilerplate.
*/
export class BoilerplateIsRemoved extends Rule {
run({ $ }: Context) {
if (!isTransformedAmp($)) {
// this check is only relevant for transformed amp pages
return this.pass();
}
const boilerplate = $("html[i-amphtml-no-boilerplate]");
if (boilerplate.length > 0) {
// The desired result: boilerplate is removed
return this.pass();
}
const fixedBlockingElements = $(
"script[custom-element='amp-story'],script[custom-element='amp-audio']"
);
if (fixedBlockingElements.length > 0) {
// with these elements the boilerplate cannot be removed and there are no options
return this.pass();
}
const optionalBlockingElements = $(
"script[custom-element='amp-experiment'],script[custom-element='amp-dynamic-css-styles']"
);
if (optionalBlockingElements.length > 0) {
return this.info(
"Avoid amp-experiment and amp-dynamic-css-styles if possible to allow AMP Boilerplate removal"
);
}
return this.warn(
"AMP Boilerplate not removed. Please upgrade to the latest AMP Optimizer version"
);
}
meta() {
return {
url:
"https://amp.dev/documentation/guides-and-tutorials/optimize-and-measure/amp-optimizer-guide/",
title: "AMP Boilerplate is removed",
info: "",
};
}
}
| Change warning text for boilerplate removal check | Change warning text for boilerplate removal check
| TypeScript | apache-2.0 | ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox | ---
+++
@@ -32,7 +32,7 @@
);
}
return this.warn(
- "AMP Boilerplate not removed. Check for AMP Optimizer updates"
+ "AMP Boilerplate not removed. Please upgrade to the latest AMP Optimizer version"
);
}
meta() { |
8164db0b5562ca3608efba0c2a8135dde7d07631 | src/client/app/fassung/fassung-routing.module.ts | src/client/app/fassung/fassung-routing.module.ts | /**
* Created by Reto Baumgartner (rfbaumgartner) on 05.07.17.
*/
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FassungComponent } from './fassung.component';
@NgModule({
imports: [
RouterModule.forChild([
{ path: 'drucke/:konvolut/:fassung', component: FassungComponent },
{ path: 'manuskripte/:konvolut/:fassung', component: FassungComponent },
{ path: 'notizbuecher/notizbuch-divers/:konvolut/:fassung', component: FassungComponent },
{ path: 'notizbuecher/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/typoskripte-sammlungen/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/:konvolut/:fassung', component: FassungComponent },
{ path: 'material/:konvolut/:fassung', component: FassungComponent }
])
],
exports: [ RouterModule ]
})
export class FassungRoutingModule {
}
| /**
* Created by Reto Baumgartner (rfbaumgartner) on 05.07.17.
*/
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FassungComponent } from './fassung.component';
@NgModule({
imports: [
RouterModule.forChild([
{ path: 'drucke/:konvolut/:fassung', component: FassungComponent },
{ path: 'manuskripte/:konvolut/:fassung', component: FassungComponent },
{ path: 'notizbuecher/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/typoskripte-sammlungen/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/:konvolut/:fassung', component: FassungComponent },
{ path: 'material/:konvolut/:fassung', component: FassungComponent }
])
],
exports: [ RouterModule ]
})
export class FassungRoutingModule {
}
| Remove route to special collection `notizbuecher-divers` | Remove route to special collection `notizbuecher-divers`
The collection `notizbuecher-divers` serves only as a ordering element in the navigation
| TypeScript | mit | nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website | ---
+++
@@ -11,7 +11,6 @@
RouterModule.forChild([
{ path: 'drucke/:konvolut/:fassung', component: FassungComponent },
{ path: 'manuskripte/:konvolut/:fassung', component: FassungComponent },
- { path: 'notizbuecher/notizbuch-divers/:konvolut/:fassung', component: FassungComponent },
{ path: 'notizbuecher/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/typoskripte-sammlungen/:konvolut/:fassung', component: FassungComponent },
{ path: 'typoskripte/:konvolut/:fassung', component: FassungComponent }, |
242edc1aa2ac62016b3dd03fee53a8983b362306 | src/Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.ts | src/Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.ts | module BABYLON {
export class ArcRotateCameraMouseWheelInput implements ICameraInput<ArcRotateCamera> {
camera: ArcRotateCamera;
private _wheel: (p: PointerInfo, s: EventState) => void;
private _observer: Observer<PointerInfo>;
@serialize()
public wheelPrecision = 3.0;
public attachControl(element: HTMLElement, noPreventDefault?: boolean) {
this._wheel = (p, s) => {
var event = <MouseWheelEvent>p.event;
var delta = 0;
if (event.wheelDelta) {
delta = event.wheelDelta / (this.wheelPrecision * 40);
} else if (event.detail) {
delta = -event.detail / this.wheelPrecision;
}
if (delta)
this.camera.inertialRadiusOffset += delta;
if (event.preventDefault) {
if (!noPreventDefault) {
event.preventDefault();
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._wheel);
}
public detachControl(element: HTMLElement) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
this._wheel = null;
}
}
getTypeName(): string {
return "ArcRotateCameraMouseWheelInput";
}
getSimpleName() {
return "mousewheel";
}
}
CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
}
| module BABYLON {
export class ArcRotateCameraMouseWheelInput implements ICameraInput<ArcRotateCamera> {
camera: ArcRotateCamera;
private _wheel: (p: PointerInfo, s: EventState) => void;
private _observer: Observer<PointerInfo>;
@serialize()
public wheelPrecision = 3.0;
public attachControl(element: HTMLElement, noPreventDefault?: boolean) {
this._wheel = (p, s) => {
//sanity check - this should be a PointerWheel event.
if (p.type !== PointerEventType.PointerWheel) return;
var event = <MouseWheelEvent>p.event;
var delta = 0;
if (event.wheelDelta) {
delta = event.wheelDelta / (this.wheelPrecision * 40);
} else if (event.detail) {
delta = -event.detail / this.wheelPrecision;
}
if (delta)
this.camera.inertialRadiusOffset += delta;
if (event.preventDefault) {
if (!noPreventDefault) {
event.preventDefault();
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._wheel);
}
public detachControl(element: HTMLElement) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
this._wheel = null;
}
}
getTypeName(): string {
return "ArcRotateCameraMouseWheelInput";
}
getSimpleName() {
return "mousewheel";
}
}
CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
}
| Make sure the wheel only works when wheel is triggered. | Make sure the wheel only works when wheel is triggered.
| TypeScript | apache-2.0 | abow/Babylon.js,Temechon/Babylon.js,BabylonJS/Babylon.js,jbousquie/Babylon.js,jbousquie/Babylon.js,Hersir88/Babylon.js,NicolasBuecher/Babylon.js,BabylonJS/Babylon.js,Temechon/Babylon.js,Hersir88/Babylon.js,abow/Babylon.js,BabylonJS/Babylon.js,NicolasBuecher/Babylon.js,sebavan/Babylon.js,RaananW/Babylon.js,RaananW/Babylon.js,Kesshi/Babylon.js,NicolasBuecher/Babylon.js,Temechon/Babylon.js,jbousquie/Babylon.js,Kesshi/Babylon.js,abow/Babylon.js,RaananW/Babylon.js,Kesshi/Babylon.js,sebavan/Babylon.js,sebavan/Babylon.js,Hersir88/Babylon.js | ---
+++
@@ -10,6 +10,8 @@
public attachControl(element: HTMLElement, noPreventDefault?: boolean) {
this._wheel = (p, s) => {
+ //sanity check - this should be a PointerWheel event.
+ if (p.type !== PointerEventType.PointerWheel) return;
var event = <MouseWheelEvent>p.event;
var delta = 0;
if (event.wheelDelta) { |
baac3ed2df638ff48f5eb0a45a72bdf5bbd506f3 | src/Styleguide/Components/__stories__/LightboxSlider.story.tsx | src/Styleguide/Components/__stories__/LightboxSlider.story.tsx | import React from "react"
import { storiesOf } from "storybook/storiesOf"
import { Slider } from "Styleguide/Components/LightboxSlider"
import { Section } from "Styleguide/Utils/Section"
storiesOf("Styleguide/Components", module).add("LightboxSlider", () => {
return (
<React.Fragment>
<Section title="Lightbox Slider">
<Slider
min={0}
max={100}
step={1}
value={50}
onChange={event => console.log(event.target.value)}
onZoomInClicked={() => console.log("zoom in")}
onZoomOutClicked={() => console.log("zoom out")}
/>
</Section>
</React.Fragment>
)
})
| import React from "react"
import { storiesOf } from "storybook/storiesOf"
import { Slider } from "Styleguide/Components/LightboxSlider"
import { Section } from "Styleguide/Utils/Section"
storiesOf("Styleguide/Components", module).add("LightboxSlider", () => {
return (
<React.Fragment>
<Section title="Lightbox Slider">
<Slider min={0} max={100} step={1} value={50} />
</Section>
</React.Fragment>
)
})
| Remove console logs causing circle ci to fail | Remove console logs causing circle ci to fail
| TypeScript | mit | xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction | ---
+++
@@ -7,15 +7,7 @@
return (
<React.Fragment>
<Section title="Lightbox Slider">
- <Slider
- min={0}
- max={100}
- step={1}
- value={50}
- onChange={event => console.log(event.target.value)}
- onZoomInClicked={() => console.log("zoom in")}
- onZoomOutClicked={() => console.log("zoom out")}
- />
+ <Slider min={0} max={100} step={1} value={50} />
</Section>
</React.Fragment>
) |
73e6100b9bc913b27b1739c4fac42a8ffb788402 | resources/app/auth/services/auth.service.ts | resources/app/auth/services/auth.service.ts | export class AuthService {
static NAME = 'AuthService';
constructor(
private $http: ng.IHttpService,
private $window: ng.IWindowService
) {
'ngInject';
}
isLoggedIn() {
return this.$window.localStorage.getItem('token') !== null;
}
static factory() {
return ($http, $window) => new AuthService($http, $window);
}
} | export interface IAuthService {
isLoggedIn();
}
export class AuthService {
static NAME = 'AuthService';
constructor(
private $http: ng.IHttpService,
private $window: ng.IWindowService
) {
'ngInject';
}
isLoggedIn() {
return this.$window.localStorage.getItem('token') !== null;
}
static factory() {
return ($http, $window) => new AuthService($http, $window);
}
} | Add AuthService interface to define implementation | Add AuthService interface to define implementation
| TypeScript | mit | ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io | ---
+++
@@ -1,3 +1,7 @@
+export interface IAuthService {
+ isLoggedIn();
+}
+
export class AuthService {
static NAME = 'AuthService';
|
2ccd613433528b21025043f44ecad58ea8bf897b | src/dashboard-refactor/styleConstants.tsx | src/dashboard-refactor/styleConstants.tsx | import colors from './colors'
export const fonts = {
primary: {
name: 'Poppins',
colors: {
primary: colors.fonts.primary,
secondary: colors.fonts.secondary,
},
weight: {
normal: 'normal',
bold: 700,
},
},
}
const styleConstants = {
fonts,
components: {
dropDown: {
boxShadow: '0px 0px 4.20px rgba(0, 0, 0, 0.14)',
borderRadius: '2.1px',
},
},
}
export default styleConstants
| import colors from './colors'
export const fonts = {
primary: {
name: 'Poppins',
colors: {
primary: colors.fonts.primary,
secondary: colors.fonts.secondary,
},
weight: {
normal: 'normal',
bold: 700,
},
},
}
const styleConstants = {
fonts,
components: {
dropDown: {
boxShadow: '0px 0px 4.20px rgba(0, 0, 0, 0.14)',
borderRadius: '2.1px',
},
sidebar: {
widthPx: 173,
},
},
}
export default styleConstants
| Add sidebar width to style constants | Add sidebar width to style constants
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -21,6 +21,9 @@
boxShadow: '0px 0px 4.20px rgba(0, 0, 0, 0.14)',
borderRadius: '2.1px',
},
+ sidebar: {
+ widthPx: 173,
+ },
},
}
|
4afee35d8713455949213866e15194c4b960b60a | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
const project = getProject(tree, options.project);
console.log(findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
}));
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/ng-steroids | ---
+++
@@ -1,12 +1,23 @@
import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
+import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
+import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
+
+ const project = getProject(tree, options.project);
+
+ console.log(findModuleFromOptions(tree, {
+ ...options,
+ path: options.path || buildDefaultPath(project)
+ }));
+
return tree;
+
};
export function scam(options: ScamOptions): Rule { |
304e3ee9c0e270364291b36eef859541f3291b4b | typescript-marionette-v2/src/TodosView.ts | typescript-marionette-v2/src/TodosView.ts | // TODO: Why does the compiler not complain when Marionette is missing?
import * as Marionette from "backbone.marionette"
import TodoCollection from "./TodoCollection"
import TodoModel from "./TodoModel"
import TodoView from "./TodoView"
// Add childViewContainer?:string; to CollectionViewOptions in marionette/index.d.ts.
interface TodosViewOptions extends Marionette.CollectionViewOptions<TodoModel> {
collection: TodoCollection
}
export default class TodosView extends Marionette.CompositeView<TodoModel, TodoView> {
constructor(options: TodosViewOptions) {
super({
childViewContainer: ".js-child-view-container"
})
this.collection = options.collection
}
childView = TodoView
collection: TodoCollection
template = require("./TodosView.ejs")
}
| // TODO: Why does the compiler not complain when Marionette is missing?
import * as Marionette from "backbone.marionette"
import TodoCollection from "./TodoCollection"
import TodoModel from "./TodoModel"
import TodoView from "./TodoView"
// Add this to marionette/index.d.ts.
// interface CompositeViewOptions<TModel extends Backbone.Model> extends CollectionViewOptions<TModel> {
// childView?: string,
// collection?: Backbone.Collection<TModel>,
// template?: any
// }
interface TodosViewOptions extends Marionette.CompositeViewOptions<TodoModel> {
collection: TodoCollection
}
export default class TodosView extends Marionette.CompositeView<TodoModel, TodoView> {
constructor(options: TodosViewOptions) {
super(TodosView.setDefaultOptions(options))
}
childView = TodoView
collection: TodoCollection
template = require("./TodosView.ejs")
private static setDefaultOptions(options: TodosViewOptions): TodosViewOptions {
options.childViewContainer = ".js-child-view-container"
return options
}
}
| Introduce setDefaultOptions to extend the options | Introduce setDefaultOptions to extend the options
| TypeScript | unlicense | janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations | ---
+++
@@ -4,19 +4,20 @@
import TodoModel from "./TodoModel"
import TodoView from "./TodoView"
-// Add childViewContainer?:string; to CollectionViewOptions in marionette/index.d.ts.
+// Add this to marionette/index.d.ts.
+// interface CompositeViewOptions<TModel extends Backbone.Model> extends CollectionViewOptions<TModel> {
+// childView?: string,
+// collection?: Backbone.Collection<TModel>,
+// template?: any
+// }
-interface TodosViewOptions extends Marionette.CollectionViewOptions<TodoModel> {
+interface TodosViewOptions extends Marionette.CompositeViewOptions<TodoModel> {
collection: TodoCollection
}
export default class TodosView extends Marionette.CompositeView<TodoModel, TodoView> {
constructor(options: TodosViewOptions) {
- super({
- childViewContainer: ".js-child-view-container"
- })
-
- this.collection = options.collection
+ super(TodosView.setDefaultOptions(options))
}
childView = TodoView
@@ -24,4 +25,9 @@
collection: TodoCollection
template = require("./TodosView.ejs")
+
+ private static setDefaultOptions(options: TodosViewOptions): TodosViewOptions {
+ options.childViewContainer = ".js-child-view-container"
+ return options
+ }
} |
6bfdcd6405c3e12dc8c74781fd7c6ebce3cb3d09 | frontend/src/pages/home/index.tsx | frontend/src/pages/home/index.tsx | import * as React from 'react';
import { Navbar } from 'components/navbar';
export class HomePage extends React.Component {
render() {
return (
<div className="App">
<Navbar />
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
);
}
}
| import * as React from 'react';
import { Navbar } from 'components/navbar';
import { Button } from 'components/button';
import { Grid, Column } from 'components/grid';
import { Card } from 'components/card';
export const HomePage = () => (
<div>
<Navbar />
<div className="hero">
<h1>PyCon 10</h1>
<h2>Florence, XX XXXX 2019</h2>
<p>Location</p>
<Button>Get your Ticket</Button>
<Button>Propose a talk</Button>
</div>
<div className="pitch">
<div>
<h2>Perché la pycon</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
reprehenderit labore, voluptatem officia velit rerum amet excepturi
esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
laudantium, ipsam veniam?
</p>
</div>
<div>
<h2>Di cosa parleremo</h2>
<h3>Data</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
reprehenderit labore, voluptatem officia velit rerum amet excepturi
esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
laudantium, ipsam veniam?
</p>
<h3>Web</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
reprehenderit labore, voluptatem officia velit rerum amet excepturi
esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
laudantium, ipsam veniam?
</p>
</div>
</div>
<div className="keynote-speakers">
<Grid>
<Column width={1 / 3}>
<Card>Example</Card>
<Card>Example</Card>
</Column>
<Column width={1 / 3}>
<Card>Example</Card>
<Card>Example</Card>
</Column>
<Column width={1 / 3}>
<Card>Example</Card>
<Card>Example</Card>
</Column>
<Button variant="secondary">See the schedule</Button>
</Grid>
</div>
</div>
);
| Add some dummy content to the home page | Add some dummy content to the home page
| TypeScript | mit | patrick91/pycon,patrick91/pycon | ---
+++
@@ -1,15 +1,72 @@
import * as React from 'react';
import { Navbar } from 'components/navbar';
+import { Button } from 'components/button';
+import { Grid, Column } from 'components/grid';
+import { Card } from 'components/card';
-export class HomePage extends React.Component {
- render() {
- return (
- <div className="App">
- <Navbar />
- <p className="App-intro">
- To get started, edit <code>src/App.tsx</code> and save to reload.
+export const HomePage = () => (
+ <div>
+ <Navbar />
+
+ <div className="hero">
+ <h1>PyCon 10</h1>
+ <h2>Florence, XX XXXX 2019</h2>
+ <p>Location</p>
+
+ <Button>Get your Ticket</Button>
+ <Button>Propose a talk</Button>
+ </div>
+
+ <div className="pitch">
+ <div>
+ <h2>Perché la pycon</h2>
+
+ <p>
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
+ reprehenderit labore, voluptatem officia velit rerum amet excepturi
+ esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
+ laudantium, ipsam veniam?
</p>
</div>
- );
- }
-}
+
+ <div>
+ <h2>Di cosa parleremo</h2>
+
+ <h3>Data</h3>
+ <p>
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
+ reprehenderit labore, voluptatem officia velit rerum amet excepturi
+ esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
+ laudantium, ipsam veniam?
+ </p>
+
+ <h3>Web</h3>
+ <p>
+ Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt,
+ reprehenderit labore, voluptatem officia velit rerum amet excepturi
+ esse, sit ea harum! Aspernatur, earum. Dolor sed commodi non
+ laudantium, ipsam veniam?
+ </p>
+ </div>
+ </div>
+
+ <div className="keynote-speakers">
+ <Grid>
+ <Column width={1 / 3}>
+ <Card>Example</Card>
+ <Card>Example</Card>
+ </Column>
+ <Column width={1 / 3}>
+ <Card>Example</Card>
+ <Card>Example</Card>
+ </Column>
+ <Column width={1 / 3}>
+ <Card>Example</Card>
+ <Card>Example</Card>
+ </Column>
+
+ <Button variant="secondary">See the schedule</Button>
+ </Grid>
+ </div>
+ </div>
+); |
bb3851cf1398b63232c7f230bad8563eb2e654b1 | app/src/ui/lib/theme-change-monitor.ts | app/src/ui/lib/theme-change-monitor.ts | import { remote } from 'electron'
import { ApplicationTheme } from './application-theme'
import { IDisposable, Disposable, Emitter } from 'event-kit'
import { supportsDarkMode, isDarkModeEnabled } from './dark-theme'
class ThemeChangeMonitor implements IDisposable {
private readonly emitter = new Emitter()
public constructor() {
this.subscribe()
}
public dispose() {
remote.nativeTheme.removeAllListeners()
}
private subscribe = () => {
if (!supportsDarkMode()) {
return
}
remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS)
}
private onThemeNotificationFromOS = (event: string, userInfo: any) => {
const darkModeEnabled = isDarkModeEnabled()
const theme = darkModeEnabled
? ApplicationTheme.Dark
: ApplicationTheme.Light
this.emitThemeChanged(theme)
}
public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable {
return this.emitter.on('theme-changed', fn)
}
private emitThemeChanged(theme: ApplicationTheme) {
this.emitter.emit('theme-changed', theme)
}
}
// this becomes our singleton that we can subscribe to from anywhere
export const themeChangeMonitor = new ThemeChangeMonitor()
// this ensures we cleanup any existing subscription on exit
remote.app.on('will-quit', () => {
themeChangeMonitor.dispose()
})
| import { remote } from 'electron'
import { ApplicationTheme } from './application-theme'
import { IDisposable, Disposable, Emitter } from 'event-kit'
import { supportsDarkMode, isDarkModeEnabled } from './dark-theme'
class ThemeChangeMonitor implements IDisposable {
private readonly emitter = new Emitter()
public constructor() {
this.subscribe()
}
public dispose() {
if (remote.nativeTheme) {
remote.nativeTheme.removeAllListeners()
}
}
private subscribe = () => {
if (!supportsDarkMode() || !remote.nativeTheme) {
return
}
remote.nativeTheme.addListener('updated', this.onThemeNotificationFromOS)
}
private onThemeNotificationFromOS = (event: string, userInfo: any) => {
const darkModeEnabled = isDarkModeEnabled()
const theme = darkModeEnabled
? ApplicationTheme.Dark
: ApplicationTheme.Light
this.emitThemeChanged(theme)
}
public onThemeChanged(fn: (theme: ApplicationTheme) => void): Disposable {
return this.emitter.on('theme-changed', fn)
}
private emitThemeChanged(theme: ApplicationTheme) {
this.emitter.emit('theme-changed', theme)
}
}
// this becomes our singleton that we can subscribe to from anywhere
export const themeChangeMonitor = new ThemeChangeMonitor()
// this ensures we cleanup any existing subscription on exit
remote.app.on('will-quit', () => {
themeChangeMonitor.dispose()
})
| Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+ | Fix nativeTheme errors in tests on Windows 10 1809+ and Server 2019+
| TypeScript | mit | artivilla/desktop,say25/desktop,desktop/desktop,artivilla/desktop,say25/desktop,say25/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop | ---
+++
@@ -11,11 +11,13 @@
}
public dispose() {
- remote.nativeTheme.removeAllListeners()
+ if (remote.nativeTheme) {
+ remote.nativeTheme.removeAllListeners()
+ }
}
private subscribe = () => {
- if (!supportsDarkMode()) {
+ if (!supportsDarkMode() || !remote.nativeTheme) {
return
}
|
d743c75a8f4378cfaf75d4de172bf9bb2f90f2a5 | ui/src/app/shared/service/logger.service.ts | ui/src/app/shared/service/logger.service.ts | import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
/**
* A service for global logs.
*
* @author Damien Vitrac
*/
@Injectable({
providedIn: 'root'
})
export class LoggerService {
constructor() {
}
static log(value: any, ...rest: any[]) {
if (!environment.production) {
console.log(value, ...rest);
}
}
static error(value: any, ...rest: any[]) {
console.error(value, ...rest);
}
static warn(value: any, ...rest: any[]) {
console.warn(value, ...rest);
}
log(value: any, ...rest: any[]) {
LoggerService.log(value, ...rest);
}
error(value: any, ...rest: any[]) {
LoggerService.error(value, ...rest);
}
warn(value: any, ...rest: any[]) {
LoggerService.warn(value, ...rest);
}
}
| import { Injectable, isDevMode } from '@angular/core';
/**
* A service for global logs.
*
* @author Damien Vitrac
*/
@Injectable({
providedIn: 'root'
})
export class LoggerService {
constructor() {
}
static log(value: any, ...rest: any[]) {
if (isDevMode()) {
console.log(value, ...rest);
}
}
static error(value: any, ...rest: any[]) {
console.error(value, ...rest);
}
static warn(value: any, ...rest: any[]) {
console.warn(value, ...rest);
}
log(value: any, ...rest: any[]) {
LoggerService.log(value, ...rest);
}
error(value: any, ...rest: any[]) {
LoggerService.error(value, ...rest);
}
warn(value: any, ...rest: any[]) {
LoggerService.warn(value, ...rest);
}
}
| Use isDevMode() instead of environment | Use isDevMode() instead of environment
| TypeScript | apache-2.0 | BoykoAlex/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,spring-cloud/spring-cloud-dataflow-ui,BoykoAlex/spring-cloud-dataflow-ui,cppwfs/spring-cloud-dataflow-ui | ---
+++
@@ -1,5 +1,4 @@
-import { Injectable } from '@angular/core';
-import { environment } from '../../../environments/environment';
+import { Injectable, isDevMode } from '@angular/core';
/**
* A service for global logs.
@@ -15,7 +14,7 @@
}
static log(value: any, ...rest: any[]) {
- if (!environment.production) {
+ if (isDevMode()) {
console.log(value, ...rest);
}
} |
3c662b1ed2a788a9b0ac7cc6cbd80e77d93df331 | client/app/logout/logout.component.spec.ts | client/app/logout/logout.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LogoutComponent } from './logout.component';
import { AuthService } from '../services/auth.service';
describe('LogoutComponent', () => {
let component: LogoutComponent;
let fixture: ComponentFixture<LogoutComponent>;
let authService: AuthService;
let authServiceStub: {
loggedIn: boolean,
logout: any
};
beforeEach(async(() => {
authServiceStub = {
loggedIn: true,
logout: (function() {
this.loggedIn = false;
})
};
TestBed.configureTestingModule({
declarations: [ LogoutComponent ],
providers: [ { provide: AuthService, useValue: authServiceStub } ],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LogoutComponent);
component = fixture.componentInstance;
authService = fixture.debugElement.injector.get(AuthService);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should logout the user', () => {
authService.loggedIn = true;
expect(authService.loggedIn).toBeTruthy();
authService.logout();
expect(authService.loggedIn).toBeFalsy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LogoutComponent } from './logout.component';
import { AuthService } from '../services/auth.service';
class AuthServiceMock {
loggedIn = true;
logout() {
this.loggedIn = false;
}
}
describe('Component: Logout', () => {
let component: LogoutComponent;
let fixture: ComponentFixture<LogoutComponent>;
let authService: AuthService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LogoutComponent ],
providers: [ { provide: AuthService, useClass: AuthServiceMock } ],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LogoutComponent);
component = fixture.componentInstance;
authService = fixture.debugElement.injector.get(AuthService);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should logout the user', () => {
authService.loggedIn = true;
expect(authService.loggedIn).toBeTruthy();
authService.logout();
expect(authService.loggedIn).toBeFalsy();
});
});
| Refactor logout component unit test | Refactor logout component unit test
| TypeScript | mit | DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular2-Express-Mongoose | ---
+++
@@ -3,25 +3,22 @@
import { LogoutComponent } from './logout.component';
import { AuthService } from '../services/auth.service';
-describe('LogoutComponent', () => {
+class AuthServiceMock {
+ loggedIn = true;
+ logout() {
+ this.loggedIn = false;
+ }
+}
+
+describe('Component: Logout', () => {
let component: LogoutComponent;
let fixture: ComponentFixture<LogoutComponent>;
let authService: AuthService;
- let authServiceStub: {
- loggedIn: boolean,
- logout: any
- };
beforeEach(async(() => {
- authServiceStub = {
- loggedIn: true,
- logout: (function() {
- this.loggedIn = false;
- })
- };
TestBed.configureTestingModule({
declarations: [ LogoutComponent ],
- providers: [ { provide: AuthService, useValue: authServiceStub } ],
+ providers: [ { provide: AuthService, useClass: AuthServiceMock } ],
})
.compileComponents();
})); |
80d68f31590ec3c70707373a38c5f2c8be0f5621 | src/Properties/IRunningBlockContent.ts | src/Properties/IRunningBlockContent.ts | // eslint-disable-next-line @typescript-eslint/no-unused-vars
import { RunningBlock } from "../System/Documents/RunningBlock";
/**
* Provides content for the different sections of a {@link RunningBlock `RunningBlock`}.
*/
export interface IRunningBlockContent
{
/**
* The content of the left part.
*/
Left: string;
/**
* The content of the center part.
*/
Center: string;
/**
* The content of the right part.
*/
Right: string;
}
| // eslint-disable-next-line @typescript-eslint/no-unused-vars
import { RunningBlock } from "../System/Documents/RunningBlock";
/**
* Provides content for the different sections of a {@link RunningBlock `RunningBlock`}.
*/
export interface IRunningBlockContent
{
/**
* The content of the left part.
*/
Left?: string;
/**
* The content of the center part.
*/
Center?: string;
/**
* The content of the right part.
*/
Right?: string;
}
| Make properties of the `IRunninngBLockContent` optional | Make properties of the `IRunninngBLockContent` optional
| TypeScript | mit | manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter | ---
+++
@@ -9,15 +9,15 @@
/**
* The content of the left part.
*/
- Left: string;
+ Left?: string;
/**
* The content of the center part.
*/
- Center: string;
+ Center?: string;
/**
* The content of the right part.
*/
- Right: string;
+ Right?: string;
} |
649b45f21f1aa0415e939867e87adf43d8786b50 | src/ITranslationEvents.ts | src/ITranslationEvents.ts | import { BehaviorSubject, Subject } from 'rxjs';
export type ResourceEvent = {lng, ns};
export type MissingKeyEvent = {lngs, namespace, key, res};
export interface ITranslationEvents {
initialized: BehaviorSubject<any>;
loaded: BehaviorSubject<boolean>;
failedLoading: Subject<any>;
missingKey: Subject<MissingKeyEvent>;
added: Subject<ResourceEvent>;
removed: Subject<ResourceEvent>;
languageChanged: BehaviorSubject<string>;
}
| import { BehaviorSubject, Subject } from 'rxjs';
export type ResourceEvent = { lng: any, ns: any };
export type MissingKeyEvent = { lngs: any, namespace: any, key: any, res: any };
export interface ITranslationEvents {
initialized: BehaviorSubject<any>;
loaded: BehaviorSubject<boolean>;
failedLoading: Subject<any>;
missingKey: Subject<MissingKeyEvent>;
added: Subject<ResourceEvent>;
removed: Subject<ResourceEvent>;
languageChanged: BehaviorSubject<string>;
}
| Update types of events to support noImplicitAny compiler option | Update types of events to support noImplicitAny compiler option
| TypeScript | mit | Romanchuk/angular-i18next,Romanchuk/angular-i18next,Romanchuk/angular-i18next,Romanchuk/angular-i18next | ---
+++
@@ -1,7 +1,7 @@
import { BehaviorSubject, Subject } from 'rxjs';
-export type ResourceEvent = {lng, ns};
-export type MissingKeyEvent = {lngs, namespace, key, res};
+export type ResourceEvent = { lng: any, ns: any };
+export type MissingKeyEvent = { lngs: any, namespace: any, key: any, res: any };
export interface ITranslationEvents {
initialized: BehaviorSubject<any>; |
c58ff87194f86351cbea32dd2da0234255233723 | client/app/heroes/services/hero.service.ts | client/app/heroes/services/hero.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../../environments/environment';
import { Hero, HeroUniverse, HeroRole } from '../models';
@Injectable()
export class HeroService {
private url = `${environment.backend.url}/heroes`;
constructor(private http: Http) {
}
searchHeroes(universe: HeroUniverse, role: HeroRole, terms: string): Observable<Hero[]> {
return this.http
.get(`${this.url}?universe=${universe}&role=${role}&terms=${encodeURI(terms || '')}`)
.map(response => response.json() as Hero[]);
}
getHero(name: string): Promise<Hero> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Hero[])
.then(heroes => heroes.filter(hero => hero.name === name).pop())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
// TODO: add real error handling
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../../environments/environment';
import { Hero, HeroUniverse, HeroRole } from '../models';
@Injectable()
export class HeroService {
private url = `${environment.backend.url}/heroes`;
constructor(private http: Http) {
}
searchHeroes(universe: HeroUniverse, role: HeroRole, terms: string): Observable<Hero[]> {
const query = this.querystring({ universe, role, terms });
return this.http
.get(`${this.url}?${query}`)
.map(response => response.json() as Hero[]);
}
getHero(name: string): Promise<Hero> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Hero[])
.then(heroes => heroes.filter(hero => hero.name === name).pop())
.catch(this.handleError);
}
private querystring(query) {
return Object
.keys(query)
.filter(key => query[key] || query[key] === 0 || query[key] === false)
.map(key => encodeURI(key) + '=' + encodeURI(query[key]))
.join('&');
}
private handleError(error: any): Promise<any> {
// TODO: add real error handling
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| Update how the query string is generated | Update how the query string is generated
| TypeScript | mit | fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training | ---
+++
@@ -15,8 +15,9 @@
}
searchHeroes(universe: HeroUniverse, role: HeroRole, terms: string): Observable<Hero[]> {
+ const query = this.querystring({ universe, role, terms });
return this.http
- .get(`${this.url}?universe=${universe}&role=${role}&terms=${encodeURI(terms || '')}`)
+ .get(`${this.url}?${query}`)
.map(response => response.json() as Hero[]);
}
@@ -28,6 +29,14 @@
.catch(this.handleError);
}
+ private querystring(query) {
+ return Object
+ .keys(query)
+ .filter(key => query[key] || query[key] === 0 || query[key] === false)
+ .map(key => encodeURI(key) + '=' + encodeURI(query[key]))
+ .join('&');
+ }
+
private handleError(error: any): Promise<any> {
// TODO: add real error handling
console.error('An error occurred', error); |
737f1613edec96a38c7d6e084c43cea779c2303a | types/react-pointable/index.d.ts | types/react-pointable/index.d.ts | // Type definitions for react-pointable 1.1
// Project: https://github.com/MilllerTime/react-pointable
// Definitions by: Stefan Fochler <https://github.com/istefo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as React from 'react';
export type TouchAction = 'auto' | 'none' | 'pan-x' | 'pan-y' | 'manipulation';
export interface PointableProps extends React.HTMLAttributes<HTMLElement> {
tagName?: keyof HTMLElementTagNameMap;
touchAction?: TouchAction;
elementRef?(el: HTMLElement): void;
onPointerMove?(evt: PointerEvent): void;
onPointerDown?(evt: PointerEvent): void;
onPointerUp?(evt: PointerEvent): void;
onPointerOver?(evt: PointerEvent): void;
onPointerOut?(evt: PointerEvent): void;
onPointerEnter?(evt: PointerEvent): void;
onPointerLeave?(evt: PointerEvent): void;
onPointerCancel?(evt: PointerEvent): void;
}
export default class Pointable extends React.Component<PointableProps> {
static defaultProps: {
tagName: 'div',
touchAction: 'auto'
};
}
| // Type definitions for react-pointable 1.1
// Project: https://github.com/MilllerTime/react-pointable
// Definitions by: Stefan Fochler <https://github.com/istefo>
// Dibyo Majumdar <https://github.com/mdibyo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as React from 'react';
export type TouchAction = 'auto' | 'none' | 'pan-x' | 'pan-y' | 'manipulation';
export interface PointableProps extends React.HTMLAttributes<Element>, React.SVGAttributes<Element> {
tagName?: keyof ElementTagNameMap;
touchAction?: TouchAction;
elementRef?(el: HTMLElement|SVGElement): void;
onPointerMove?(evt: PointerEvent): void;
onPointerDown?(evt: PointerEvent): void;
onPointerUp?(evt: PointerEvent): void;
onPointerOver?(evt: PointerEvent): void;
onPointerOut?(evt: PointerEvent): void;
onPointerEnter?(evt: PointerEvent): void;
onPointerLeave?(evt: PointerEvent): void;
onPointerCancel?(evt: PointerEvent): void;
}
export default class Pointable extends React.Component<PointableProps> {
static defaultProps: {
tagName: 'div',
touchAction: 'auto'
};
}
| Allow Pointable element to be an SVG element | Allow Pointable element to be an SVG element
| TypeScript | mit | mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,benliddicott/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,aciccarello/DefinitelyTyped,aciccarello/DefinitelyTyped,alexdresko/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,rolandzwaga/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,one-pieces/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,chrootsu/DefinitelyTyped,chrootsu/DefinitelyTyped,magny/DefinitelyTyped,alexdresko/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped | ---
+++
@@ -1,6 +1,7 @@
// Type definitions for react-pointable 1.1
// Project: https://github.com/MilllerTime/react-pointable
// Definitions by: Stefan Fochler <https://github.com/istefo>
+// Dibyo Majumdar <https://github.com/mdibyo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -8,10 +9,10 @@
export type TouchAction = 'auto' | 'none' | 'pan-x' | 'pan-y' | 'manipulation';
-export interface PointableProps extends React.HTMLAttributes<HTMLElement> {
- tagName?: keyof HTMLElementTagNameMap;
+export interface PointableProps extends React.HTMLAttributes<Element>, React.SVGAttributes<Element> {
+ tagName?: keyof ElementTagNameMap;
touchAction?: TouchAction;
- elementRef?(el: HTMLElement): void;
+ elementRef?(el: HTMLElement|SVGElement): void;
onPointerMove?(evt: PointerEvent): void;
onPointerDown?(evt: PointerEvent): void;
onPointerUp?(evt: PointerEvent): void; |
4f5934e507956b80c82fdd7e82375b075f78ab0d | addons/docs/src/frameworks/vue/extractArgTypes.ts | addons/docs/src/frameworks/vue/extractArgTypes.ts | import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor, hasDocgen, extractComponentProps } from '../../lib/docgen';
import { convert } from '../../lib/sbtypes';
import { trimQuotes } from '../../lib/sbtypes/utils';
const SECTIONS = ['props', 'events', 'slots'];
const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (!hasDocgen(component)) {
return null;
}
const results: ArgTypes = {};
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, docgenInfo, jsDocTags }) => {
const { name, type, description, defaultValue, required } = propDef;
const sbType = section === 'props' ? convert(docgenInfo) : { name: 'void' };
results[name] = {
name,
description,
type: { required, ...sbType },
defaultValue: defaultValue && trim(defaultValue.detail || defaultValue.summary),
table: {
type,
jsDocTags,
defaultValue,
category: section,
},
};
});
});
return results;
};
| import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor, hasDocgen, extractComponentProps } from '../../lib/docgen';
import { convert } from '../../lib/sbtypes';
import { trimQuotes } from '../../lib/sbtypes/utils';
const SECTIONS = ['props', 'events', 'slots'];
const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (!hasDocgen(component)) {
return null;
}
const results: ArgTypes = {};
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, docgenInfo, jsDocTags }) => {
const { name, type, description, defaultValue: defaultSummary, required } = propDef;
const sbType = section === 'props' ? convert(docgenInfo) : { name: 'void' };
let defaultValue = defaultSummary && (defaultSummary.detail || defaultSummary.summary);
try {
// eslint-disable-next-line no-eval
defaultValue = eval(defaultValue);
// eslint-disable-next-line no-empty
} catch {}
results[name] = {
name,
description,
type: { required, ...sbType },
defaultValue,
table: {
type,
jsDocTags,
defaultValue,
category: section,
},
};
});
});
return results;
};
| Fix default values for vue argTypes | Addon-docs: Fix default values for vue argTypes
| TypeScript | mit | storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -15,13 +15,20 @@
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, docgenInfo, jsDocTags }) => {
- const { name, type, description, defaultValue, required } = propDef;
+ const { name, type, description, defaultValue: defaultSummary, required } = propDef;
const sbType = section === 'props' ? convert(docgenInfo) : { name: 'void' };
+ let defaultValue = defaultSummary && (defaultSummary.detail || defaultSummary.summary);
+ try {
+ // eslint-disable-next-line no-eval
+ defaultValue = eval(defaultValue);
+ // eslint-disable-next-line no-empty
+ } catch {}
+
results[name] = {
name,
description,
type: { required, ...sbType },
- defaultValue: defaultValue && trim(defaultValue.detail || defaultValue.summary),
+ defaultValue,
table: {
type,
jsDocTags, |
ca4022f1fe20d15ca71b1a9b4e8db1701ac53952 | ui/src/main.ts | ui/src/main.ts | import {enableProdMode} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {Thread} from 'compiled_proto/src/proto/tagpost_pb';
import {TagpostServiceClient} from 'compiled_proto/src/proto/Tagpost_rpcServiceClientPb';
import {FetchThreadsByTagRequest} from 'compiled_proto/src/proto/tagpost_rpc_pb';
import {AppModule} from './app/app.module';
import {environment} from './environments/environment';
// Only for demo purpose. Can be removed after we have real protobuf use cases.
const thread = new Thread();
thread.setThreadId('12345');
const serialized = thread.serializeBinary();
console.log(serialized);
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
const tagpostService = new TagpostServiceClient('http://localhost:46764');
const fetchThreadsByTagRequest = new FetchThreadsByTagRequest();
fetchThreadsByTagRequest.setTag('noise');
tagpostService.fetchThreadsByTag(fetchThreadsByTagRequest, {}, (err, response) => {
if (err) {
console.error(err);
}
if (response) {
console.log(response);
}
});
| import {enableProdMode} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {Thread} from 'compiled_proto/src/proto/tagpost_pb';
import {TagpostServiceClient} from 'compiled_proto/src/proto/Tagpost_rpcServiceClientPb';
import {FetchThreadsByTagRequest} from 'compiled_proto/src/proto/tagpost_rpc_pb';
import {AppModule} from './app/app.module';
import {environment} from './environments/environment';
// Only for demo purpose. Can be removed after we have real protobuf use cases.
const thread = new Thread();
thread.setThreadId('12345');
const serialized = thread.serializeBinary();
console.log(serialized);
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
function createGrpcClient(): TagpostServiceClient {
let url = new URL('/', window.location.toString()).toString();
if (url.endsWith('/')) {
url = url.substring(0, url.length - 1);
}
return new TagpostServiceClient(url);
}
const tagpostService = createGrpcClient();
const fetchThreadsByTagRequest = new FetchThreadsByTagRequest();
fetchThreadsByTagRequest.setTag('noise');
tagpostService.fetchThreadsByTag(fetchThreadsByTagRequest, {}, (err, response) => {
if (err) {
console.error(err);
}
if (response) {
console.log(response);
}
});
| Use the same host for static content and gRPC in the UI | Use the same host for static content and gRPC in the UI
| TypeScript | apache-2.0 | googleinterns/tagpost,googleinterns/tagpost,googleinterns/tagpost,googleinterns/tagpost,googleinterns/tagpost | ---
+++
@@ -18,9 +18,17 @@
}
platformBrowserDynamic().bootstrapModule(AppModule)
- .catch(err => console.error(err));
+.catch(err => console.error(err));
-const tagpostService = new TagpostServiceClient('http://localhost:46764');
+function createGrpcClient(): TagpostServiceClient {
+ let url = new URL('/', window.location.toString()).toString();
+ if (url.endsWith('/')) {
+ url = url.substring(0, url.length - 1);
+ }
+ return new TagpostServiceClient(url);
+}
+
+const tagpostService = createGrpcClient();
const fetchThreadsByTagRequest = new FetchThreadsByTagRequest();
fetchThreadsByTagRequest.setTag('noise');
tagpostService.fetchThreadsByTag(fetchThreadsByTagRequest, {}, (err, response) => { |
3b28ee3da4279213820dac7d481dcf886a564eba | src/renderer/components/toolbar/toolbar.tsx | src/renderer/components/toolbar/toolbar.tsx | import { ipcRenderer } from 'electron';
import React, { MouseEventHandler } from 'react';
import './toolbar.css';
interface ToolbarProps {
onUrlEnter: (url: string) => void;
requestUpdate: (url: string) => void;
}
export default class ToolbarComponent extends React.Component<ToolbarProps, any> {
private urlInput: HTMLInputElement;
handleOpenButtonClick: MouseEventHandler<HTMLButtonElement> = (e) => {
const url = this.urlInput.value;
this.props.onUrlEnter(url);
};
handleUpdateButtonClick: MouseEventHandler<HTMLButtonElement> = (e) => {
const url = this.urlInput.value;
this.props.requestUpdate(url);
};
render() {
return (
<div className="toolbar">
<button onClick={(e) => ipcRenderer.send('open-subwindow-request')}>字幕</button>
<input type="text" className="url-input" ref={(node) => this.urlInput = node} defaultValue="http://jbbs.shitaraba.net/bbs/read.cgi/computer/42660/1462262759/" />
<button onClick={this.handleOpenButtonClick}>開く</button>
<button onClick={this.handleUpdateButtonClick}>更新</button>
</div>
);
}
}
| import { ipcRenderer } from 'electron';
import React from 'react';
import './toolbar.css';
interface ToolbarProps {
onUrlEnter: (url: string) => void;
requestUpdate: (url: string) => void;
}
export default class ToolbarComponent extends React.Component<ToolbarProps, any> {
private urlInput: HTMLInputElement;
handleOpenButtonClick = (e) => {
const url = this.urlInput.value;
this.props.onUrlEnter(url);
};
handleUpdateButtonClick = (e) => {
const url = this.urlInput.value;
this.props.requestUpdate(url);
};
render() {
return (
<div className="toolbar">
<button onClick={(e) => ipcRenderer.send('open-subwindow-request')}>字幕</button>
<input type="text" className="url-input" ref={(node) => this.urlInput = node} defaultValue="http://jbbs.shitaraba.net/bbs/read.cgi/computer/42660/1462262759/" />
<button onClick={this.handleOpenButtonClick}>開く</button>
<button onClick={this.handleUpdateButtonClick}>更新</button>
<label><input type="checkbox"/>自動更新</label>
</div>
);
}
}
| Stop applying types to component event handlers | Stop applying types to component event handlers
| TypeScript | mit | rikuba/conmai,rikuba/conmai,rikuba/conmai | ---
+++
@@ -1,6 +1,6 @@
import { ipcRenderer } from 'electron';
-import React, { MouseEventHandler } from 'react';
+import React from 'react';
import './toolbar.css';
@@ -12,12 +12,12 @@
export default class ToolbarComponent extends React.Component<ToolbarProps, any> {
private urlInput: HTMLInputElement;
- handleOpenButtonClick: MouseEventHandler<HTMLButtonElement> = (e) => {
+ handleOpenButtonClick = (e) => {
const url = this.urlInput.value;
this.props.onUrlEnter(url);
};
- handleUpdateButtonClick: MouseEventHandler<HTMLButtonElement> = (e) => {
+ handleUpdateButtonClick = (e) => {
const url = this.urlInput.value;
this.props.requestUpdate(url);
};
@@ -29,6 +29,7 @@
<input type="text" className="url-input" ref={(node) => this.urlInput = node} defaultValue="http://jbbs.shitaraba.net/bbs/read.cgi/computer/42660/1462262759/" />
<button onClick={this.handleOpenButtonClick}>開く</button>
<button onClick={this.handleUpdateButtonClick}>更新</button>
+ <label><input type="checkbox"/>自動更新</label>
</div>
);
} |
f9e395b27ef4b3d6cd957dd7e67bc2796152564b | app/CakeCounter.tsx | app/CakeCounter.tsx | import * as React from "react";
import { CakeProps } from "./Cake.tsx";
import { CakeListProps } from "./CakeList.tsx";
interface CakeCounterState {
daysSinceLastCake: number;
}
class CakeCounter extends React.Component<CakeListProps, CakeCounterState> {
constructor(props: CakeListProps) {
super(props);
this.state = {
daysSinceLastCake: this.calculateDaysSinceLastCake(this.props.cakes)
};
}
calculateDateDiffInDays(a: Date, b: Date): number {
const MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.abs(Math.floor((utc2 - utc1) / MILLISECONDS_IN_DAY));
}
calculateDaysSinceLastCake(cakes: any) {
const lastCake = this.props.cakes[0];
return this.calculateDateDiffInDays(new Date(), lastCake.date);
}
render() {
console.log("cakecounter render", new Date());
return (<div>
Days since last cake: {this.state.daysSinceLastCake}
</div>);
}
}
export {
CakeCounter
}; | import * as React from "react";
import { CakeProps } from "./Cake.tsx";
import { CakeListProps } from "./CakeList.tsx";
interface CakeCounterState {
daysSinceLastCake: number;
}
class CakeCounter extends React.Component<CakeListProps, CakeCounterState> {
constructor(props: CakeListProps) {
super(props);
this.calculateNewState = this.calculateNewState.bind(this);
this.state = this.calculateNewState(this.props);
}
calculateNewState(props: CakeListProps): CakeCounterState {
return {
daysSinceLastCake: this.calculateDaysSinceLastCake(props.cakes)
};
}
calculateDateDiffInDays(a: Date, b: Date): number {
const MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.abs(Math.floor((utc2 - utc1) / MILLISECONDS_IN_DAY));
}
componentWillReceiveProps(nextProps: CakeListProps) {
this.state = this.calculateNewState(nextProps);
}
calculateDaysSinceLastCake(cakes: any) {
const lastCake = this.props.cakes[0];
return this.calculateDateDiffInDays(new Date(), lastCake.date);
}
render() {
return (<div>
Days since last cake: {this.state.daysSinceLastCake}
</div>);
}
}
export {
CakeCounter
}; | Refresh cake counter when a cake is added | Refresh cake counter when a cake is added
| TypeScript | mit | mieky/we-love-cake,mieky/we-love-cake | ---
+++
@@ -10,8 +10,13 @@
constructor(props: CakeListProps) {
super(props);
- this.state = {
- daysSinceLastCake: this.calculateDaysSinceLastCake(this.props.cakes)
+ this.calculateNewState = this.calculateNewState.bind(this);
+ this.state = this.calculateNewState(this.props);
+ }
+
+ calculateNewState(props: CakeListProps): CakeCounterState {
+ return {
+ daysSinceLastCake: this.calculateDaysSinceLastCake(props.cakes)
};
}
@@ -25,13 +30,16 @@
return Math.abs(Math.floor((utc2 - utc1) / MILLISECONDS_IN_DAY));
}
+ componentWillReceiveProps(nextProps: CakeListProps) {
+ this.state = this.calculateNewState(nextProps);
+ }
+
calculateDaysSinceLastCake(cakes: any) {
const lastCake = this.props.cakes[0];
return this.calculateDateDiffInDays(new Date(), lastCake.date);
}
render() {
- console.log("cakecounter render", new Date());
return (<div>
Days since last cake: {this.state.daysSinceLastCake}
</div>); |
8e024f9731cd1510b47411985b855ff5529e2482 | ngapp/src/app/projects/projects-routing.module.ts | ngapp/src/app/projects/projects-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ProjectsComponent } from './projects.component';
import { ProjectComponent } from './project/project.component';
import { AuthGuard } from './../auth.guard';
const projectsRoutes = [
{ path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard] },
{ path: 'projects/:id', component: ProjectComponent }
]
@NgModule({
imports: [
RouterModule.forChild(projectsRoutes)
],
exports: [
RouterModule
]
})
export class ProjectsRoutingModule { } | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { ProjectsComponent } from './projects.component';
import { ProjectComponent } from './project/project.component';
import { AuthGuard } from './../auth.guard';
const projectsRoutes = [
{ path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard] },
{ path: 'projects/:id', component: ProjectComponent, canActivate: [AuthGuard] }
]
@NgModule({
imports: [
RouterModule.forChild(projectsRoutes)
],
exports: [
RouterModule
]
})
export class ProjectsRoutingModule { } | Add auth guard to projects/:id route | Add auth guard to projects/:id route
| TypeScript | mit | todes1/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot,todes1/parrot,todes1/parrot,anthonynsimon/parrot,anthonynsimon/parrot,todes1/parrot,anthonynsimon/parrot | ---
+++
@@ -6,7 +6,7 @@
const projectsRoutes = [
{ path: 'projects', component: ProjectsComponent, canActivate: [AuthGuard] },
- { path: 'projects/:id', component: ProjectComponent }
+ { path: 'projects/:id', component: ProjectComponent, canActivate: [AuthGuard] }
]
@NgModule({ |
faab1dc747ac139e7c6ac4160395a073276f9958 | src/nishe_test.ts | src/nishe_test.ts | ///<reference path='../node_modules/immutable/dist/immutable.d.ts'/>
///<reference path="../typings/jasmine/jasmine.d.ts" />
import nishe = require('nishe');
import Immutable = require('immutable');
describe('Partition', () => {
describe('domain', () => {
it('matches constructor', () => {
var p = new nishe.Partition(Immutable.Map({'a': 'a'}));
expect(p.domain().toArray()).toEqual(['a']);
});
it('throws if not a partition', () => {
expect(() => {
new nishe.Partition(Immutable.Map({'a': 'b'}));
}).toThrowError('The value b is not a key');
});
});
});
| ///<reference path='../node_modules/immutable/dist/immutable.d.ts'/>
///<reference path='../typings/jasmine/jasmine.d.ts'/>
import nishe = require('nishe');
import Immutable = require('immutable');
describe('Partition', () => {
describe('domain', () => {
it('matches constructor', () => {
let p = new nishe.Partition(Immutable.Map({'a': 'a'}));
expect(p.domain().toArray()).toEqual(['a']);
});
it('throws if not a partition', () => {
expect(() => {
new nishe.Partition(Immutable.Map({'a': 'b'}));
}).toThrowError('The value b is not a key');
});
});
});
| Use let instead of var in the test | Use let instead of var in the test
| TypeScript | mit | b0ri5/nishe,b0ri5/nishe | ---
+++
@@ -1,5 +1,5 @@
///<reference path='../node_modules/immutable/dist/immutable.d.ts'/>
-///<reference path="../typings/jasmine/jasmine.d.ts" />
+///<reference path='../typings/jasmine/jasmine.d.ts'/>
import nishe = require('nishe');
import Immutable = require('immutable');
@@ -7,7 +7,7 @@
describe('Partition', () => {
describe('domain', () => {
it('matches constructor', () => {
- var p = new nishe.Partition(Immutable.Map({'a': 'a'}));
+ let p = new nishe.Partition(Immutable.Map({'a': 'a'}));
expect(p.domain().toArray()).toEqual(['a']);
});
it('throws if not a partition', () => { |
7729f0c6821ca0d59b44da9aa70a7efc230da7c2 | plugins/kubernetes-api/ts/kubernetesApiGlobals.ts | plugins/kubernetes-api/ts/kubernetesApiGlobals.ts | /// <reference path="kubernetesApiInterfaces.ts"/>
declare var smokesignals;
module KubernetesAPI {
export var pluginName = 'hawtio-k8s-api';
export var pluginPath = 'plugins/kubernetes-api/';
export var templatePath = pluginPath + 'html/';
export var log:Logging.Logger = Logger.get(pluginName);
export var keepPollingModel = true;
export var defaultIconUrl = Core.url("/img/kubernetes.svg");
export var hostIconUrl = Core.url("/img/host.svg");
// this gets set as a pre-bootstrap task
export var osConfig:KubernetesConfig = undefined;
export var masterUrl = "";
export var isOpenShift = false;
export var K8S_PREFIX = 'api';
export var OS_PREFIX = 'oapi';
export var K8S_EXT_PREFIX = 'apis';
export var K8S_API_VERSION = 'v1';
export var OS_API_VERSION = 'v1';
export var K8S_EXT_VERSION = 'v1beta1';
export var K8S_EXTENSIONS = 'extensions';
export var defaultApiVersion = K8S_API_VERSION;
export var defaultOSApiVersion = OS_API_VERSION;
export var labelFilterTextSeparator = ",";
export var defaultNamespace = "default";
export var appSuffix = ".app";
}
| /// <reference path="kubernetesApiInterfaces.ts"/>
declare var smokesignals;
module KubernetesAPI {
export var pluginName = 'KubernetesAPI';
export var pluginPath = 'plugins/kubernetes-api/';
export var templatePath = pluginPath + 'html/';
export var log:Logging.Logger = Logger.get('hawtio-k8s-api');
export var keepPollingModel = true;
export var defaultIconUrl = Core.url("/img/kubernetes.svg");
export var hostIconUrl = Core.url("/img/host.svg");
// this gets set as a pre-bootstrap task
export var osConfig:KubernetesConfig = undefined;
export var masterUrl = "";
export var isOpenShift = false;
export var K8S_PREFIX = 'api';
export var OS_PREFIX = 'oapi';
export var K8S_EXT_PREFIX = 'apis';
export var K8S_API_VERSION = 'v1';
export var OS_API_VERSION = 'v1';
export var K8S_EXT_VERSION = 'v1beta1';
export var K8S_EXTENSIONS = 'extensions';
export var defaultApiVersion = K8S_API_VERSION;
export var defaultOSApiVersion = OS_API_VERSION;
export var labelFilterTextSeparator = ",";
export var defaultNamespace = "default";
export var appSuffix = ".app";
}
| Revert pluginName to KubernetesAPI as it is used downstream | Revert pluginName to KubernetesAPI as it is used downstream
| TypeScript | apache-2.0 | hawtio/hawtio-kubernetes-api,hawtio/hawtio-kubernetes-api,hawtio/hawtio-kubernetes-api | ---
+++
@@ -4,10 +4,10 @@
module KubernetesAPI {
- export var pluginName = 'hawtio-k8s-api';
+ export var pluginName = 'KubernetesAPI';
export var pluginPath = 'plugins/kubernetes-api/';
export var templatePath = pluginPath + 'html/';
- export var log:Logging.Logger = Logger.get(pluginName);
+ export var log:Logging.Logger = Logger.get('hawtio-k8s-api');
export var keepPollingModel = true;
|
44213dde8270a22aa87ba3b7ef835eb199e397a9 | src/_common/meta/seo-meta-container.ts | src/_common/meta/seo-meta-container.ts | import { MetaContainer } from './meta-container';
type RobotsTag = 'noindex' | 'nofollow';
type RobotsTags = Partial<{ [field in RobotsTag]: boolean }>;
export class SeoMetaContainer extends MetaContainer {
private robotsTags: RobotsTags = {};
deindex() {
this.robotsTags.noindex = true;
this.robotsTags.nofollow = true;
this._updateRobotsTag();
}
private _updateRobotsTag() {
const tags = Object.keys(this.robotsTags).join(' ');
if (tags) {
this.set('robots', tags);
}
}
}
| import { MetaContainer } from './meta-container';
type RobotsTag = 'noindex' | 'nofollow';
type RobotsTags = Partial<{ [field in RobotsTag]: boolean }>;
export class SeoMetaContainer extends MetaContainer {
private robotsTags: RobotsTags = {};
deindex() {
this.robotsTags.noindex = true;
this.robotsTags.nofollow = true;
this._updateRobotsTag();
}
private _updateRobotsTag() {
const tags = Object.keys(this.robotsTags).join(',');
if (tags) {
this.set('robots', tags);
}
}
}
| Fix deindexing not actually deindexing, ffs | Fix deindexing not actually deindexing, ffs
| TypeScript | mit | gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt,gamejolt/gamejolt | ---
+++
@@ -13,7 +13,7 @@
}
private _updateRobotsTag() {
- const tags = Object.keys(this.robotsTags).join(' ');
+ const tags = Object.keys(this.robotsTags).join(',');
if (tags) {
this.set('robots', tags);
} |
45986caffe0564cef28a5b5ccd89a9a57eadbd78 | src/api.ts | src/api.ts | /**
* defines the public API of Chevrotain.
* changes here may require major version change. (semVer)
*/
declare var CHEV_TEST_MODE
declare var global
var testMode = (typeof global === "object" && global.CHEV_TEST_MODE) ||
(typeof window === "object" && (<any>window).CHEV_TEST_MODE)
var API:any = {}
/* istanbul ignore next */
if (!testMode) {
// runtime API
API.Parser = chevrotain.recognizer.Parser
API.Lexer = chevrotain.lexer.Lexer
API.Token = chevrotain.tokens.Token
// utilities
API.extendToken = chevrotain.tokens.extendToken
// grammar reflection API
API.gast = {}
API.gast.GAstVisitor = chevrotain.gast.GAstVisitor
API.gast.FLAT = chevrotain.gast.FLAT
API.gast.AT_LEAST_ONE = chevrotain.gast.AT_LEAST_ONE
API.gast.MANY = chevrotain.gast.MANY
API.gast.OPTION = chevrotain.gast.OPTION
API.gast.OR = chevrotain.gast.OR
API.gast.ProdRef = chevrotain.gast.ProdRef
API.gast.Terminal = chevrotain.gast.Terminal
}
else {
console.log("running in TEST_MODE")
API = chevrotain
}
| /**
* defines the public API of Chevrotain.
* changes here may require major version change. (semVer)
*/
declare var CHEV_TEST_MODE
declare var global
var testMode = (typeof global === "object" && global.CHEV_TEST_MODE) ||
(typeof window === "object" && (<any>window).CHEV_TEST_MODE)
var API:any = {}
/* istanbul ignore next */
if (!testMode) {
// runtime API
API.Parser = chevrotain.recognizer.Parser
API.Lexer = chevrotain.lexer.Lexer
API.Token = chevrotain.tokens.Token
// utilities
API.extendToken = chevrotain.tokens.extendToken
// grammar reflection API
API.gast = {}
API.gast.GAstVisitor = chevrotain.gast.GAstVisitor
API.gast.FLAT = chevrotain.gast.FLAT
API.gast.AT_LEAST_ONE = chevrotain.gast.AT_LEAST_ONE
API.gast.MANY = chevrotain.gast.MANY
API.gast.OPTION = chevrotain.gast.OPTION
API.gast.OR = chevrotain.gast.OR
API.gast.ProdRef = chevrotain.gast.ProdRef
API.gast.Terminal = chevrotain.gast.Terminal
API.gast.TOP_LEVEL = chevrotain.gast.TOP_LEVEL
}
else {
console.log("running in TEST_MODE")
API = chevrotain
}
| Add gast.TOP_LEVEL to the API | Add gast.TOP_LEVEL to the API
| TypeScript | apache-2.0 | SAP/chevrotain,SAP/chevrotain,SAP/chevrotain,SAP/chevrotain | ---
+++
@@ -30,6 +30,7 @@
API.gast.OR = chevrotain.gast.OR
API.gast.ProdRef = chevrotain.gast.ProdRef
API.gast.Terminal = chevrotain.gast.Terminal
+ API.gast.TOP_LEVEL = chevrotain.gast.TOP_LEVEL
}
else {
console.log("running in TEST_MODE") |
dbd8f2d1c433e306f17346214637f4f4a5116216 | client/app/app-routing.module.ts | client/app/app-routing.module.ts | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
{ path: '', redirectTo: '/tables', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
| import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { environment } from '../environments/environment';
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
{ path: '', redirectTo: '/tables', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { useHash: environment.preview })
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
| Use hash routing in preview mode | Use hash routing in preview mode
| TypeScript | mit | mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium | ---
+++
@@ -1,6 +1,6 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
-
+import { environment } from '../environments/environment';
import { NotFoundComponent } from './not-found.component';
const routes: Routes = [
@@ -10,7 +10,7 @@
@NgModule({
imports: [
- RouterModule.forRoot(routes)
+ RouterModule.forRoot(routes, { useHash: environment.preview })
],
exports: [
RouterModule |
5adfda2e3598f29bf64e50a907301f339d11e367 | src/renderer/app/components/HistoryItem/index.tsx | src/renderer/app/components/HistoryItem/index.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
import store from '../../store';
import { HistoryItem } from '../../models';
import { formatTime } from '../../utils';
import { Favicon, Item, Remove, Title, Time, Site } from './style';
const onClick = (data: HistoryItem) => (e: React.MouseEvent) => {
if (e.ctrlKey) {
data.selected = !data.selected;
}
};
export default observer(({ data }: { data: HistoryItem }) => {
return (
<Item key={data._id} onClick={onClick(data)} selected={data.selected}>
<Favicon
style={{
backgroundImage: `url(${store.faviconsStore.favicons[data.favicon]})`,
}}
/>
<Title>{data.title}</Title>
<Site>{data.url.split('/')[2]}</Site>
<Time>{formatTime(new Date(data.date))}</Time>
<Remove />
</Item>
);
});
| import * as React from 'react';
import { observer } from 'mobx-react';
import store from '../../store';
import { HistoryItem } from '../../models';
import { formatTime } from '../../utils';
import { Favicon, Item, Remove, Title, Time, Site } from './style';
const onClick = (item: HistoryItem) => (e: React.MouseEvent) => {
if (e.ctrlKey) {
item.selected = !item.selected;
}
};
const onRemoveClick = (item: HistoryItem) => () => {
store.historyStore.removeItem(item._id);
};
export default observer(({ data }: { data: HistoryItem }) => {
return (
<Item key={data._id} onClick={onClick(data)} selected={data.selected}>
<Favicon
style={{
backgroundImage: `url(${store.faviconsStore.favicons[data.favicon]})`,
}}
/>
<Title>{data.title}</Title>
<Site>{data.url.split('/')[2]}</Site>
<Time>{formatTime(new Date(data.date))}</Time>
<Remove onClick={onRemoveClick(data)} />
</Item>
);
});
| Add basic deletion in history | Add basic deletion in history
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -6,10 +6,14 @@
import { formatTime } from '../../utils';
import { Favicon, Item, Remove, Title, Time, Site } from './style';
-const onClick = (data: HistoryItem) => (e: React.MouseEvent) => {
+const onClick = (item: HistoryItem) => (e: React.MouseEvent) => {
if (e.ctrlKey) {
- data.selected = !data.selected;
+ item.selected = !item.selected;
}
+};
+
+const onRemoveClick = (item: HistoryItem) => () => {
+ store.historyStore.removeItem(item._id);
};
export default observer(({ data }: { data: HistoryItem }) => {
@@ -23,7 +27,7 @@
<Title>{data.title}</Title>
<Site>{data.url.split('/')[2]}</Site>
<Time>{formatTime(new Date(data.date))}</Time>
- <Remove />
+ <Remove onClick={onRemoveClick(data)} />
</Item>
);
}); |
2a727b9e4028073adc7549e36ff49a95933a14c3 | app/src/ui/discard-changes/index.tsx | app/src/ui/discard-changes/index.tsx | import * as React from 'react'
import { Repository } from '../../models/repository'
import { Dispatcher } from '../../lib/dispatcher'
import { WorkingDirectoryFileChange } from '../../models/status'
interface IDiscardChangesProps {
readonly repository: Repository
readonly dispatcher: Dispatcher
readonly files: ReadonlyArray<WorkingDirectoryFileChange>
}
/** A component to confirm and then discard changes. */
export class DiscardChanges extends React.Component<IDiscardChangesProps, void> {
public render() {
const paths = this.props.files.map(f => f.path).join(', ')
return (
<form className='panel' onSubmit={this.cancel}>
<div>Confirm Discard Changes</div>
<div>Are you sure you want to discard all changes to {paths}?</div>
<button type='submit'>Cancel</button>
<button onClick={this.discard}>Discard Changes</button>
</form>
)
}
private cancel = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
this.props.dispatcher.closePopup()
}
private discard = () => {
this.props.dispatcher.discardChanges(this.props.repository, this.props.files)
}
}
| import * as React from 'react'
import { Repository } from '../../models/repository'
import { Dispatcher } from '../../lib/dispatcher'
import { WorkingDirectoryFileChange } from '../../models/status'
import { Form } from '../lib/form'
import { Button } from '../lib/button'
interface IDiscardChangesProps {
readonly repository: Repository
readonly dispatcher: Dispatcher
readonly files: ReadonlyArray<WorkingDirectoryFileChange>
}
/** A component to confirm and then discard changes. */
export class DiscardChanges extends React.Component<IDiscardChangesProps, void> {
public render() {
const paths = this.props.files.map(f => f.path).join(', ')
return (
<Form onSubmit={this.cancel}>
<div>Confirm Discard Changes</div>
<div>Are you sure you want to discard all changes to {paths}?</div>
<Button type='submit'>Cancel</Button>
<Button onClick={this.discard}>Discard Changes</Button>
</Form>
)
}
private cancel = () => {
this.props.dispatcher.closePopup()
}
private discard = () => {
this.props.dispatcher.discardChanges(this.props.repository, this.props.files)
}
}
| Use a Form for Discard Changes | Use a Form for Discard Changes
| TypeScript | mit | j-f1/forked-desktop,desktop/desktop,gengjiawen/desktop,gengjiawen/desktop,hjobrien/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,BugTesterTest/desktops,artivilla/desktop,BugTesterTest/desktops,artivilla/desktop,gengjiawen/desktop,j-f1/forked-desktop,hjobrien/desktop,artivilla/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,kactus-io/kactus,hjobrien/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,hjobrien/desktop,desktop/desktop,shiftkey/desktop,artivilla/desktop,gengjiawen/desktop,j-f1/forked-desktop,BugTesterTest/desktops,kactus-io/kactus,shiftkey/desktop,j-f1/forked-desktop,say25/desktop | ---
+++
@@ -3,6 +3,8 @@
import { Repository } from '../../models/repository'
import { Dispatcher } from '../../lib/dispatcher'
import { WorkingDirectoryFileChange } from '../../models/status'
+import { Form } from '../lib/form'
+import { Button } from '../lib/button'
interface IDiscardChangesProps {
readonly repository: Repository
@@ -15,19 +17,17 @@
public render() {
const paths = this.props.files.map(f => f.path).join(', ')
return (
- <form className='panel' onSubmit={this.cancel}>
+ <Form onSubmit={this.cancel}>
<div>Confirm Discard Changes</div>
<div>Are you sure you want to discard all changes to {paths}?</div>
- <button type='submit'>Cancel</button>
- <button onClick={this.discard}>Discard Changes</button>
- </form>
+ <Button type='submit'>Cancel</Button>
+ <Button onClick={this.discard}>Discard Changes</Button>
+ </Form>
)
}
- private cancel = (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault()
-
+ private cancel = () => {
this.props.dispatcher.closePopup()
}
|
41fea7fd5eefe0c4b7f13fb6ff7de0fafc68f68e | app/javascript/retrospring/features/lists/destroy.ts | app/javascript/retrospring/features/lists/destroy.ts | import Rails from '@rails/ujs';
import swal from 'sweetalert';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
export function destroyListHandler(event: Event): void {
event.preventDefault();
const button = event.target as HTMLButtonElement;
const list = button.dataset.list;
swal({
title: I18n.translate('frontend.list.confirm.title'),
text: I18n.translate('frontend.list.confirm.text'),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: I18n.translate('voc.delete'),
cancelButtonText: I18n.translate('voc.cancel'),
closeOnConfirm: true
}, () => {
Rails.ajax({
url: '/ajax/destroy_list',
type: 'POST',
data: new URLSearchParams({
list: list
}).toString(),
success: (data) => {
if (data.success) {
const element = document.querySelector(`li.list-group-item#list-${list}`);
if (element) {
element.remove();
}
}
showNotification(data.message, data.success);
},
error: (data, status, xhr) => {
console.log(data, status, xhr);
showErrorNotification(I18n.translate('frontend.error.message'));
}
});
});
} | import { post } from '@rails/request.js';
import swal from 'sweetalert';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
export function destroyListHandler(event: Event): void {
event.preventDefault();
const button = event.target as HTMLButtonElement;
const list = button.dataset.list;
swal({
title: I18n.translate('frontend.list.confirm.title'),
text: I18n.translate('frontend.list.confirm.text'),
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: I18n.translate('voc.delete'),
cancelButtonText: I18n.translate('voc.cancel'),
closeOnConfirm: true
}, () => {
post('/ajax/destroy_list', {
body: {
list: list
},
contentType: 'application/json'
})
.then(async response => {
const data = await response.json;
if (data.success) {
const element = document.querySelector(`li.list-group-item#list-${list}`);
if (element) {
element.remove();
}
}
showNotification(data.message, data.success);
})
.catch(err => {
console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
});
});
} | Refactor list removal to use request.js | Refactor list removal to use request.js
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -1,4 +1,4 @@
-import Rails from '@rails/ujs';
+import { post } from '@rails/request.js';
import swal from 'sweetalert';
import { showNotification, showErrorNotification } from 'utilities/notifications';
import I18n from 'retrospring/i18n';
@@ -18,13 +18,15 @@
cancelButtonText: I18n.translate('voc.cancel'),
closeOnConfirm: true
}, () => {
- Rails.ajax({
- url: '/ajax/destroy_list',
- type: 'POST',
- data: new URLSearchParams({
+ post('/ajax/destroy_list', {
+ body: {
list: list
- }).toString(),
- success: (data) => {
+ },
+ contentType: 'application/json'
+ })
+ .then(async response => {
+ const data = await response.json;
+
if (data.success) {
const element = document.querySelector(`li.list-group-item#list-${list}`);
@@ -34,11 +36,10 @@
}
showNotification(data.message, data.success);
- },
- error: (data, status, xhr) => {
- console.log(data, status, xhr);
+ })
+ .catch(err => {
+ console.log(err);
showErrorNotification(I18n.translate('frontend.error.message'));
- }
- });
+ });
});
} |
6ceaf2c238bceecb3453c5f6e207f6bf53617658 | app/resources/resource-edit-can-deactivate-guard.ts | app/resources/resource-edit-can-deactivate-guard.ts | import { Injectable } from '@angular/core';
import { CanDeactivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import {DocumentEditChangeMonitor} from "idai-components-2/documents";
import { ResourceEditNavigationComponent } from './resource-edit-navigation.component';
import { CanDeactivateGuardBase} from '../common/can-deactivate-guard-base';
/**
* @author Daniel de Oliveira
*/
@Injectable()
export class ResourceEditCanDeactivateGuard
extends CanDeactivateGuardBase
implements CanDeactivate<ResourceEditNavigationComponent> {
constructor (private documentEditChangeMonitor:DocumentEditChangeMonitor) {super();}
canDeactivate(
component: ResourceEditNavigationComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> | boolean {
return this.resolveOrShowModal(component,function() {
if (!this.documentEditChangeMonitor.isChanged()) {
if (component.mode=='new') {
component.discard();
}
return true;
}
return false;
}.bind(this));
}
}
| import { Injectable } from '@angular/core';
import { CanDeactivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import {DocumentEditChangeMonitor} from "idai-components-2/documents";
import { ResourceEditNavigationComponent } from './resource-edit-navigation.component';
import { CanDeactivateGuardBase} from '../common/can-deactivate-guard-base';
/**
* @author Daniel de Oliveira
*/
@Injectable()
export class ResourceEditCanDeactivateGuard
extends CanDeactivateGuardBase
implements CanDeactivate<ResourceEditNavigationComponent> {
constructor (private documentEditChangeMonitor:DocumentEditChangeMonitor) {super();}
canDeactivate(
component: ResourceEditNavigationComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> | boolean {
return this.resolveOrShowModal(component,function() {
if (!this.documentEditChangeMonitor.isChanged()) {
if (component.mode=='new') {
component.discard(true);
}
return true;
}
return false;
}.bind(this));
}
}
| Fix bug which caused a console error got thrown in tests. | Fix bug which caused a console error got thrown in tests.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -25,7 +25,7 @@
return this.resolveOrShowModal(component,function() {
if (!this.documentEditChangeMonitor.isChanged()) {
if (component.mode=='new') {
- component.discard();
+ component.discard(true);
}
return true;
} |
c92014e32f6d1b8c3ec3840ba15e063353231851 | app/js/components/delete_member.ts | app/js/components/delete_member.ts | import * as $ from 'jquery';
import addFlashMessage from './addFlashMessage';
$(() => {
const flashUl = document.querySelector('.teams__flashMessages') as HTMLUListElement;
const deleteLinks = document.querySelectorAll('.teams__deleteMemberLink');
if (!!flashUl && !!deleteLinks) {
document.addEventListener('click', (event) => {
const target = event.target as HTMLSelectElement;
if (!target.matches('.teams__deleteMemberLink')) return;
event.preventDefault();
const td = document.querySelector('.teams__actions') as HTMLTableDataCellElement;
td.classList.add('loading');
const url = target.getAttribute('href') || '';
const closeText = flashUl.getAttribute('data-close') || 'Close';
const deleteMemberText = flashUl.getAttribute('data-deleteMember') || '';
const name = target.getAttribute('data-name') || '';
fetch(url)
.then(response => response.json())
.then(data => {
if (data !== 'success') {
addFlashMessage(flashUl, data, 'error', closeText);
td.classList.remove('loading');
return;
}
const message = deleteMemberText.replace('<name>', name);
addFlashMessage(flashUl, message, 'info', closeText);
td.classList.remove('loading');
td.parentElement?.remove();
})
.catch(error => {
addFlashMessage(flashUl, error.message, 'error', closeText);
td.classList.remove('loading');
});
});
}
});
| import * as $ from 'jquery';
import addFlashMessage from './addFlashMessage';
$(() => {
const flashUl = document.querySelector('.teams__flashMessages') as HTMLUListElement;
const deleteLinks = document.querySelectorAll('.teams__deleteMemberLink');
if (!!flashUl && !!deleteLinks) {
document.addEventListener('click', (event) => {
const target = event.target as HTMLSelectElement;
if (!target.matches('.teams__deleteMemberLink')) return;
event.preventDefault();
const td = target.closest('td') as HTMLTableDataCellElement;
td.classList.add('loading');
const url = target.getAttribute('href') || '';
const closeText = flashUl.getAttribute('data-close') || 'Close';
const deleteMemberText = flashUl.getAttribute('data-deleteMember') || '';
const name = target.getAttribute('data-name') || '';
fetch(url)
.then(response => response.json())
.then(data => {
if (data !== 'success') {
addFlashMessage(flashUl, data, 'error', closeText);
td.classList.remove('loading');
return;
}
const message = deleteMemberText.replace('<name>', name);
addFlashMessage(flashUl, message, 'info', closeText);
td.classList.remove('loading');
td.parentElement?.remove();
})
.catch(error => {
addFlashMessage(flashUl, error.message, 'error', closeText);
td.classList.remove('loading');
});
});
}
});
| Fix visual deletion of a wrong entry | Fix visual deletion of a wrong entry
Previously when deleting a team member it would remove the first entry in the list, now it deletes the correct entry
| TypeScript | apache-2.0 | SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard,SURFnet/sp-dashboard | ---
+++
@@ -11,7 +11,7 @@
if (!target.matches('.teams__deleteMemberLink')) return;
event.preventDefault();
- const td = document.querySelector('.teams__actions') as HTMLTableDataCellElement;
+ const td = target.closest('td') as HTMLTableDataCellElement;
td.classList.add('loading');
const url = target.getAttribute('href') || ''; |
34d48853c1a8fe845d9cfac5cd137207325ddea3 | src/app/components/inline-assessment/comment-assessment.component.ts | src/app/components/inline-assessment/comment-assessment.component.ts | import {Component, Input} from "@angular/core";
@Component({
selector: 'comment-assessment',
template: `
<div class="panel" [hidden]="!hasVoted">
<div class="panel-body">
<h4>¿Porqué está {{tipo}}</h4>
<span class="hideOverflow">{{texto}}</span>
<textarea placeholder="máximo 250 caracteres ..." maxlength="250" style="width: 100%"></textarea>
<button class="btn btn-success btn-block">Aceptar</button>
</div>
</div>
`,
styles: [`
.hideOverflow{
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
max-width: 200px;
display:block;
}
`]
})
export class CommentAssessment {
@Input() tipo: string;
@Input() hasVoted: boolean;
@Input() texto: string;
} | import {Component, Input} from "@angular/core";
@Component({
selector: 'comment-assessment',
template: `
<div class="panel" [hidden]="!hasVoted">
<div class="panel-body">
<h4>¿Porqué está {{tipo}}</h4>
<span class="hideOverflow">{{texto}}</span>
<textarea placeholder="máximo 250 caracteres ..." maxlength="250" style="width: 100%"></textarea>
<button class="btn btn-success btn-block">Aceptar</button>
</div>
</div>
`,
styles: [`
.hideOverflow{
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
max-width: 240px;
display:block;
}
`]
})
export class CommentAssessment {
@Input() tipo: string;
@Input() hasVoted: boolean;
@Input() texto: string;
} | Improve some styles on inline assessment | Improve some styles on inline assessment
| TypeScript | agpl-3.0 | llopv/jetpad-ic,llopv/jetpad-ic,llopv/jetpad-ic | ---
+++
@@ -17,7 +17,7 @@
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
- max-width: 200px;
+ max-width: 240px;
display:block;
}
`] |
e0d9764f81562e94eb66e4dff81fa29cab1379ad | src/browser/note/note-collection/note-item/note-item-context-menu.ts | src/browser/note/note-collection/note-item/note-item-context-menu.ts | import { Injectable } from '@angular/core';
import { MenuItemConstructorOptions } from 'electron';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { commonMenuLabels, NativeMenu } from '../../../ui/menu';
export type NoteItemContextMenuCommand = 'revealInFinder';
@Injectable()
export class NoteItemContextMenu {
constructor(private nativeMenu: NativeMenu) {
}
open(): Observable<NoteItemContextMenuCommand | undefined> {
return this.nativeMenu.open(this.buildTemplate()).afterClosed().pipe(
map(item => item ? item.id as NoteItemContextMenuCommand : undefined),
);
}
private buildTemplate(): MenuItemConstructorOptions[] {
return [
{
id: 'revealInFinder',
label: commonMenuLabels.revealInFileManager,
},
];
}
}
| import { Injectable } from '@angular/core';
import { MenuItemConstructorOptions } from 'electron';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { commonMenuLabels, NativeMenu } from '../../../ui/menu';
export type NoteItemContextMenuCommand = 'revealInFinder' | 'deleteNote';
@Injectable()
export class NoteItemContextMenu {
constructor(private nativeMenu: NativeMenu) {
}
open(): Observable<NoteItemContextMenuCommand | undefined> {
return this.nativeMenu.open(this.buildTemplate()).afterClosed().pipe(
map(item => item ? item.id as NoteItemContextMenuCommand : undefined),
);
}
private buildTemplate(): MenuItemConstructorOptions[] {
return [
{
id: 'revealInFinder',
label: commonMenuLabels.revealInFileManager,
},
{
id: 'deleteNote',
label: `Move Note to ${commonMenuLabels.trashName}`,
},
];
}
}
| Add 'deleteNote' command on note item context menu | Add 'deleteNote' command on note item context menu
| TypeScript | mit | seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary | ---
+++
@@ -5,7 +5,7 @@
import { commonMenuLabels, NativeMenu } from '../../../ui/menu';
-export type NoteItemContextMenuCommand = 'revealInFinder';
+export type NoteItemContextMenuCommand = 'revealInFinder' | 'deleteNote';
@Injectable()
@@ -25,6 +25,10 @@
id: 'revealInFinder',
label: commonMenuLabels.revealInFileManager,
},
+ {
+ id: 'deleteNote',
+ label: `Move Note to ${commonMenuLabels.trashName}`,
+ },
];
}
} |
c74d17b8615d0f30bfd2784fdd5eac630dc16a62 | src/Carousel.webmodeler.ts | src/Carousel.webmodeler.ts | import { Component, createElement } from "react";
import { Carousel, Image } from "./components/Carousel";
import CarouselContainer, { CarouselContainerProps } from "./components/CarouselContainer";
// tslint:disable class-name
export class preview extends Component<CarouselContainerProps, {}> {
render() {
const validationAlert = CarouselContainer.validateProps(this.props);
return createElement(Carousel, {
alertMessage: validationAlert,
images: this.getImages(this.props)
});
}
private getImages(props: CarouselContainerProps): Image[] {
const defaultImages = [ { url: require("./img/Preview.jpg") } ];
if (props.dataSource === "static") {
return props.staticImages && props.staticImages.length
? props.staticImages
: defaultImages;
}
return defaultImages;
}
}
export function getPreviewCss() {
return require("./ui/Carousel.scss");
}
| import { Component, createElement } from "react";
import { Carousel, Image } from "./components/Carousel";
import CarouselContainer, { CarouselContainerProps } from "./components/CarouselContainer";
type VisibilityMap = {
[P in keyof CarouselContainerProps]: boolean;
};
// tslint:disable class-name
export class preview extends Component<CarouselContainerProps, {}> {
render() {
const validationAlert = CarouselContainer.validateProps(this.props);
return createElement(Carousel, {
alertMessage: validationAlert,
images: this.getImages(this.props)
});
}
private getImages(props: CarouselContainerProps): Image[] {
const defaultImages = [ { url: require("./img/Preview.jpg") } ];
if (props.dataSource === "static") {
return props.staticImages && props.staticImages.length
? props.staticImages
: defaultImages;
}
return defaultImages;
}
}
export function getPreviewCss() {
return require("./ui/Carousel.scss");
}
export function getVisibleProperties(props: CarouselContainerProps, visibilityMap: VisibilityMap) {
if (props.dataSource === "static") {
visibilityMap.imagesEntity = false;
visibilityMap.entityConstraint = false;
visibilityMap.dataSourceMicroflow = false;
visibilityMap.urlAttribute = false;
} else if (props.dataSource === "XPath") {
visibilityMap.staticImages = false;
visibilityMap.dataSourceMicroflow = false;
} else if (props.dataSource === "microflow") {
visibilityMap.staticImages = false;
visibilityMap.imagesEntity = false;
visibilityMap.entityConstraint = false;
}
if (props.onClickOptions === "doNothing") {
visibilityMap.onClickMicroflow = false;
visibilityMap.onClickForm = false;
} else if (props.onClickOptions === "callMicroflow") {
visibilityMap.onClickForm = false;
} else if (props.onClickOptions === "showPage") {
visibilityMap.onClickMicroflow = false;
}
}
| Add web modeler conditional visibility | Add web modeler conditional visibility
| TypeScript | apache-2.0 | mendixlabs/carousel,FlockOfBirds/carousel,mendixlabs/carousel,FlockOfBirds/carousel | ---
+++
@@ -2,6 +2,10 @@
import { Carousel, Image } from "./components/Carousel";
import CarouselContainer, { CarouselContainerProps } from "./components/CarouselContainer";
+
+type VisibilityMap = {
+ [P in keyof CarouselContainerProps]: boolean;
+};
// tslint:disable class-name
export class preview extends Component<CarouselContainerProps, {}> {
@@ -29,3 +33,28 @@
export function getPreviewCss() {
return require("./ui/Carousel.scss");
}
+
+export function getVisibleProperties(props: CarouselContainerProps, visibilityMap: VisibilityMap) {
+ if (props.dataSource === "static") {
+ visibilityMap.imagesEntity = false;
+ visibilityMap.entityConstraint = false;
+ visibilityMap.dataSourceMicroflow = false;
+ visibilityMap.urlAttribute = false;
+ } else if (props.dataSource === "XPath") {
+ visibilityMap.staticImages = false;
+ visibilityMap.dataSourceMicroflow = false;
+ } else if (props.dataSource === "microflow") {
+ visibilityMap.staticImages = false;
+ visibilityMap.imagesEntity = false;
+ visibilityMap.entityConstraint = false;
+ }
+
+ if (props.onClickOptions === "doNothing") {
+ visibilityMap.onClickMicroflow = false;
+ visibilityMap.onClickForm = false;
+ } else if (props.onClickOptions === "callMicroflow") {
+ visibilityMap.onClickForm = false;
+ } else if (props.onClickOptions === "showPage") {
+ visibilityMap.onClickMicroflow = false;
+ }
+} |
69d43e25f97e377efa1f2a840d18e6de629dd2e0 | src/delir-core/src/index.ts | src/delir-core/src/index.ts | // @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exceptions from './exceptions'
import ColorRGB from './struct/color-rgb'
import ColorRGBA from './struct/color-rgba'
import Type, {TypeDescriptor} from './plugin/type-descriptor'
import PluginBase from './plugin/plugin-base'
import RenderRequest from './renderer/render-request'
import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request'
import LayerPluginBase from './plugin/layer-plugin-base'
import EffectPluginBase from './plugin/effect-plugin-base'
import * as ProjectHelper from './helper/project-helper'
export {
// Core
Project,
Renderer,
Services,
Exceptions,
// Structure
ColorRGB,
ColorRGBA,
// Plugins
Type,
TypeDescriptor,
PluginBase,
LayerPluginBase,
EffectPluginBase,
PluginPreRenderRequest,
RenderRequest,
// import shorthand
ProjectHelper,
}
export default exports
| // @flow
import * as Project from './project/index'
import Renderer from './renderer/renderer'
import * as Services from './services'
import * as Exceptions from './exceptions'
import ColorRGB from './struct/color-rgb'
import ColorRGBA from './struct/color-rgba'
import Type, {TypeDescriptor} from './plugin/type-descriptor'
import PluginBase from './plugin/plugin-base'
import RenderRequest from './renderer/render-request'
import PluginPreRenderRequest from './renderer/plugin-pre-rendering-request'
import LayerPluginBase from './plugin/layer-plugin-base'
import EffectPluginBase from './plugin/effect-plugin-base'
import * as ProjectHelper from './helper/project-helper'
export {
// Core
Project,
Renderer,
Services,
Exceptions,
// Structure
ColorRGB,
ColorRGBA,
// Plugins
Type,
TypeDescriptor,
PluginBase,
LayerPluginBase,
EffectPluginBase,
PluginPreRenderRequest,
RenderRequest,
// import shorthand
ProjectHelper,
} | Stop `export {...}` on delir-core | Stop `export {...}` on delir-core
`export default exports`でエラーが出始めて
`export _exports`とか試したけど出来なかったし、2箇所で同じような項目扱うのもめんどうなのでやめろ
| TypeScript | mit | Ragg-/Delir,Ragg-/Delir,Ragg-/Delir,Ragg-/Delir | ---
+++
@@ -39,5 +39,3 @@
// import shorthand
ProjectHelper,
}
-
-export default exports |
7431e7b7f62314135aeda6c6176f7ad80fc74e5f | app/src/models/account.ts | app/src/models/account.ts | import { getDotComAPIEndpoint, IAPIEmail } from '../lib/api'
/**
* A GitHub account, representing the user found on GitHub The Website or GitHub Enterprise Server.
*
* This contains a token that will be used for operations that require authentication.
*/
export class Account {
/** Create an account which can be used to perform unauthenticated API actions */
public static anonymous(): Account {
return new Account('', getDotComAPIEndpoint(), '', [], '', -1, '')
}
/**
* Create an instance of an account
*
* @param login The login name for this account
* @param endpoint The server for this account - GitHub or a GitHub Enterprise Server instance
* @param token The access token used to perform operations on behalf of this account
* @param emails The current list of email addresses associated with the account
* @param avatarURL The profile URL to render for this account
* @param id The database id for this account
* @param name The friendly name associated with this account
*/
public constructor(
public readonly login: string,
public readonly endpoint: string,
public readonly token: string,
public readonly emails: ReadonlyArray<IAPIEmail>,
public readonly avatarURL: string,
public readonly id: number,
public readonly name: string
) {}
public withToken(token: string): Account {
return new Account(
this.login,
this.endpoint,
token,
this.emails,
this.avatarURL,
this.id,
this.name
)
}
}
| import { getDotComAPIEndpoint, IAPIEmail } from '../lib/api'
/**
* A GitHub account, representing the user found on GitHub The Website or GitHub Enterprise Server.
*
* This contains a token that will be used for operations that require authentication.
*/
export class Account {
/** Create an account which can be used to perform unauthenticated API actions */
public static anonymous(): Account {
return new Account('', getDotComAPIEndpoint(), '', [], '', -1, '')
}
/**
* Create an instance of an account
*
* @param login The login name for this account
* @param endpoint The server for this account - GitHub or a GitHub Enterprise Server instance
* @param token The access token used to perform operations on behalf of this account
* @param emails The current list of email addresses associated with the account
* @param avatarURL The profile URL to render for this account
* @param id The GitHub.com or GitHub Enterprise Server database id for this account.
* @param name The friendly name associated with this account
*/
public constructor(
public readonly login: string,
public readonly endpoint: string,
public readonly token: string,
public readonly emails: ReadonlyArray<IAPIEmail>,
public readonly avatarURL: string,
public readonly id: number,
public readonly name: string
) {}
public withToken(token: string): Account {
return new Account(
this.login,
this.endpoint,
token,
this.emails,
this.avatarURL,
this.id,
this.name
)
}
}
| Clarify that this isn't a desktop id | Clarify that this isn't a desktop id
| TypeScript | mit | artivilla/desktop,say25/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,j-f1/forked-desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,say25/desktop | ---
+++
@@ -19,7 +19,7 @@
* @param token The access token used to perform operations on behalf of this account
* @param emails The current list of email addresses associated with the account
* @param avatarURL The profile URL to render for this account
- * @param id The database id for this account
+ * @param id The GitHub.com or GitHub Enterprise Server database id for this account.
* @param name The friendly name associated with this account
*/
public constructor( |
085cabf8e01f485aac6ce87b0427e0de92022483 | tests/cases/fourslash/completionListInExtendsClause.ts | tests/cases/fourslash/completionListInExtendsClause.ts | /// <reference path='fourslash.ts' />
////interface IFoo {
//// method();
////}
////
////class Foo {
//// property: number;
//// method() { }
//// static staticMethod() { }
////}
////class test1 extends Foo./*1*/ {}
////class test2 implements IFoo./*2*/ {}
////interface test3 extends IFoo./*3*/ {}
////interface test4 implements Foo./*4*/ {}
test.markers().forEach((marker) => {
goTo.position(marker.position, marker.fileName);
verify.completionListIsEmpty();
});
| /// <reference path='fourslash.ts' />
////interface IFoo {
//// method();
////}
////
////class Foo {
//// property: number;
//// method() { }
//// static staticMethod() { }
////}
////class test1 extends Foo./*1*/ {}
////class test2 implements IFoo./*2*/ {}
////interface test3 extends IFoo./*3*/ {}
////interface test4 implements Foo./*4*/ {}
goTo.marker("1");
verify.completionListIsEmpty();
goTo.marker("2");
verify.completionListIsEmpty();
goTo.marker("3");
verify.completionListIsEmpty();
// This needs comletion list filtering based on location to work
goTo.marker("4");
verify.not.completionListIsEmpty(); | Change test untill we have filtering on location | Change test untill we have filtering on location
| TypeScript | apache-2.0 | jteplitz602/TypeScript,AbubakerB/TypeScript,plantain-00/TypeScript,AbubakerB/TypeScript,chuckjaz/TypeScript,Mqgh2013/TypeScript,zmaruo/TypeScript,kimamula/TypeScript,MartyIX/TypeScript,DanielRosenwasser/TypeScript,HereSinceres/TypeScript,enginekit/TypeScript,OlegDokuka/TypeScript,ziacik/TypeScript,DLehenbauer/TypeScript,ionux/TypeScript,JohnZ622/TypeScript,progre/TypeScript,DLehenbauer/TypeScript,RyanCavanaugh/TypeScript,msynk/TypeScript,abbasmhd/TypeScript,mszczepaniak/TypeScript,mmoskal/TypeScript,ZLJASON/TypeScript,gonifade/TypeScript,jnetterf/typescript-react-jsx,mauricionr/TypeScript,pcan/TypeScript,nojvek/TypeScript,zmaruo/TypeScript,yortus/TypeScript,alexeagle/TypeScript,zmaruo/TypeScript,sassson/TypeScript,blakeembrey/TypeScript,fabioparra/TypeScript,ionux/TypeScript,evgrud/TypeScript,vilic/TypeScript,hitesh97/TypeScript,ionux/TypeScript,ZLJASON/TypeScript,pcan/TypeScript,jteplitz602/TypeScript,fdecampredon/jsx-typescript,webhost/TypeScript,TukekeSoft/TypeScript,Viromo/TypeScript,moander/TypeScript,wangyanxing/TypeScript,webhost/TypeScript,jnetterf/typescript-react-jsx,thr0w/Thr0wScript,JohnZ622/TypeScript,mihailik/TypeScript,SaschaNaz/TypeScript,Raynos/TypeScript,SimoneGianni/TypeScript,RReverser/TypeScript,fearthecowboy/TypeScript,hitesh97/TypeScript,matthewjh/TypeScript,jnetterf/typescript-react-jsx,minestarks/TypeScript,billti/TypeScript,kumikumi/TypeScript,kimamula/TypeScript,rodrigues-daniel/TypeScript,DanielRosenwasser/TypeScript,OlegDokuka/TypeScript,jwbay/TypeScript,thr0w/Thr0wScript,vilic/TypeScript,gdi2290/TypeScript,RReverser/TypeScript,mauricionr/TypeScript,yukulele/TypeScript,Viromo/TypeScript,microsoft/TypeScript,nagyistoce/TypeScript,kumikumi/TypeScript,jamesrmccallum/TypeScript,rodrigues-daniel/TypeScript,thr0w/Thr0wScript,blakeembrey/TypeScript,donaldpipowitch/TypeScript,tempbottle/TypeScript,minestarks/TypeScript,synaptek/TypeScript,SmallAiTT/TypeScript,basarat/TypeScript,MartyIX/TypeScript,fdecampredon/jsx-typescript,weswigham/TypeScript,sassson/TypeScript,mmoskal/TypeScript,shanexu/TypeScript,jdavidberger/TypeScript,germ13/TypeScript,ziacik/TypeScript,ropik/TypeScript,zhengbli/TypeScript,impinball/TypeScript,kpreisser/TypeScript,tinganho/TypeScript,hoanhtien/TypeScript,tempbottle/TypeScript,basarat/TypeScript,mcanthony/TypeScript,chuckjaz/TypeScript,pcan/TypeScript,webhost/TypeScript,ziacik/TypeScript,keir-rex/TypeScript,samuelhorwitz/typescript,weswigham/TypeScript,suto/TypeScript,Eyas/TypeScript,gonifade/TypeScript,SmallAiTT/TypeScript,synaptek/TypeScript,fabioparra/TypeScript,tinganho/TypeScript,erikmcc/TypeScript,rgbkrk/TypeScript,billti/TypeScript,erikmcc/TypeScript,nycdotnet/TypeScript,progre/TypeScript,blakeembrey/TypeScript,zhengbli/TypeScript,fdecampredon/jsx-typescript,enginekit/TypeScript,jamesrmccallum/TypeScript,chuckjaz/TypeScript,suto/TypeScript,ropik/TypeScript,hitesh97/TypeScript,rodrigues-daniel/TypeScript,kitsonk/TypeScript,shovon/TypeScript,moander/TypeScript,TukekeSoft/TypeScript,MartyIX/TypeScript,donaldpipowitch/TypeScript,samuelhorwitz/typescript,kingland/TypeScript,msynk/TypeScript,MartyIX/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,mauricionr/TypeScript,mcanthony/TypeScript,JohnZ622/TypeScript,Mqgh2013/TypeScript,moander/TypeScript,impinball/TypeScript,zhengbli/TypeScript,plantain-00/TypeScript,fabioparra/TypeScript,vilic/TypeScript,jwbay/TypeScript,shiftkey/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,abbasmhd/TypeScript,msynk/TypeScript,thr0w/Thr0wScript,chuckjaz/TypeScript,Microsoft/TypeScript,tinganho/TypeScript,Eyas/TypeScript,shovon/TypeScript,yortus/TypeScript,fdecampredon/jsx-typescript,samuelhorwitz/typescript,kitsonk/TypeScript,progre/TypeScript,yazeng/TypeScript,RReverser/TypeScript,Raynos/TypeScript,yazeng/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,mmoskal/TypeScript,fabioparra/TypeScript,kingland/TypeScript,germ13/TypeScript,jbondc/TypeScript,mszczepaniak/TypeScript,nycdotnet/TypeScript,kimamula/TypeScript,minestarks/TypeScript,Eyas/TypeScript,samuelhorwitz/typescript,nagyistoce/TypeScript,RyanCavanaugh/TypeScript,shovon/TypeScript,kimamula/TypeScript,AbubakerB/TypeScript,nycdotnet/TypeScript,yortus/TypeScript,rodrigues-daniel/TypeScript,SmallAiTT/TypeScript,nagyistoce/TypeScript,jeremyepling/TypeScript,SaschaNaz/TypeScript,bpowers/TypeScript,alexeagle/TypeScript,RyanCavanaugh/TypeScript,billti/TypeScript,mcanthony/TypeScript,chocolatechipui/TypeScript,kpreisser/TypeScript,mihailik/TypeScript,jteplitz602/TypeScript,DanielRosenwasser/TypeScript,erikmcc/TypeScript,DanielRosenwasser/TypeScript,microsoft/TypeScript,jbondc/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,evgrud/TypeScript,synaptek/TypeScript,fearthecowboy/TypeScript,yukulele/TypeScript,erikmcc/TypeScript,TukekeSoft/TypeScript,hoanhtien/TypeScript,rgbkrk/TypeScript,yukulele/TypeScript,donaldpipowitch/TypeScript,bpowers/TypeScript,chocolatechipui/TypeScript,Raynos/TypeScript,mszczepaniak/TypeScript,jdavidberger/TypeScript,ropik/TypeScript,sassson/TypeScript,nycdotnet/TypeScript,nojvek/TypeScript,HereSinceres/TypeScript,ZLJASON/TypeScript,moander/TypeScript,basarat/TypeScript,Viromo/TypeScript,matthewjh/TypeScript,shanexu/TypeScript,yazeng/TypeScript,shanexu/TypeScript,jeremyepling/TypeScript,rgbkrk/TypeScript,mihailik/TypeScript,ropik/TypeScript,matthewjh/TypeScript,AbubakerB/TypeScript,shanexu/TypeScript,jdavidberger/TypeScript,abbasmhd/TypeScript,bpowers/TypeScript,jwbay/TypeScript,ionux/TypeScript,evgrud/TypeScript,nojvek/TypeScript,mauricionr/TypeScript,DLehenbauer/TypeScript,impinball/TypeScript,kumikumi/TypeScript,ziacik/TypeScript,DLehenbauer/TypeScript,JohnZ622/TypeScript,SimoneGianni/TypeScript,Eyas/TypeScript,jwbay/TypeScript,hoanhtien/TypeScript,shiftkey/TypeScript,kitsonk/TypeScript,basarat/TypeScript,mihailik/TypeScript,chocolatechipui/TypeScript,wangyanxing/TypeScript,suto/TypeScript,mmoskal/TypeScript,donaldpipowitch/TypeScript,OlegDokuka/TypeScript,jbondc/TypeScript,shiftkey/TypeScript,germ13/TypeScript,plantain-00/TypeScript,SimoneGianni/TypeScript,Raynos/TypeScript,Viromo/TypeScript,keir-rex/TypeScript,HereSinceres/TypeScript,tempbottle/TypeScript,kpreisser/TypeScript,keir-rex/TypeScript,blakeembrey/TypeScript,jamesrmccallum/TypeScript,yortus/TypeScript,fearthecowboy/TypeScript,mcanthony/TypeScript,kingland/TypeScript,Microsoft/TypeScript,enginekit/TypeScript,gonifade/TypeScript,Mqgh2013/TypeScript,plantain-00/TypeScript,synaptek/TypeScript,wangyanxing/TypeScript,jeremyepling/TypeScript,evgrud/TypeScript | ---
+++
@@ -18,8 +18,15 @@
////interface test4 implements Foo./*4*/ {}
-test.markers().forEach((marker) => {
- goTo.position(marker.position, marker.fileName);
+goTo.marker("1");
+verify.completionListIsEmpty();
- verify.completionListIsEmpty();
-});
+goTo.marker("2");
+verify.completionListIsEmpty();
+
+goTo.marker("3");
+verify.completionListIsEmpty();
+
+// This needs comletion list filtering based on location to work
+goTo.marker("4");
+verify.not.completionListIsEmpty(); |
50fbdb41bed90381a2d048c9b18e2f45ccdd1021 | src/v2/components/UI/Head/components/Title/index.tsx | src/v2/components/UI/Head/components/Title/index.tsx | import React from 'react'
import { unescape } from 'underscore'
import Head from 'v2/components/UI/Head'
export const TITLE_TEMPLATE = 'Are.na / %s'
interface Props {
children: string
}
export const Title: React.FC<Props> = ({ children }) => {
const title = TITLE_TEMPLATE.replace('%s', unescape(children))
return (
<Head>
<title>{title}</title>
<meta name="twitter:title" content={title} />
<meta property="og:title" content={title} />
</Head>
)
}
export default Title
| import React from 'react'
import { unescape } from 'underscore'
import Head from 'v2/components/UI/Head'
export const TITLE_TEMPLATE = '%s — Are.na'
interface Props {
children: string
}
export const Title: React.FC<Props> = ({ children }) => {
const title = TITLE_TEMPLATE.replace('%s', unescape(children))
return (
<Head>
<title>{title}</title>
<meta name="twitter:title" content={title} />
<meta property="og:title" content={title} />
</Head>
)
}
export default Title
| Switch title tag template so Are.na goes last | Switch title tag template so Are.na goes last
| TypeScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -3,7 +3,7 @@
import Head from 'v2/components/UI/Head'
-export const TITLE_TEMPLATE = 'Are.na / %s'
+export const TITLE_TEMPLATE = '%s — Are.na'
interface Props {
children: string |
c8f77b9d9b0343270516ec591a53fd1853804125 | packages/kernel-relay/__tests__/index.spec.ts | packages/kernel-relay/__tests__/index.spec.ts | import { gql } from "apollo-server";
import { createTestClient } from "apollo-server-testing";
import { server } from "../src";
describe("Queries", () => {
it("returns a list of kernelspecs", async () => {
const { query } = createTestClient(server);
const kernelspecsQuery = gql`
query GetKernels {
listKernelSpecs {
name
}
}
`;
const response = await query({ query: kernelspecsQuery });
expect(response).not.toBeNull();
expect(response.data.listKernelSpecs.length).toBeGreaterThan(0);
});
});
| import { gql } from "apollo-server";
import { createTestClient } from "apollo-server-testing";
import { server } from "../src";
describe("Queries", () => {
it("returns a list of kernelspecs", async () => {
const { query } = createTestClient(server);
const LIST_KERNELSPECS = gql`
query GetKernels {
listKernelSpecs {
name
}
}
`;
const response = await query({ query: LIST_KERNELSPECS });
expect(response).not.toBeNull();
expect(response.data.listKernelSpecs.length).toBeGreaterThan(0);
});
});
describe("Mutations", () => {
let kernelId;
it("launches a kernel", async () => {
const { mutate } = createTestClient(server);
const START_KERNEL = gql`
mutation StartJupyterKernel {
startKernel(name: "python3") {
id
status
}
}
`;
const response = await mutate({ mutation: START_KERNEL });
kernelId = response.data.startKernel.id;
expect(response).not.toBeNull();
expect(response.data.startKernel.status).toBe("launched");
});
it("shuts down a kernel", async () => {
const { mutate } = createTestClient(server);
const SHUTDOWN_KERNEL = gql`
mutation KillJupyterKernel($id: ID) {
shutdownKernel(id: $id) {
id
status
}
}
`;
const response = await mutate({
mutation: SHUTDOWN_KERNEL,
variables: { id: kernelId }
});
expect(response).not.toBeNull();
expect(response.data.shutdownKernel.status).toBe("shutdown");
});
});
| Add tests for GraphQL mutations | Add tests for GraphQL mutations
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition | ---
+++
@@ -5,15 +5,52 @@
describe("Queries", () => {
it("returns a list of kernelspecs", async () => {
const { query } = createTestClient(server);
- const kernelspecsQuery = gql`
+ const LIST_KERNELSPECS = gql`
query GetKernels {
listKernelSpecs {
name
}
}
`;
- const response = await query({ query: kernelspecsQuery });
+ const response = await query({ query: LIST_KERNELSPECS });
expect(response).not.toBeNull();
expect(response.data.listKernelSpecs.length).toBeGreaterThan(0);
});
});
+
+describe("Mutations", () => {
+ let kernelId;
+ it("launches a kernel", async () => {
+ const { mutate } = createTestClient(server);
+ const START_KERNEL = gql`
+ mutation StartJupyterKernel {
+ startKernel(name: "python3") {
+ id
+ status
+ }
+ }
+ `;
+ const response = await mutate({ mutation: START_KERNEL });
+ kernelId = response.data.startKernel.id;
+
+ expect(response).not.toBeNull();
+ expect(response.data.startKernel.status).toBe("launched");
+ });
+ it("shuts down a kernel", async () => {
+ const { mutate } = createTestClient(server);
+ const SHUTDOWN_KERNEL = gql`
+ mutation KillJupyterKernel($id: ID) {
+ shutdownKernel(id: $id) {
+ id
+ status
+ }
+ }
+ `;
+ const response = await mutate({
+ mutation: SHUTDOWN_KERNEL,
+ variables: { id: kernelId }
+ });
+ expect(response).not.toBeNull();
+ expect(response.data.shutdownKernel.status).toBe("shutdown");
+ });
+}); |
cbbe9806d28df9a21f34bb30e5553721ed694d67 | saleor/static/dashboard-next/storybook/Decorator.tsx | saleor/static/dashboard-next/storybook/Decorator.tsx | import * as React from "react";
import AppActionContext from "../components/AppLayout/AppActionContext";
import { Provider as DateProvider } from "../components/Date/DateContext";
import { FormProvider } from "../components/Form";
import { MessageManager } from "../components/messages";
import ThemeProvider from "../components/Theme";
import { TimezoneProvider } from "../components/Timezone";
const DecoratorComponent: React.FC<{ story: any }> = ({ story }) => {
const appActionAnchor = React.useRef<HTMLDivElement>();
return (
<FormProvider>
<DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
<TimezoneProvider value="America/New_York">
<ThemeProvider isDefaultDark={false}>
<MessageManager>
<AppActionContext.Provider value={appActionAnchor}>
<div
style={{
display: "flex",
flexGrow: 1,
padding: 24
}}
>
{story}
</div>
<div
style={{
bottom: 0,
gridColumn: 2,
position: "sticky"
}}
ref={appActionAnchor}
/>
</AppActionContext.Provider>
</MessageManager>
</ThemeProvider>
</TimezoneProvider>
</DateProvider>
</FormProvider>
);
};
export const Decorator = storyFn => <DecoratorComponent story={storyFn()} />;
export default Decorator;
| import * as React from "react";
import AppActionContext from "../components/AppLayout/AppActionContext";
import { Provider as DateProvider } from "../components/Date/DateContext";
import { FormProvider } from "../components/Form";
import { MessageManager } from "../components/messages";
import ThemeProvider from "../components/Theme";
import { TimezoneProvider } from "../components/Timezone";
const DecoratorComponent: React.FC<{ story: any }> = ({ story }) => {
const appActionAnchor = React.useRef<HTMLDivElement>();
return (
<FormProvider>
<DateProvider value={+new Date("2018-08-07T14:30:44+00:00")}>
<TimezoneProvider value="America/New_York">
<ThemeProvider isDefaultDark={false}>
<MessageManager>
<AppActionContext.Provider value={appActionAnchor}>
<div
style={{
display: "flex",
flexGrow: 1,
padding: 24
}}
>
<div style={{ flexGrow: 1 }}>{story}</div>
</div>
<div
style={{
bottom: 0,
gridColumn: 2,
position: "sticky"
}}
ref={appActionAnchor}
/>
</AppActionContext.Provider>
</MessageManager>
</ThemeProvider>
</TimezoneProvider>
</DateProvider>
</FormProvider>
);
};
export const Decorator = storyFn => <DecoratorComponent story={storyFn()} />;
export default Decorator;
| Fix flex horizontal size issue | Fix flex horizontal size issue
| TypeScript | bsd-3-clause | maferelo/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -24,7 +24,7 @@
padding: 24
}}
>
- {story}
+ <div style={{ flexGrow: 1 }}>{story}</div>
</div>
<div
style={{ |
5a7bb894e1a132e01ce63f75d7f6ac04eb46c2d1 | resources/app/auth/services/auth.service.ts | resources/app/auth/services/auth.service.ts | export interface IAuthService {
isLoggedIn();
}
export class AuthService {
static NAME = 'AuthService';
constructor(
private $http: ng.IHttpService,
private $window: ng.IWindowService
) {
'ngInject';
}
isLoggedIn() {
return this.$window.localStorage.getItem('token') !== null;
}
static factory() {
return ($http, $window) => new AuthService($http, $window);
}
} | export interface IAuthService {
isLoggedIn();
}
export class AuthService {
static NAME = 'AuthService';
config;
url;
constructor(
private $http: ng.IHttpService,
private $window: ng.IWindowService,
private $httpParamSerializerJQLike: ng.IHttpParamSerializer
) {
'ngInject';
this.config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
this.url = 'http://localhost:8080/api'
}
isLoggedIn() {
return this.$window.localStorage.getItem('token') !== null;
}
login(user) {
return this.$http.post(
this.url + '/login',
this.$httpParamSerializerJQLike(user),
this.config
)
.then(response => response.data);
}
static factory() {
return (
$http, $window, $httpParamSerializerJQLike
) => new AuthService($http, $window, $httpParamSerializerJQLike);
}
} | Add user login method to AuthService | Add user login method to AuthService
| TypeScript | mit | ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io,ibnumalik/ibnumalik.github.io | ---
+++
@@ -4,20 +4,42 @@
export class AuthService {
static NAME = 'AuthService';
+ config;
+ url;
constructor(
private $http: ng.IHttpService,
- private $window: ng.IWindowService
+ private $window: ng.IWindowService,
+ private $httpParamSerializerJQLike: ng.IHttpParamSerializer
) {
'ngInject';
+
+ this.config = {
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded'
+ }
+ }
+ this.url = 'http://localhost:8080/api'
}
isLoggedIn() {
return this.$window.localStorage.getItem('token') !== null;
}
+ login(user) {
+
+ return this.$http.post(
+ this.url + '/login',
+ this.$httpParamSerializerJQLike(user),
+ this.config
+ )
+ .then(response => response.data);
+ }
+
static factory() {
- return ($http, $window) => new AuthService($http, $window);
+ return (
+ $http, $window, $httpParamSerializerJQLike
+ ) => new AuthService($http, $window, $httpParamSerializerJQLike);
}
} |
626efa502acdfdc5a26b09d3a9f7b15240d5f5ba | client/Utility/Metrics.ts | client/Utility/Metrics.ts | import { Store } from "./Store";
interface EventData {
[key: string]: any;
}
export class Metrics {
public static TrackLoad(): void {
const counts = {
Encounters: Store.List(Store.SavedEncounters).length,
NpcStatBlocks: Store.List(Store.StatBlocks).length,
PcStatBlocks: Store.List(Store.PlayerCharacters).length,
Spells: Store.List(Store.Spells).length
};
Metrics.TrackEvent("AppLoad", counts);
}
public static TrackEvent(name: string, data: EventData = {}): void {
if (!Store.Load(Store.User, "AllowTracking")) {
return;
}
console.log(`Event ${name}`);
if (data !== {}) {
console.table(data);
}
data.referrer = { url: document.referrer };
data.page = { url: document.URL };
data.localTime = new Date().toString();
$.ajax({
type: "POST",
url: `/recordEvent/${name}`,
data: JSON.stringify(data || {}),
contentType: "application/json"
});
}
}
| import { Store } from "./Store";
interface EventData {
[key: string]: any;
}
export class Metrics {
public static TrackLoad(): void {
const counts = {
Encounters: Store.List(Store.SavedEncounters).length,
NpcStatBlocks: Store.List(Store.StatBlocks).length,
PcStatBlocks: Store.List(Store.PlayerCharacters).length,
PersistentCharacters: Store.List(Store.PersistentCharacters).length,
Spells: Store.List(Store.Spells).length
};
Metrics.TrackEvent("AppLoad", counts);
}
public static TrackEvent(name: string, data: EventData = {}): void {
if (!Store.Load(Store.User, "AllowTracking")) {
return;
}
console.log(`Event ${name}`);
if (data !== {}) {
console.table(data);
}
data.referrer = { url: document.referrer };
data.page = { url: document.URL };
data.localTime = new Date().toString();
$.ajax({
type: "POST",
url: `/recordEvent/${name}`,
data: JSON.stringify(data || {}),
contentType: "application/json"
});
}
}
| Add PersistentCharacter count to TrackLoad | Add PersistentCharacter count to TrackLoad
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -10,6 +10,7 @@
Encounters: Store.List(Store.SavedEncounters).length,
NpcStatBlocks: Store.List(Store.StatBlocks).length,
PcStatBlocks: Store.List(Store.PlayerCharacters).length,
+ PersistentCharacters: Store.List(Store.PersistentCharacters).length,
Spells: Store.List(Store.Spells).length
};
|
4374f4b114bf5b2d58a00b071684fbebe2e7acb5 | src/views/index.tsx | src/views/index.tsx | import * as React from 'react';
export class Home extends React.Component<any, any> {
render() {
return (
<h1>Index</h1>
);
}
}
| import * as React from 'react';
import {Counter} from '../components/counter';
export class Home extends React.Component<any, any> {
render() {
return (
<div>
<h1>Index</h1>
<Counter />
</div>
);
}
}
| Update view to include Counter | Update view to include Counter
| TypeScript | mit | melxx001/redux-starter,melxx001/redux-starter | ---
+++
@@ -1,9 +1,12 @@
import * as React from 'react';
-
+import {Counter} from '../components/counter';
export class Home extends React.Component<any, any> {
render() {
return (
- <h1>Index</h1>
+ <div>
+ <h1>Index</h1>
+ <Counter />
+ </div>
);
}
} |
7fcd62b5adcce4ba83d28eacc276a4c9595f6deb | ui/src/api/image.ts | ui/src/api/image.ts | import { getHeaders } from './utils';
export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const response = await fetch(getImageUrl(project, id, maxWidth, maxHeight), { headers: getHeaders(token) });
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
const getImageUrl = (project: string, id: string, maxWidth: number, maxHeight: number) =>
`/api/images/${project}/${id}${false /* if production */ ? '.jp2' : ''}/full%2F!${maxWidth},${maxHeight}%2F0%2Fdefault.jpg?q=hallo`;
| export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const imageUrl = getImageUrl(project, id, maxWidth, maxHeight, token);
const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
const getImageUrl = (project: string, id: string, maxWidth: number, maxHeight: number, token: string) =>
`/api/images/${project}/${id}${false /* if production */ ? '.jp2' : ''}/${token}/full/!${maxWidth},${maxHeight}/0/default.jpg`;
| Make links work in frontend | Make links work in frontend
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -1,16 +1,15 @@
-import { getHeaders } from './utils';
-
export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
- const response = await fetch(getImageUrl(project, id, maxWidth, maxHeight), { headers: getHeaders(token) });
+ const imageUrl = getImageUrl(project, id, maxWidth, maxHeight, token);
+ const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
-const getImageUrl = (project: string, id: string, maxWidth: number, maxHeight: number) =>
- `/api/images/${project}/${id}${false /* if production */ ? '.jp2' : ''}/full%2F!${maxWidth},${maxHeight}%2F0%2Fdefault.jpg?q=hallo`;
+const getImageUrl = (project: string, id: string, maxWidth: number, maxHeight: number, token: string) =>
+ `/api/images/${project}/${id}${false /* if production */ ? '.jp2' : ''}/${token}/full/!${maxWidth},${maxHeight}/0/default.jpg`; |
6b3d6c983b77eaaeb978b93ec12f0791cf8bfebf | src/lib/seeds/FactoryInterface.ts | src/lib/seeds/FactoryInterface.ts | import * as Faker from 'faker';
import { ObjectType } from 'typeorm';
import { EntityFactoryInterface } from './EntityFactoryInterface';
/**
* This interface is used to define new entity faker factories or to get such a
* entity faker factory to start seeding.
*/
export interface FactoryInterface {
/**
* Returns an EntityFactoryInterface
*/
get<Entity>(entityClass: ObjectType<Entity>): EntityFactoryInterface<Entity>;
/**
* Define an entity faker
*/
define<Entity>(entityClass: ObjectType<Entity>, fakerFunction: (faker: typeof Faker, args: any[]) => Entity): void;
}
| import * as Faker from 'faker';
import { ObjectType } from 'typeorm';
import { EntityFactoryInterface } from './EntityFactoryInterface';
/**
* This interface is used to define new entity faker factories or to get such a
* entity faker factory to start seeding.
*/
export interface FactoryInterface {
/**
* Returns an EntityFactoryInterface
*/
get<Entity>(entityClass: ObjectType<Entity>, args: any[]): EntityFactoryInterface<Entity>;
/**
* Define an entity faker
*/
define<Entity>(entityClass: ObjectType<Entity>, fakerFunction: (faker: typeof Faker, args: any[]) => Entity): void;
}
| Add missed parameter to the factory interface | Add missed parameter to the factory interface
| TypeScript | mit | w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate | ---
+++
@@ -9,7 +9,7 @@
/**
* Returns an EntityFactoryInterface
*/
- get<Entity>(entityClass: ObjectType<Entity>): EntityFactoryInterface<Entity>;
+ get<Entity>(entityClass: ObjectType<Entity>, args: any[]): EntityFactoryInterface<Entity>;
/**
* Define an entity faker
*/ |
acb50bc698508d46198440c85380493d7ddd6064 | src/lib/hashingFunctions.ts | src/lib/hashingFunctions.ts | const _addition = (a, b) => {
return a + b;
};
const _subtraction = (a, b) => {
return a - b;
};
const _multiplication = (a, b) => {
return a * b;
};
export const sum = array => {
return array.reduce(_addition, 0);
};
export const sumAndDiff = array => {
return array.reduce((prev, curr, index) => {
if (index % 2 === 0) {
return _addition(prev, curr);
} else {
return _subtraction(prev, curr);
}
}, 0);
};
export const product = array => {
return array.reduce(_multiplication, 1);
};
| const isEven: (num: number) => boolean = num => num % 2 === 0;
export const sum: (array: number[]) => number = arr =>
arr.reduce((a, b) => a + b, 0);
export const sumAndDiff: (array: number[]) => number = array =>
array.reduce(
(prev, curr, index) => (isEven(index) ? prev + curr : prev - curr),
0,
);
| Clean up our hashing functions | Clean up our hashing functions
Use arrow functions with implicit returns to clean up most of this basic
math.
Also removes some pretty basic add/subtract functions, along with an
unused product function.
| TypeScript | mit | adorableio/avatars-api | ---
+++
@@ -1,29 +1,10 @@
-const _addition = (a, b) => {
- return a + b;
-};
+const isEven: (num: number) => boolean = num => num % 2 === 0;
-const _subtraction = (a, b) => {
- return a - b;
-};
+export const sum: (array: number[]) => number = arr =>
+ arr.reduce((a, b) => a + b, 0);
-const _multiplication = (a, b) => {
- return a * b;
-};
-
-export const sum = array => {
- return array.reduce(_addition, 0);
-};
-
-export const sumAndDiff = array => {
- return array.reduce((prev, curr, index) => {
- if (index % 2 === 0) {
- return _addition(prev, curr);
- } else {
- return _subtraction(prev, curr);
- }
- }, 0);
-};
-
-export const product = array => {
- return array.reduce(_multiplication, 1);
-};
+export const sumAndDiff: (array: number[]) => number = array =>
+ array.reduce(
+ (prev, curr, index) => (isEven(index) ? prev + curr : prev - curr),
+ 0,
+ ); |
274a23a6e6860c7195b64629efda576237dded79 | packages/apollo-link-utilities/src/__tests__/index.ts | packages/apollo-link-utilities/src/__tests__/index.ts | import { Observable, ApolloLink, execute } from 'apollo-link';
import gql from 'graphql-tag';
import * as fetchMock from 'fetch-mock';
import {
parseAndCheckHttpResponse,
selectHttpOptionsAndBody,
selectURI,
serializeFetchBody,
} from '../index';
const sampleQuery = gql`
query SampleQuery {
stub {
id
}
}
`;
describe('Link Utilities', () => {
describe('Http utilities', () => {
describe('parseAndCheckResponse', () => {
it('throws a network error with a status code and result', () => {});
it('throws a server error on incorrect data', () => {});
it('is able to return a correct result and add it to the context', () => {});
});
describe('selectOptionsAndBody', () => {
it('throws a network error', () => {});
});
describe('selectURI', () => {
it('returns a passed in string', () => {});
it('returns a fallback of /graphql', () => {});
it('returns the result of a UriFunction', () => {});
});
describe('serializeBody', () => {
it('throws a parse error on an unparsable body', () => {});
it('returns a correctly parsed body', () => {});
});
});
});
| import { Observable, ApolloLink, execute } from 'apollo-link';
import gql from 'graphql-tag';
import * as fetchMock from 'fetch-mock';
import {
parseAndCheckHttpResponse,
selectHttpOptionsAndBody,
selectURI,
serializeFetchBody,
} from '../index';
const sampleQuery = gql`
query SampleQuery {
stub {
id
}
}
`;
describe('Link Utilities', () => {
describe('Http utilities', () => {
describe('parseAndCheckResponse', () => {
it('throws a network error with a status code and result', () => {});
it('throws a server error on incorrect data', () => {});
it('is able to return a correct result and add it to the context', () => {});
});
describe('selectOptionsAndBody', () => {
it('throws a network error', () => {});
});
describe('selectURI', () => {
it('returns a passed in string', () => {});
it('returns a fallback of /graphql', () => {});
it('returns the result of a UriFunction', () => {});
});
describe('serializeFetchBody', () => {
it('throws a parse error on an unparsable body', () => {
const b = {};
const a = { b };
(b as any).a = a;
expect(() => serializeFetchBody(b)).toThrow();
});
it('returns a correctly parsed body', () => {
const body = { no: 'thing' };
expect(serializeFetchBody(body)).toEqual('{"no":"thing"}');
});
});
});
});
| Add tests for serializeFetchBody utility fn | Add tests for serializeFetchBody utility fn
| TypeScript | mit | apollographql/apollo-link,apollographql/apollo-link | ---
+++
@@ -35,9 +35,20 @@
it('returns the result of a UriFunction', () => {});
});
- describe('serializeBody', () => {
- it('throws a parse error on an unparsable body', () => {});
- it('returns a correctly parsed body', () => {});
+ describe('serializeFetchBody', () => {
+ it('throws a parse error on an unparsable body', () => {
+ const b = {};
+ const a = { b };
+ (b as any).a = a;
+
+ expect(() => serializeFetchBody(b)).toThrow();
+ });
+
+ it('returns a correctly parsed body', () => {
+ const body = { no: 'thing' };
+
+ expect(serializeFetchBody(body)).toEqual('{"no":"thing"}');
+ });
});
});
}); |
12053a29dc699f14db4adc6c28eb86b4433d05b1 | src/js/View/Components/NotificationFilters/Index.tsx | src/js/View/Components/NotificationFilters/Index.tsx | import * as React from 'react';
import { createGitHubNotificationFilterSet } from 'Helpers/Models/GitHubNotificationFilterSet';
import NotificationFilterStringFilter from './NotificationFilterStringFilter';
import NotificationFilterRepositoryFilter from './NotificationFilterRepositoryFilter';
interface INotificationFiltersProps
{
notifications: IGitHubNotification[];
};
class NotificationFilters extends React.Component<INotificationFiltersProps, any>
{
render()
{
let filterSet = createGitHubNotificationFilterSet(this.props.notifications);
return (
<div className="soft-delta">
<div className="grid">
{filterSet.subjectTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.subjectTypes}
className="grid__item one-whole push-delta--bottom"
getTitle={() => 'Subjects'}
getFilterTitle={filter => filter.name} />
: undefined}
{filterSet.reasonTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.reasonTypes}
className="grid__item one-whole push-delta--bottom"
getTitle={() => 'Reasons'}
getFilterTitle={filter => filter.name} />
: undefined}
{filterSet.repositories.length > 0
? <NotificationFilterRepositoryFilter repositoryFilters={filterSet.repositories}
className="grid__item one-whole"
getTitle={() => 'Repositories'}
getFilterTitle={filter => filter.repository.fullName.toLowerCase()} />
: undefined}
</div>
</div>
);
}
};
export default NotificationFilters; | import * as React from 'react';
import {
getNotificationReasonPrettyName,
getNotificationSubjectPrettyName
} from 'Helpers/Services/GitHub';
import { createGitHubNotificationFilterSet } from 'Helpers/Models/GitHubNotificationFilterSet';
import NotificationFilterStringFilter from './NotificationFilterStringFilter';
import NotificationFilterRepositoryFilter from './NotificationFilterRepositoryFilter';
import { Scroll } from 'View/Ui/Index';
interface INotificationFiltersProps
{
notifications: IGitHubNotification[];
};
class NotificationFilters extends React.Component<INotificationFiltersProps, any>
{
render()
{
let filterSet = createGitHubNotificationFilterSet(this.props.notifications);
return (
<Scroll>
<div className="grid">
{filterSet.subjectTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.subjectTypes}
className="grid__item one-whole"
getTitle={() => 'Subjects'}
getFilterTitle={filter => getNotificationSubjectPrettyName(filter.name)} />
: undefined}
{filterSet.reasonTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.reasonTypes}
className="grid__item one-whole"
getTitle={() => 'Reasons'}
getFilterTitle={filter => getNotificationReasonPrettyName(filter.name)} />
: undefined}
{filterSet.repositories.length > 0
? <NotificationFilterRepositoryFilter repositoryFilters={filterSet.repositories}
className="grid__item one-whole"
getTitle={() => 'Repositories'}
getFilterTitle={filter => filter.repository.fullName.toLowerCase()} />
: undefined}
</div>
</Scroll>
);
}
};
export default NotificationFilters; | Format names and classes for filters | Format names and classes for filters
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -1,9 +1,15 @@
import * as React from 'react';
+import {
+ getNotificationReasonPrettyName,
+ getNotificationSubjectPrettyName
+} from 'Helpers/Services/GitHub';
import { createGitHubNotificationFilterSet } from 'Helpers/Models/GitHubNotificationFilterSet';
import NotificationFilterStringFilter from './NotificationFilterStringFilter';
import NotificationFilterRepositoryFilter from './NotificationFilterRepositoryFilter';
+
+import { Scroll } from 'View/Ui/Index';
interface INotificationFiltersProps
{
@@ -17,19 +23,19 @@
let filterSet = createGitHubNotificationFilterSet(this.props.notifications);
return (
- <div className="soft-delta">
+ <Scroll>
<div className="grid">
{filterSet.subjectTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.subjectTypes}
- className="grid__item one-whole push-delta--bottom"
+ className="grid__item one-whole"
getTitle={() => 'Subjects'}
- getFilterTitle={filter => filter.name} />
+ getFilterTitle={filter => getNotificationSubjectPrettyName(filter.name)} />
: undefined}
{filterSet.reasonTypes.length > 0
? <NotificationFilterStringFilter stringFilters={filterSet.reasonTypes}
- className="grid__item one-whole push-delta--bottom"
+ className="grid__item one-whole"
getTitle={() => 'Reasons'}
- getFilterTitle={filter => filter.name} />
+ getFilterTitle={filter => getNotificationReasonPrettyName(filter.name)} />
: undefined}
{filterSet.repositories.length > 0
? <NotificationFilterRepositoryFilter repositoryFilters={filterSet.repositories}
@@ -37,8 +43,8 @@
getTitle={() => 'Repositories'}
getFilterTitle={filter => filter.repository.fullName.toLowerCase()} />
: undefined}
- </div>
- </div>
+ </div>
+ </Scroll>
);
}
}; |
2ded93c2eceeede0237595745a2f4b54a63157e2 | analysis/tbchunter/src/metrics/growlCasts.ts | analysis/tbchunter/src/metrics/growlCasts.ts | import { AnyEvent } from 'parser/core/Events';
import metric from 'parser/core/metric';
import castCount from 'parser/shared/metrics/castCount';
import * as SPELLS from '../SPELLS_PET';
/**
* Returns the max amount of Kill Command casts considering the buff uptime.
* Does not account for fluctuating cooldowns.
*/
const growlCasts = (events: AnyEvent[], pets: Array<{ id: number }>) =>
pets.reduce((sum, pet) => {
const casts = castCount(events, pet.id);
return sum + casts[SPELLS.GROWL];
}, 0);
export default metric(growlCasts);
| import { AnyEvent } from 'parser/core/Events';
import metric from 'parser/core/metric';
import castCount from 'parser/shared/metrics/castCount';
import lowRankSpellsPet from '../lowRankSpellsPet';
import * as SPELLS from '../SPELLS_PET';
/**
* Returns the max amount of Kill Command casts considering the buff uptime.
* Does not account for fluctuating cooldowns.
*/
const growlCasts = (events: AnyEvent[], pets: Array<{ id: number }>) =>
pets.reduce((sum, pet) => {
const casts = castCount(events, pet.id);
return (
sum +
(casts[SPELLS.GROWL] || 0) +
lowRankSpellsPet[SPELLS.GROWL].reduce((sum, spellId) => sum + (casts[spellId] || 0), 0)
);
}, 0);
export default metric(growlCasts);
| Fix Growl suggestion did not consider lower rank Growls | tbchunter: Fix Growl suggestion did not consider lower rank Growls
| TypeScript | agpl-3.0 | sMteX/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,Juko8/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer | ---
+++
@@ -2,6 +2,7 @@
import metric from 'parser/core/metric';
import castCount from 'parser/shared/metrics/castCount';
+import lowRankSpellsPet from '../lowRankSpellsPet';
import * as SPELLS from '../SPELLS_PET';
/**
@@ -12,7 +13,11 @@
pets.reduce((sum, pet) => {
const casts = castCount(events, pet.id);
- return sum + casts[SPELLS.GROWL];
+ return (
+ sum +
+ (casts[SPELLS.GROWL] || 0) +
+ lowRankSpellsPet[SPELLS.GROWL].reduce((sum, spellId) => sum + (casts[spellId] || 0), 0)
+ );
}, 0);
export default metric(growlCasts); |
e5da9ab12177da0da33cc18fe20c9dbc14ac5b2a | src/components/ScoreBox.tsx | src/components/ScoreBox.tsx | import * as React from 'react';
export interface ScoreBoxProps {
score: number | null,
bid: number | null,
tricks: number | null
};
const border = '1px solid black';
export default class extends React.Component<ScoreBoxProps, {}> {
render() {
return (
<div style={{display: 'flex'}}>
<div style={{border: border, boxSizing: 'border-box', width: '50%'}}>{this.props.score}</div>
<div style={{boxSizing: 'border-box', width: '50%'}}>
<div style={{border: border}}>{this.props.bid}</div>
<div style={{border: border}}>{this.props.tricks}</div>
</div>
</div>
);
}
};
| import * as React from 'react';
export interface ScoreBoxProps {
score: number | null,
bid: number | undefined,
tricks: number | undefined
};
const border = '1px solid black';
export default class extends React.Component<ScoreBoxProps, {}> {
render() {
return (
<div style={{display: 'flex'}}>
<div style={{border: border, boxSizing: 'border-box', whiteSpace: 'pre-wrap', width: '50%'}}>{this.props.score !== null ? this.props.score : ' '}</div>
<div style={{boxSizing: 'border-box', width: '50%'}}>
<div style={{border: border, textAlign: 'center', whiteSpace: 'pre-wrap'}}>{this.props.bid !== undefined ? this.props.bid : ' '}</div>
<div style={{border: border, textAlign: 'center', whiteSpace: 'pre-wrap'}}>{this.props.tricks !== undefined ? this.props.tricks : ' '}</div>
</div>
</div>
);
}
};
| Fix styling with score box | Fix styling with score box
| TypeScript | mit | jeffcharles/wizard-scorekeeper,jeffcharles/wizard-scorekeeper,jeffcharles/wizard-scorekeeper,jeffcharles/wizard-scorekeeper | ---
+++
@@ -2,8 +2,8 @@
export interface ScoreBoxProps {
score: number | null,
- bid: number | null,
- tricks: number | null
+ bid: number | undefined,
+ tricks: number | undefined
};
const border = '1px solid black';
@@ -12,10 +12,10 @@
render() {
return (
<div style={{display: 'flex'}}>
- <div style={{border: border, boxSizing: 'border-box', width: '50%'}}>{this.props.score}</div>
+ <div style={{border: border, boxSizing: 'border-box', whiteSpace: 'pre-wrap', width: '50%'}}>{this.props.score !== null ? this.props.score : ' '}</div>
<div style={{boxSizing: 'border-box', width: '50%'}}>
- <div style={{border: border}}>{this.props.bid}</div>
- <div style={{border: border}}>{this.props.tricks}</div>
+ <div style={{border: border, textAlign: 'center', whiteSpace: 'pre-wrap'}}>{this.props.bid !== undefined ? this.props.bid : ' '}</div>
+ <div style={{border: border, textAlign: 'center', whiteSpace: 'pre-wrap'}}>{this.props.tricks !== undefined ? this.props.tricks : ' '}</div>
</div>
</div>
); |
1123057da3728015853bb8ac859e296575bc4ef7 | app/src/lib/is-git-on-path.ts | app/src/lib/is-git-on-path.ts | import { spawn } from 'child_process'
import * as Path from 'path'
export function isGitOnPath(): Promise<boolean> {
// Modern versions of macOS ship with a Git shim that guides you through
// the process of setting everything up. We trust this is available, so
// don't worry about looking for it here.
// I decide linux user have git too :)
if (__DARWIN__ || __LINUX__) {
return Promise.resolve(true)
}
// adapted from http://stackoverflow.com/a/34953561/1363815
return new Promise<boolean>((resolve, reject) => {
if (__WIN32__) {
const windowsRoot = process.env.SystemRoot || 'C:\\Windows'
const wherePath = Path.join(windowsRoot, 'System32', 'where.exe')
const cp = spawn(wherePath, ['git'])
cp.on('error', error => {
log.warn('Unable to spawn where.exe', error)
resolve(false)
})
// `where` will return 0 when the executable
// is found under PATH, or 1 if it cannot be found
cp.on('close', function(code) {
resolve(code === 0)
})
return
}
// in case you're on a non-Windows/non-macOS platform
resolve(false)
})
}
| import { spawn } from 'child_process'
import * as Path from 'path'
export function isGitOnPath(): Promise<boolean> {
// Modern versions of macOS ship with a Git shim that guides you through
// the process of setting everything up. We trust this is available, so
// don't worry about looking for it here.
if (__DARWIN__) {
return Promise.resolve(true)
}
// adapted from http://stackoverflow.com/a/34953561/1363815
if (__WIN32__) {
return new Promise<boolean>((resolve, reject) => {
const windowsRoot = process.env.SystemRoot || 'C:\\Windows'
const wherePath = Path.join(windowsRoot, 'System32', 'where.exe')
const cp = spawn(wherePath, ['git'])
cp.on('error', error => {
log.warn('Unable to spawn where.exe', error)
resolve(false)
})
// `where` will return 0 when the executable
// is found under PATH, or 1 if it cannot be found
cp.on('close', function(code) {
resolve(code === 0)
})
return
})
}
if (__LINUX__) {
return new Promise<boolean>((resolve, reject) => {
const process = spawn('which', ['git'])
// `which` will return 0 when the executable
// is found under PATH, or 1 if it cannot be found
process.on('close', function(code) {
resolve(code === 0)
})
})
}
return Promise.resolve(false)
}
| Check if git is found under PATH on Linux | Check if git is found under PATH on Linux
| TypeScript | mit | shiftkey/desktop,kactus-io/kactus,desktop/desktop,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,artivilla/desktop,shiftkey/desktop,say25/desktop,desktop/desktop | ---
+++
@@ -5,14 +5,13 @@
// Modern versions of macOS ship with a Git shim that guides you through
// the process of setting everything up. We trust this is available, so
// don't worry about looking for it here.
- // I decide linux user have git too :)
- if (__DARWIN__ || __LINUX__) {
+ if (__DARWIN__) {
return Promise.resolve(true)
}
// adapted from http://stackoverflow.com/a/34953561/1363815
- return new Promise<boolean>((resolve, reject) => {
- if (__WIN32__) {
+ if (__WIN32__) {
+ return new Promise<boolean>((resolve, reject) => {
const windowsRoot = process.env.SystemRoot || 'C:\\Windows'
const wherePath = Path.join(windowsRoot, 'System32', 'where.exe')
@@ -29,9 +28,20 @@
resolve(code === 0)
})
return
- }
+ })
+ }
- // in case you're on a non-Windows/non-macOS platform
- resolve(false)
- })
+ if (__LINUX__) {
+ return new Promise<boolean>((resolve, reject) => {
+ const process = spawn('which', ['git'])
+
+ // `which` will return 0 when the executable
+ // is found under PATH, or 1 if it cannot be found
+ process.on('close', function(code) {
+ resolve(code === 0)
+ })
+ })
+ }
+
+ return Promise.resolve(false)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.