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
aa718271ac86d003fac422bf60174f88cdca9969
ui/src/app/statusbar.ts
ui/src/app/statusbar.ts
declare function require(name: string): string; import * as nprogress from "nprogress"; export class Statusbar { public static Start(): void { Statusbar.loadStylesheet(); nprogress.configure({ minimum: 0.3, showSpinner: false, trickleSpeed: 200 }); nprogress.start(); } public static Inc(): void { nprogress.inc(0.6); } public static Done(): void { nprogress.done(); } private static loadStylesheet() { // tslint:disable:no-submodule-imports const css = require("nprogress/nprogress.css").toString(); const style: HTMLStyleElement = document.createElement("style"); style.type = "text/css"; style.innerHTML = css; document.head.appendChild(style); } }
declare function require(name: string): string; import * as nprogress from "nprogress"; interface IWindow extends Window { Statusbar: Statusbar; } export class Statusbar { public static Start(): void { Statusbar.Instance.Start(); } public static Inc(): void { Statusbar.Instance.Inc(); } public static Done(): void { Statusbar.Instance.Done(); } private static get Instance() { // attach this to the window object to make sure that there is really only one. const w = window as IWindow; return w.Statusbar || (w.Statusbar = new this()); } private Start(): void { this.loadStylesheet(); nprogress.configure({ minimum: 0.3, showSpinner: false, trickleSpeed: 200 }); nprogress.start(); } private loadStylesheet() { // tslint:disable:no-submodule-imports const css = require("nprogress/nprogress.css").toString(); const style: HTMLStyleElement = document.createElement("style"); style.type = "text/css"; style.innerHTML = css; document.head.appendChild(style); } private Inc(): void { nprogress.inc(0.6); } private Done(): void { nprogress.done(); } }
Make sure that there will really only be one NProgress instance.
Make sure that there will really only be one NProgress instance.
TypeScript
mit
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
--- +++ @@ -1,9 +1,31 @@ declare function require(name: string): string; import * as nprogress from "nprogress"; +interface IWindow extends Window { + Statusbar: Statusbar; +} + export class Statusbar { public static Start(): void { - Statusbar.loadStylesheet(); + Statusbar.Instance.Start(); + } + + public static Inc(): void { + Statusbar.Instance.Inc(); + } + + public static Done(): void { + Statusbar.Instance.Done(); + } + + private static get Instance() { + // attach this to the window object to make sure that there is really only one. + const w = window as IWindow; + return w.Statusbar || (w.Statusbar = new this()); + } + + private Start(): void { + this.loadStylesheet(); nprogress.configure({ minimum: 0.3, showSpinner: false, @@ -12,15 +34,7 @@ nprogress.start(); } - public static Inc(): void { - nprogress.inc(0.6); - } - - public static Done(): void { - nprogress.done(); - } - - private static loadStylesheet() { + private loadStylesheet() { // tslint:disable:no-submodule-imports const css = require("nprogress/nprogress.css").toString(); const style: HTMLStyleElement = document.createElement("style"); @@ -28,4 +42,12 @@ style.innerHTML = css; document.head.appendChild(style); } + + private Inc(): void { + nprogress.inc(0.6); + } + + private Done(): void { + nprogress.done(); + } }
8e4f2a99a32dfc362b27c883890f64e406ba5aae
test/e2e/helloworld.ts
test/e2e/helloworld.ts
import t = require("unittest/unittest"); function main(): void { t.test("bigifies text", function() { t.expect("hello".toUpperCase(), t.equals("HELLO")); }); }
import t = require("unittest/unittest"); class MyClass { field: string; MyClass(someVal: string) { this.field = someVal; } getField(): string { return this.field + " world"; } } function main(): void { t.test("bigifies text", function() { t.expect("hello".toUpperCase(), t.equals("HELLO")); }); t.test("handles classes", function() { var mc = new MyClass("hello"); t.expect(mc.field.toUpperCase(), t.equals("HELLO WORLD")); }); }
Add an end2end test using a class.
Add an end2end test using a class.
TypeScript
apache-2.0
yjbanov/ts2dart,alfonso-presa/ts2dart,vsavkin/ts2dart,jeffbcross/ts2dart,alfonso-presa/ts2dart,dart-archive/ts2dart,jacob314/ts2dart,hterkelsen/ts2dart,dart-archive/ts2dart,dart-archive/ts2dart,jeffbcross/ts2dart,vsavkin/ts2dart,vicb/ts2dart,caitp/ts2dart,yjbanov/ts2dart,caitp/ts2dart,hansl/ts2dart,hansl/ts2dart,jteplitz602/ts2dart,jteplitz602/ts2dart,jacob314/ts2dart,vicb/ts2dart,hterkelsen/ts2dart
--- +++ @@ -1,5 +1,17 @@ import t = require("unittest/unittest"); + +class MyClass { + field: string; + + MyClass(someVal: string) { this.field = someVal; } + + getField(): string { return this.field + " world"; } +} function main(): void { t.test("bigifies text", function() { t.expect("hello".toUpperCase(), t.equals("HELLO")); }); + t.test("handles classes", function() { + var mc = new MyClass("hello"); + t.expect(mc.field.toUpperCase(), t.equals("HELLO WORLD")); + }); }
4611d9c79704cac18108996c85c9a88d38c122c3
packages/db/src/db.ts
packages/db/src/db.ts
import { logger } from "@truffle/db/logger"; const debug = logger("db:db"); import gql from "graphql-tag"; import { DocumentNode, ExecutionResult, execute } from "graphql"; import type TruffleConfig from "@truffle/config"; import { Db } from "./meta"; export { Db }; // rather than force src/index from touching meta import { schema } from "./schema"; import { Workspace, attach } from "./workspace"; export const connect = (config: TruffleConfig): Db => { const workspace: Workspace = attach({ workingDirectory: config.working_directory, adapter: (config.db || {}).adapter }); return { async execute( request: DocumentNode | string, variables: any = {} ): Promise<ExecutionResult> { const response = await execute( schema, typeof request === "string" ? gql` ${request} ` : request, null, { workspace }, variables ); if (response.errors) { debug("errors %o", response.errors); } return response; } }; };
import { logger } from "@truffle/db/logger"; const debug = logger("db:db"); import gql from "graphql-tag"; import { print } from "graphql/language/printer"; import { DocumentNode, ExecutionResult, execute } from "graphql"; import type TruffleConfig from "@truffle/config"; import { Db } from "./meta"; export { Db }; // rather than force src/index from touching meta import { schema } from "./schema"; import { Workspace, attach } from "./workspace"; export const connect = (config: TruffleConfig): Db => { const workspace: Workspace = attach({ workingDirectory: config.working_directory, adapter: (config.db || {}).adapter }); return { async execute( request: DocumentNode | string, variables: any = {} ): Promise<ExecutionResult> { const document = typeof request === "string" ? gql` ${request} ` : request; const response = await execute( schema, document, null, { workspace }, variables ); if (response.errors) { debug("request %s", print(document)); debug("errors %O", response.errors); } return response; } }; };
Add debug logging for failed GraphQL requests
Add debug logging for failed GraphQL requests
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -2,6 +2,7 @@ const debug = logger("db:db"); import gql from "graphql-tag"; +import { print } from "graphql/language/printer"; import { DocumentNode, ExecutionResult, execute } from "graphql"; import type TruffleConfig from "@truffle/config"; @@ -23,20 +24,23 @@ request: DocumentNode | string, variables: any = {} ): Promise<ExecutionResult> { - const response = await execute( - schema, + const document = typeof request === "string" ? gql` ${request} ` - : request, + : request; + const response = await execute( + schema, + document, null, { workspace }, variables ); if (response.errors) { - debug("errors %o", response.errors); + debug("request %s", print(document)); + debug("errors %O", response.errors); } return response;
4a2fcb50d8a8551a910d9524cbf2ed4bba35042f
src/ChatBubble/index.tsx
src/ChatBubble/index.tsx
import * as React from 'react'; import ChatBubbleProps from './interface'; import styles from './styles'; const defaultBubbleStyles = { userBubble: {}, chatbubble: {}, text: {}, }; export default class ChatBubble extends React.Component { props; constructor(props: ChatBubbleProps) { super(props); } public render() { const { bubblesCentered } = this.props; let { bubbleStyles } = this.props; bubbleStyles = bubbleStyles || defaultBubbleStyles; const { userBubble, chatbubble, text } = bubbleStyles; // message.id 0 is reserved for blue const chatBubbleStyles = this.props.message.id === 0 ? { ...styles.chatbubble, ...bubblesCentered ? {} : styles.chatbubbleOrientationNormal, ...chatbubble, ...userBubble, } : { ...styles.chatbubble, ...styles.recipientChatbubble, ...bubblesCentered ? {} : styles.recipientChatbubbleOrientationNormal, ...chatbubble, ...userBubble, }; return ( <div style={{ ...styles.chatbubbleWrapper, }} > <div style={chatBubbleStyles}> <p style={{ ...styles.p, ...text }}>{this.props.message.message}</p> </div> </div> ); } } export { ChatBubbleProps };
import * as React from 'react'; import ChatBubbleProps from './interface'; import styles from './styles'; const defaultBubbleStyles = { userBubble: {}, chatbubble: {}, text: {}, }; export default class ChatBubble extends React.Component { props; constructor(props: ChatBubbleProps) { super(props); } public render() { const { bubblesCentered } = this.props; let { bubbleStyles } = this.props; bubbleStyles = bubbleStyles || defaultBubbleStyles; const { userBubble, chatbubble, text } = bubbleStyles; // message.id 0 is reserved for blue const chatBubbleStyles = this.props.message.id === 0 ? { ...styles.chatbubble, ...bubblesCentered ? {} : styles.chatbubbleOrientationNormal, ...chatbubble, ...userBubble, } : { ...styles.chatbubble, ...styles.recipientChatbubble, ...bubblesCentered ? {} : styles.recipientChatbubbleOrientationNormal, ...userBubble, ...chatbubble, }; return ( <div style={{ ...styles.chatbubbleWrapper, }} > <div style={chatBubbleStyles}> <p style={{ ...styles.p, ...text }}>{this.props.message.message}</p> </div> </div> ); } } export { ChatBubbleProps };
Make user bubble and chat bubble styles apply independently.
Make user bubble and chat bubble styles apply independently. Currently, when I use 'bubbleStyles', the useBubble style is getting applied to both userBubble and chatbubble. This commit fixes this issue and applies the right styles to the right bubbles.
TypeScript
mit
brandonmowat/react-chat-ui,brandonmowat/react-chat-ui
--- +++ @@ -36,8 +36,8 @@ ...bubblesCentered ? {} : styles.recipientChatbubbleOrientationNormal, + ...userBubble, ...chatbubble, - ...userBubble, }; return (
c10fa9989604580d0f2be07015f5df5ebe5afce8
collector/src/options.ts
collector/src/options.ts
import * as yargs from 'yargs' interface Options extends yargs.Arguments { count: number } const allOptions = { count: { alias: 'c', default: 5, describe: 'number of sources to poll', number: true } } const parseArgs = (args: string[]): Options => { return yargs .options(allOptions) .parse(args) as Options } export { allOptions, Options, parseArgs as parseArguments }
import * as yargs from 'yargs' interface Options extends yargs.Arguments { count: number } const allOptions = { count: { alias: 'c', default: 5, describe: 'number of sources to poll', number: true } } const parseArgs = (args: string[]): Options => { return yargs .options(allOptions) .help() .version() .parse(args) as Options } export { allOptions, Options, parseArgs as parseArguments }
Add --help and --version flags.
feat(help): Add --help and --version flags.
TypeScript
apache-2.0
eheikes/oscar,eheikes/oscar,eheikes/oscar,eheikes/oscar
--- +++ @@ -16,6 +16,8 @@ const parseArgs = (args: string[]): Options => { return yargs .options(allOptions) + .help() + .version() .parse(args) as Options }
11de346a2ef4e86502c88df074cb9ba1e6a0022a
webapp/source/plugins-for-local-libre-or-standard-services/rss/rss-plugin.ts
webapp/source/plugins-for-local-libre-or-standard-services/rss/rss-plugin.ts
import m = require("mithril"); import testData = require("./rssFeedExampleFromFSF"); export function initialize() { console.log("test data:", testData) console.log("RSS plugin initialized"); } export function display() { return m("div.rssPlugin", ["RSS feed reader plugin", m("pre", JSON.stringify(testData, null, 2))]); }
import m = require("mithril"); import testData = require("./rssFeedExampleFromFSF"); export function initialize() { console.log("test data:", testData) console.log("RSS plugin initialized"); } function displayItem(item) { var title = item.title; var link = item.link; var description = item.desc; var timestamp = item.date; return m("div.item", [ m("br") m("strong", title), m("br") description, " ", m("a", { href: link }, "More ..."), m("br"), ]); } function displayRSS() { return m("div.feed", [ testData.items.map(displayItem); ]); } export function display() { return m("div.rssPlugin", [ m("hr"), m("strong", "RSS feed reader plugin"), //m("pre", JSON.stringify(testData, null, 2)) displayRSS() ]); }
Improve display of test RSS data
Improve display of test RSS data
TypeScript
mpl-2.0
pdfernhout/Twirlip2,pdfernhout/Twirlip2,pdfernhout/Twirlip2
--- +++ @@ -7,6 +7,34 @@ console.log("RSS plugin initialized"); } +function displayItem(item) { + var title = item.title; + var link = item.link; + var description = item.desc; + var timestamp = item.date; + + return m("div.item", [ + m("br") + m("strong", title), + m("br") + description, + " ", + m("a", { href: link }, "More ..."), + m("br"), + ]); +} + +function displayRSS() { + return m("div.feed", [ + testData.items.map(displayItem); + ]); +} + export function display() { - return m("div.rssPlugin", ["RSS feed reader plugin", m("pre", JSON.stringify(testData, null, 2))]); + return m("div.rssPlugin", [ + m("hr"), + m("strong", "RSS feed reader plugin"), + //m("pre", JSON.stringify(testData, null, 2)) + displayRSS() + ]); }
a76ac48528786ec207478ffa7cab07bd742124e2
lib/utils/mapbox-search.ts
lib/utils/mapbox-search.ts
import throttle from 'lodash/throttle' import get from 'lodash/get' import {stringify} from 'querystring' import {MB_TOKEN} from 'lib/constants' const DELAY_MS = 400 const BASE_URL = 'https://api.mapbox.com' const PATH = '/geocoding/v5/mapbox.places' const getURL = (s: string, q: string) => `${BASE_URL}${PATH}/${encodeURIComponent(s)}.json?${q}` /** * Mapbox adds properties to a normal featuer. * https://docs.mapbox.com/api/search/#geocoding-response-object */ export interface MapboxFeature extends GeoJSON.Feature { center: [number, number] // lon/lat } type SearchCallback = (features: MapboxFeature[]) => void /** * Using callbacks in order to handle throttling appropriately. */ export default throttle(function mapboxSearch( s: string, options = {}, cb: SearchCallback ) { if (get(s, 'length') < 3) return cb([]) const querystring = stringify({ access_token: MB_TOKEN, autocomplete: false, ...options }) fetch(getURL(s, querystring)) .then((r) => r.json()) .then((json) => cb(json.features)) .catch((e) => { console.error(e) cb([]) }) }, DELAY_MS)
import throttle from 'lodash/throttle' import get from 'lodash/get' import {stringify} from 'querystring' import {MB_TOKEN} from 'lib/constants' const DELAY_MS = 400 const BASE_URL = 'https://api.mapbox.com' const PATH = '/geocoding/v5/mapbox.places' const getURL = (s: string, q: string) => `${BASE_URL}${PATH}/${encodeURIComponent(s)}.json?${q}` /** * Mapbox adds properties to a normal featuer. * https://docs.mapbox.com/api/search/#geocoding-response-object */ export interface MapboxFeature extends GeoJSON.Feature { center: [number, number] // lon/lat } type SearchCallback = (features: MapboxFeature[]) => void /** * Using callbacks in order to handle throttling appropriately. */ export default throttle(function mapboxSearch( s: string, options = {}, cb: SearchCallback ) { if (get(s, 'length') < 3) return cb([]) const querystring = stringify({ access_token: MB_TOKEN, autocomplete: false, // All types except `country` and `poi`: https://docs.mapbox.com/api/search/geocoding/#data-types types: 'region,district,locality,postcode,place,neighborhood,address', ...options }) fetch(getURL(s, querystring)) .then((r) => r.json()) .then((json) => cb(json.features)) .catch((e) => { console.error(e) cb([]) }) }, DELAY_MS)
Remove `country` and `poi` from search
Remove `country` and `poi` from search
TypeScript
mit
conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui
--- +++ @@ -33,6 +33,8 @@ const querystring = stringify({ access_token: MB_TOKEN, autocomplete: false, + // All types except `country` and `poi`: https://docs.mapbox.com/api/search/geocoding/#data-types + types: 'region,district,locality,postcode,place,neighborhood,address', ...options })
bd1b5e9607662cf74a7b387d9b27784264ea287e
dium/src/components/text-input.ts
dium/src/components/text-input.ts
import * as Finder from "../finder"; import * as Filters from "../filters"; export const enum TextInputSizes { DEFAULT = "default", MINI = "mini" } interface TextInputProps { type?: string; value?: string; name?: string; placeholder?: string; error?: any; minLength?: any; maxLength?: any; onChange: (value: string) => void; className?: string; inputClassName?: string; inputPrefix?: any; disabled?: boolean; size?: string; editable?: boolean; autoFocus?: boolean; inputRef?: React.Ref<HTMLInputElement>; prefixElement?: any; focusProps?: any; titleId?: any; "aria-labelledby"?: any; } export interface TextInput extends React.ComponentClass<TextInputProps, any> { Sizes: typeof TextInputSizes; contextType: React.Context<any>; defaultProps: { name: ""; size: "default"; disabled: false; type: "text"; placeholder: ""; autoFocus: false; maxLength: 999; }; } interface TextInputModule { TextInput: TextInput; TextInputError: React.FunctionComponent<any>; } export const {TextInput, TextInputError}: TextInputModule = /* @__PURE__ */ Finder.demangle({ TextInput: (target) => target.defaultProps?.type === "text", TextInputError: Filters.bySource(".error", "text-danger") } as const, ["TextInput"]);
import * as Finder from "../finder"; import * as Filters from "../filters"; export const enum TextInputSizes { DEFAULT = "default", MINI = "mini" } interface TextInputProps { type?: string; value?: string; name?: string; placeholder?: string; error?: any; minLength?: any; maxLength?: any; onChange: (value: string) => void; className?: string; inputClassName?: string; inputPrefix?: any; disabled?: boolean; size?: string; editable?: boolean; autoFocus?: boolean; inputRef?: React.Ref<HTMLInputElement>; prefixElement?: any; focusProps?: any; titleId?: any; "aria-labelledby"?: any; } export interface TextInput extends React.ComponentClass<TextInputProps, any> { Sizes: typeof TextInputSizes; contextType: React.Context<any>; defaultProps: { name: ""; size: "default"; disabled: false; type: "text"; placeholder: ""; autoFocus: false; maxLength: 999; }; } interface TextInputModule { TextInput: TextInput; TextInputError: React.FunctionComponent<any>; } export const {TextInput, TextInputError}: TextInputModule = /* @__PURE__ */ Finder.demangle({ TextInput: (target) => target?.defaultProps?.type === "text", TextInputError: Filters.bySource(".error", "text-danger") } as const, ["TextInput"]);
Fix text input filter error
Fix text input filter error
TypeScript
mit
Zerthox/BetterDiscord-Plugins,Zerthox/BetterDiscord-Plugins
--- +++ @@ -49,6 +49,6 @@ } export const {TextInput, TextInputError}: TextInputModule = /* @__PURE__ */ Finder.demangle({ - TextInput: (target) => target.defaultProps?.type === "text", + TextInput: (target) => target?.defaultProps?.type === "text", TextInputError: Filters.bySource(".error", "text-danger") } as const, ["TextInput"]);
83901755106b45c9e244e02f118dacaf184b6ccf
src/app/dashboard/shared/services/dashboard.service.ts
src/app/dashboard/shared/services/dashboard.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { Observable } from 'rxjs/Observable'; import { NgRedux } from '@angular-redux/store'; import { SELECT_USER, IAppState } from '../../../store'; @Injectable() export class DashboardService { constructor(private http: HttpClient, private ngRedux: NgRedux<IAppState>) { } getAllUserPosts(id: number): Observable<any>{ return this.http.get(`/api/users/${id}/allposts`) .catch(error => Observable.throw(error)); } }
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { Observable } from 'rxjs/Observable'; import { NgRedux } from '@angular-redux/store'; import { SELECT_USER, IAppState } from '../../../store'; @Injectable() export class DashboardService { constructor(private http: HttpClient, private ngRedux: NgRedux<IAppState>) { } getAllUserPosts(id: number): Observable<any>{ const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'); return this.http.get(`/api/users/${id}/allposts`, { headers }) .catch(error => Observable.throw(error)); } }
Add headers to get request
Add headers to get request
TypeScript
mit
zackluckyf/advanced-social-network,zackluckyf/advanced-social-network,zackluckyf/advanced-social-network
--- +++ @@ -13,9 +13,9 @@ constructor(private http: HttpClient, private ngRedux: NgRedux<IAppState>) { } getAllUserPosts(id: number): Observable<any>{ - return this.http.get(`/api/users/${id}/allposts`) + const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'); + return this.http.get(`/api/users/${id}/allposts`, { headers }) .catch(error => Observable.throw(error)); } - }
f16808620fd345dae127bd3011ccfa2393d34241
app/src/lib/parse-url.ts
app/src/lib/parse-url.ts
import * as URL from 'url' interface IURLAction<T> { name: string readonly args: T } export interface IOAuthActionArgs { readonly code: string } export interface IOAuthAction extends IURLAction<IOAuthActionArgs> { readonly name: 'oauth' readonly args: IOAuthActionArgs } export interface IOpenRepositoryAction extends IURLAction<string> { readonly name: 'open-repository' readonly args: string } export interface IUnknownAction extends IURLAction<{}> { readonly name: 'unknown' readonly args: {} } export type URLActionType = IOAuthAction | IOpenRepositoryAction | IUnknownAction export default function parseURL(url: string): URLActionType { const parsedURL = URL.parse(url, true) const hostname = parsedURL.hostname const unknown: IUnknownAction = { name: 'unknown', args: {} } if (!hostname) { return unknown } const actionName = hostname.toLowerCase() if (actionName === 'oauth') { return { name: 'oauth', args: { code: parsedURL.query.code } } } else if (actionName === 'openrepo') { // The `path` will be: /https://github.com/user/repo, so we need to take a // substring from the first character on. return { name: 'open-repository', args: parsedURL.path!.substr(1) } } else { return unknown } }
import * as URL from 'url' interface IURLAction<T> { name: string readonly args: T } export interface IOAuthActionArgs { readonly code: string } export interface IOAuthAction extends IURLAction<IOAuthActionArgs> { readonly name: 'oauth' readonly args: IOAuthActionArgs } export interface IOpenRepositoryAction extends IURLAction<string> { readonly name: 'open-repository' readonly args: string } export interface IUnknownAction extends IURLAction<{}> { readonly name: 'unknown' readonly args: {} } export type URLActionType = IOAuthAction | IOpenRepositoryAction | IUnknownAction export default function parseURL(url: string): URLActionType { const parsedURL = URL.parse(url, true) const hostname = parsedURL.hostname const unknown: IUnknownAction = { name: 'unknown', args: {} } if (!hostname) { return unknown } const actionName = hostname.toLowerCase() if (actionName === 'oauth') { return { name: 'oauth', args: { code: parsedURL.query.code } } } else if (actionName === 'openrepo') { // The `path` will be: /https://github.com/user/repo, so we need to take a // substring from the first character on. return { name: 'open-repository', args: `${parsedURL.path!.substr(1)}.git` } } else { return unknown } }
Append the trailing git extension
Append the trailing git extension
TypeScript
mit
hjobrien/desktop,BugTesterTest/desktops,artivilla/desktop,j-f1/forked-desktop,BugTesterTest/desktops,hjobrien/desktop,desktop/desktop,artivilla/desktop,desktop/desktop,j-f1/forked-desktop,hjobrien/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,BugTesterTest/desktops,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,gengjiawen/desktop,say25/desktop,hjobrien/desktop,say25/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,BugTesterTest/desktops,gengjiawen/desktop,artivilla/desktop,gengjiawen/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus
--- +++ @@ -38,7 +38,7 @@ } else if (actionName === 'openrepo') { // The `path` will be: /https://github.com/user/repo, so we need to take a // substring from the first character on. - return { name: 'open-repository', args: parsedURL.path!.substr(1) } + return { name: 'open-repository', args: `${parsedURL.path!.substr(1)}.git` } } else { return unknown }
a0c618826752293c837dac6e702cc4a913a35ccb
client/src/environments/environment.prod.ts
client/src/environments/environment.prod.ts
export const environment = { production: true, RECAPTCHA_SITE_KEY: process.env.RECAPTCHA_SITE_KEY, // For kfet-insa.fr domains VERSION: require('../../../package.json').version, JWT_DAY_EXP_LONG: 30, JWT_DAY_EXP: 1, };
export const environment = { production: true, RECAPTCHA_SITE_KEY: '6Ldbh14UAAAAAC_hGGi0xaHS5Om-Qln1UQV_lW-7', // For kfet-insa.fr domains VERSION: require('../../../package.json').version, JWT_DAY_EXP_LONG: 30, JWT_DAY_EXP: 1, };
Revert angular env variables (Thx angular!)
Revert angular env variables (Thx angular!)
TypeScript
apache-2.0
K-Fet/K-App,K-Fet/K-App,K-Fet/K-App,K-Fet/K-App
--- +++ @@ -1,6 +1,6 @@ export const environment = { production: true, - RECAPTCHA_SITE_KEY: process.env.RECAPTCHA_SITE_KEY, // For kfet-insa.fr domains + RECAPTCHA_SITE_KEY: '6Ldbh14UAAAAAC_hGGi0xaHS5Om-Qln1UQV_lW-7', // For kfet-insa.fr domains VERSION: require('../../../package.json').version, JWT_DAY_EXP_LONG: 30, JWT_DAY_EXP: 1,
5e1dc59042349bb71a25b2e9ac9c969200dcb7b4
app/modal-save-map/modal-save-map.component.ts
app/modal-save-map/modal-save-map.component.ts
import { Component, Input, Output, EventEmitter } from "@angular/core"; import { MapService } from "../core/map.service"; import { OptionMap } from "../core/map"; @Component({ selector: 'aba-modal-save-map', templateUrl: 'modal-save-map.component.html', styleUrls: ['modal-save-map.component.css'] }) export class ModalSaveMapComponent { @Input('visible') visible: boolean = false; @Output() onMapSubmit: EventEmitter<any> = new EventEmitter(); private title: string = ""; constructor(private mapService: MapService) { } private isVisible(): boolean { return this.visible; } public open(): void { this.visible = true; } public close(): void{ this.visible = false; } private onSubmit(): void { this.close(); this.onMapSubmit.emit( {title: this.title}); } }
import { Component, Input, Output, EventEmitter } from "@angular/core"; @Component({ selector: 'aba-modal-save-map', templateUrl: 'modal-save-map.component.html', styleUrls: ['modal-save-map.component.css'] }) export class ModalSaveMapComponent { @Input('visible') visible: boolean = false; @Output() onMapSubmit: EventEmitter<any> = new EventEmitter(); private title: string = ""; constructor() { } private isVisible(): boolean { return this.visible; } public open(): void { this.visible = true; } public close(): void{ this.visible = false; } private onSubmit(): void { this.close(); this.onMapSubmit.emit( {title: this.title} ); } }
Refresh after saving a map
Refresh after saving a map close #59
TypeScript
mit
ABAPlan/abaplan-core,ABAPlan/abaplan-core,ABAPlan/abaplan-core
--- +++ @@ -1,6 +1,4 @@ import { Component, Input, Output, EventEmitter } from "@angular/core"; -import { MapService } from "../core/map.service"; -import { OptionMap } from "../core/map"; @Component({ selector: 'aba-modal-save-map', @@ -12,10 +10,9 @@ @Input('visible') visible: boolean = false; @Output() onMapSubmit: EventEmitter<any> = new EventEmitter(); - private title: string = ""; - constructor(private mapService: MapService) { + constructor() { } private isVisible(): boolean { @@ -31,7 +28,7 @@ private onSubmit(): void { this.close(); - this.onMapSubmit.emit( {title: this.title}); + this.onMapSubmit.emit( {title: this.title} ); } }
2f55b45147e37f75a2bb9d7ddc325631ff6549cb
src/model/optional-range.ts
src/model/optional-range.ts
export interface OptionalRange { value: string; endValue?: string; } export module OptionalRange { export const VALUE = 'value'; export const ENDVALUE = 'endValue'; export function isValid(optionalRange: OptionalRange): boolean { const keys = Object.keys(optionalRange); if (keys.length !== 1 && keys.length !== 2) return false; if (keys.length === 1 && keys[0] !== VALUE) return false; if (keys.length === 2 && (typeof optionalRange[VALUE] !== typeof optionalRange[ENDVALUE])) return false; return true; } }
export interface OptionalRange { value: string; endValue?: string; } export module OptionalRange { export const VALUE = 'value'; export const ENDVALUE = 'endValue'; export function isValid(optionalRange: OptionalRange): boolean { const keys = Object.keys(optionalRange); if (keys.length !== 1 && keys.length !== 2) return false; if (keys.length === 1 && keys[0] !== VALUE) return false; if (keys.length === 2 && (typeof optionalRange[VALUE] !== typeof optionalRange[ENDVALUE])) return false; return true; } export function generateLabel(optionalRange: OptionalRange, getTranslation: (key: string) => string): string { return optionalRange.endValue ? getTranslation('from') + optionalRange.value + getTranslation('to') + optionalRange.endValue : optionalRange.value; } }
Add method generateLabel to OptionalRange
Add method generateLabel to OptionalRange
TypeScript
apache-2.0
dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2
--- +++ @@ -19,4 +19,13 @@ if (keys.length === 2 && (typeof optionalRange[VALUE] !== typeof optionalRange[ENDVALUE])) return false; return true; } + + + export function generateLabel(optionalRange: OptionalRange, + getTranslation: (key: string) => string): string { + + return optionalRange.endValue + ? getTranslation('from') + optionalRange.value + getTranslation('to') + optionalRange.endValue + : optionalRange.value; + } }
4b3361a7b9b2adf5ccbc2c0774c30a0be92f417f
src/vs/editor/contrib/parameterHints/provideSignatureHelp.ts
src/vs/editor/contrib/parameterHints/provideSignatureHelp.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 { TPromise } from 'vs/base/common/winjs.base'; import { onUnexpectedExternalError } from 'vs/base/common/errors'; import { ITextModel } from 'vs/editor/common/model'; import { registerDefaultLanguageCommand } from 'vs/editor/browser/editorExtensions'; import { SignatureHelp, SignatureHelpProviderRegistry } from 'vs/editor/common/modes'; import { asWinJsPromise, sequence } from 'vs/base/common/async'; import { Position } from 'vs/editor/common/core/position'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const Context = { Visible: new RawContextKey<boolean>('parameterHintsVisible', false), MultipleSignatures: new RawContextKey<boolean>('parameterHintsMultipleSignatures', false), }; export function provideSignatureHelp(model: ITextModel, position: Position): TPromise<SignatureHelp> { const supports = SignatureHelpProviderRegistry.ordered(model); let result: SignatureHelp; return sequence(supports.map(support => () => { if (result) { // stop when there is a result return undefined; } return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)).then(thisResult => { result = thisResult; }, onUnexpectedExternalError); })).then(() => result); } registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { asWinJsPromise, first } from 'vs/base/common/async'; import { onUnexpectedExternalError } from 'vs/base/common/errors'; import { TPromise } from 'vs/base/common/winjs.base'; import { registerDefaultLanguageCommand } from 'vs/editor/browser/editorExtensions'; import { Position } from 'vs/editor/common/core/position'; import { ITextModel } from 'vs/editor/common/model'; import { SignatureHelp, SignatureHelpProviderRegistry } from 'vs/editor/common/modes'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const Context = { Visible: new RawContextKey<boolean>('parameterHintsVisible', false), MultipleSignatures: new RawContextKey<boolean>('parameterHintsMultipleSignatures', false), }; export function provideSignatureHelp(model: ITextModel, position: Position): TPromise<SignatureHelp> { const supports = SignatureHelpProviderRegistry.ordered(model); return first(supports.map(support => () => { return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)) .then(undefined, onUnexpectedExternalError); })); } registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
Use first for picking first sig help result
Use first for picking first sig help result
TypeScript
mit
eamodio/vscode,joaomoreno/vscode,rishii7/vscode,cleidigh/vscode,eamodio/vscode,the-ress/vscode,Microsoft/vscode,hoovercj/vscode,microlv/vscode,landonepps/vscode,0xmohit/vscode,cleidigh/vscode,the-ress/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,cleidigh/vscode,0xmohit/vscode,Microsoft/vscode,eamodio/vscode,microsoft/vscode,microsoft/vscode,microlv/vscode,DustinCampbell/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,landonepps/vscode,Microsoft/vscode,landonepps/vscode,rishii7/vscode,mjbvz/vscode,rishii7/vscode,Microsoft/vscode,landonepps/vscode,cleidigh/vscode,cleidigh/vscode,rishii7/vscode,DustinCampbell/vscode,microlv/vscode,landonepps/vscode,hoovercj/vscode,cleidigh/vscode,landonepps/vscode,0xmohit/vscode,landonepps/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,joaomoreno/vscode,rishii7/vscode,cleidigh/vscode,DustinCampbell/vscode,microsoft/vscode,eamodio/vscode,microlv/vscode,microsoft/vscode,the-ress/vscode,rishii7/vscode,mjbvz/vscode,joaomoreno/vscode,DustinCampbell/vscode,the-ress/vscode,the-ress/vscode,mjbvz/vscode,Microsoft/vscode,mjbvz/vscode,landonepps/vscode,cleidigh/vscode,the-ress/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,mjbvz/vscode,microsoft/vscode,joaomoreno/vscode,the-ress/vscode,DustinCampbell/vscode,microlv/vscode,the-ress/vscode,eamodio/vscode,landonepps/vscode,the-ress/vscode,joaomoreno/vscode,eamodio/vscode,microlv/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,hoovercj/vscode,rishii7/vscode,0xmohit/vscode,microsoft/vscode,cleidigh/vscode,DustinCampbell/vscode,microlv/vscode,eamodio/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,joaomoreno/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,0xmohit/vscode,joaomoreno/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,0xmohit/vscode,eamodio/vscode,rishii7/vscode,microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,hoovercj/vscode,mjbvz/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,rishii7/vscode,joaomoreno/vscode,eamodio/vscode,DustinCampbell/vscode,the-ress/vscode,landonepps/vscode,Microsoft/vscode,Microsoft/vscode,cleidigh/vscode,microlv/vscode,cleidigh/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,0xmohit/vscode,landonepps/vscode,DustinCampbell/vscode,Microsoft/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Microsoft/vscode,microlv/vscode,0xmohit/vscode,joaomoreno/vscode,DustinCampbell/vscode,hoovercj/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,cleidigh/vscode,0xmohit/vscode,hoovercj/vscode,mjbvz/vscode,eamodio/vscode,mjbvz/vscode,Microsoft/vscode,cleidigh/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,eamodio/vscode,microlv/vscode,landonepps/vscode,rishii7/vscode,the-ress/vscode,hoovercj/vscode,landonepps/vscode,eamodio/vscode,microlv/vscode,the-ress/vscode,mjbvz/vscode,0xmohit/vscode,landonepps/vscode,microsoft/vscode,joaomoreno/vscode,eamodio/vscode,DustinCampbell/vscode,rishii7/vscode,the-ress/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,hoovercj/vscode,microsoft/vscode,the-ress/vscode,cleidigh/vscode,mjbvz/vscode,microsoft/vscode,0xmohit/vscode,hoovercj/vscode,landonepps/vscode,landonepps/vscode,DustinCampbell/vscode,microsoft/vscode,microlv/vscode,microlv/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,0xmohit/vscode,0xmohit/vscode,Microsoft/vscode,DustinCampbell/vscode,Microsoft/vscode,eamodio/vscode,mjbvz/vscode,mjbvz/vscode,cleidigh/vscode,DustinCampbell/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,mjbvz/vscode,mjbvz/vscode,hoovercj/vscode,mjbvz/vscode,rishii7/vscode,microsoft/vscode,DustinCampbell/vscode,hoovercj/vscode,mjbvz/vscode,microlv/vscode,microsoft/vscode,hoovercj/vscode,DustinCampbell/vscode,microsoft/vscode
--- +++ @@ -3,15 +3,13 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -'use strict'; - +import { asWinJsPromise, first } from 'vs/base/common/async'; +import { onUnexpectedExternalError } from 'vs/base/common/errors'; import { TPromise } from 'vs/base/common/winjs.base'; -import { onUnexpectedExternalError } from 'vs/base/common/errors'; +import { registerDefaultLanguageCommand } from 'vs/editor/browser/editorExtensions'; +import { Position } from 'vs/editor/common/core/position'; import { ITextModel } from 'vs/editor/common/model'; -import { registerDefaultLanguageCommand } from 'vs/editor/browser/editorExtensions'; import { SignatureHelp, SignatureHelpProviderRegistry } from 'vs/editor/common/modes'; -import { asWinJsPromise, sequence } from 'vs/base/common/async'; -import { Position } from 'vs/editor/common/core/position'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const Context = { @@ -22,20 +20,11 @@ export function provideSignatureHelp(model: ITextModel, position: Position): TPromise<SignatureHelp> { const supports = SignatureHelpProviderRegistry.ordered(model); - let result: SignatureHelp; - return sequence(supports.map(support => () => { - - if (result) { - // stop when there is a result - return undefined; - } - - return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)).then(thisResult => { - result = thisResult; - }, onUnexpectedExternalError); - - })).then(() => result); + return first(supports.map(support => () => { + return asWinJsPromise(token => support.provideSignatureHelp(model, position, token)) + .then(undefined, onUnexpectedExternalError); + })); } registerDefaultLanguageCommand('_executeSignatureHelpProvider', provideSignatureHelp);
9158be7fc0404e4672c98ee321c380a4b581e5ff
client/src/app/routes.ts
client/src/app/routes.ts
import {Route} from '@angular/router'; import {HomeComponent} from './home/home.component'; import {LoginComponent} from './login/login.component'; import {FacebookAuthorizerComponent} from './oauth/facebook/facebook_authorizer.component'; import {FacebookTokenHandlerComponent} from './oauth/facebook/facebook_token_handler.component'; import {SignupComponent} from './signup/signup.component'; import {LoggedInGuard} from './common/logged_in_guard'; import {FeedComponent} from './feed/feed.component'; import {TopicIndexComponent} from './topic/topic-index/topic-index.component'; import {TopicDetailComponent} from './topic/topic-detail/topic-detail.component'; export const ROUTES: Route[] = [ { path: '', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, { path: 'feed', component: FeedComponent, canActivate: [LoggedInGuard] }, { path: 'topics', component: TopicIndexComponent, canActivate: [LoggedInGuard], }, { path: 'topics/:id', component: TopicDetailComponent, canActivate: [LoggedInGuard] }, { path: 'oauth/facebook', children: [ { path: 'authorize', component: FacebookAuthorizerComponent }, { path: 'token', component: FacebookTokenHandlerComponent } ] } ];
import {Route} from '@angular/router'; import {HomeComponent} from './home/home.component'; import {LoginComponent} from './login/login.component'; import {FacebookAuthorizerComponent} from './oauth/facebook/facebook_authorizer.component'; import {FacebookTokenHandlerComponent} from './oauth/facebook/facebook_token_handler.component'; import {SignupComponent} from './signup/signup.component'; import {LoggedInGuard} from './common/logged_in_guard'; import {FeedComponent} from './feed/feed.component'; import {TopicIndexComponent} from './topic/topic-index/topic-index.component'; import {TopicDetailComponent} from './topic/topic-detail/topic-detail.component'; export const ROUTES: Route[] = [ { path: '', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, { path: 'feed', component: FeedComponent, canActivate: [LoggedInGuard] }, { path: 'topics', component: TopicIndexComponent, canActivate: [LoggedInGuard], }, { path: 'topics/:id', component: TopicDetailComponent, canActivate: [LoggedInGuard] }, { path: 'oauth/facebook', children: [ { path: 'authorize', component: FacebookAuthorizerComponent }, { path: 'token', component: FacebookTokenHandlerComponent } ] }, { path: '404', component: NotFoundComponent }, { path: '**', redirectTo: '404' } ];
Make path for 404 in router.
Make path for 404 in router.
TypeScript
mit
frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq
--- +++ @@ -49,5 +49,13 @@ component: FacebookTokenHandlerComponent } ] + }, + { + path: '404', + component: NotFoundComponent + }, + { + path: '**', + redirectTo: '404' } ];
568768198c173ffc62a718cade3a98dee89c809e
src/smc-webapp/project/explorer/path-segment-link.tsx
src/smc-webapp/project/explorer/path-segment-link.tsx
import * as React from "react"; import { COLORS, Tip } from "../../r_misc" const Breadcrumb = require("react-bootstrap") interface Props { path?: string, display?: string | JSX.Element, actions: any, full_name?: string, history?: boolean, active?: boolean } // One segment of the directory links at the top of the files listing. export class PathSegmentLink extends React.Component<Props> { constructor(props) { super(props); } getDefaultProps() { return { active: false }; } handle_click() { return this.props.actions.open_directory(this.props.path); } render_content() { if (this.props.full_name && this.props.full_name !== this.props.display) { return ( <Tip tip={this.props.full_name} placement="bottom" title="Full name"> {this.props.display} </Tip> ); } else { return this.props.display; } } style() { if (this.props.history) { return { color: "#c0c0c0" }; } else if (this.props.active) { return { color: COLORS.BS_BLUE_BGRND }; } return {}; } render() { return ( <Breadcrumb.Item onClick={this.handle_click} active={this.props.active} style={this.style()} > {this.render_content()} </Breadcrumb.Item> ); } }
import * as React from "react"; import { COLORS, Tip } from "../../r_misc"; const Breadcrumb = require("react-bootstrap"); interface Props { path?: string; display?: string | JSX.Element; actions: any; full_name?: string; history?: boolean; active?: boolean; } // One segment of the directory links at the top of the files listing. export function PathSegmentLink({ path, display, actions, full_name, history, active = false }: Props) { function handle_click() { return actions.open_directory(path); } function render_content() { if (full_name && full_name !== display) { return ( <Tip tip={full_name} placement="bottom" title="Full name"> {display} </Tip> ); } else { return display; } } function style() { if (history) { return { color: "#c0c0c0" }; } else if (active) { return { color: COLORS.BS_BLUE_BGRND }; } return {}; } return ( <Breadcrumb.Item onClick={handle_click} active={active} style={style()} > {render_content()} </Breadcrumb.Item> ); }
Convert PathSegmentLink to a function
Convert PathSegmentLink to a function
TypeScript
agpl-3.0
tscholl2/smc,tscholl2/smc,sagemathinc/smc,tscholl2/smc,sagemathinc/smc,tscholl2/smc,DrXyzzy/smc,DrXyzzy/smc,DrXyzzy/smc,tscholl2/smc,DrXyzzy/smc,sagemathinc/smc,sagemathinc/smc
--- +++ @@ -1,61 +1,59 @@ import * as React from "react"; -import { COLORS, Tip } from "../../r_misc" +import { COLORS, Tip } from "../../r_misc"; -const Breadcrumb = require("react-bootstrap") +const Breadcrumb = require("react-bootstrap"); interface Props { - path?: string, - display?: string | JSX.Element, - actions: any, - full_name?: string, - history?: boolean, - active?: boolean - } + path?: string; + display?: string | JSX.Element; + actions: any; + full_name?: string; + history?: boolean; + active?: boolean; +} // One segment of the directory links at the top of the files listing. -export class PathSegmentLink extends React.Component<Props> { - constructor(props) { - super(props); +export function PathSegmentLink({ + path, + display, + actions, + full_name, + history, + active = false +}: Props) { + + function handle_click() { + return actions.open_directory(path); } - getDefaultProps() { - return { active: false }; - } - - handle_click() { - return this.props.actions.open_directory(this.props.path); - } - - render_content() { - if (this.props.full_name && this.props.full_name !== this.props.display) { + function render_content() { + if (full_name && full_name !== display) { return ( - <Tip tip={this.props.full_name} placement="bottom" title="Full name"> - {this.props.display} + <Tip tip={full_name} placement="bottom" title="Full name"> + {display} </Tip> ); } else { - return this.props.display; + return display; } } - style() { - if (this.props.history) { + function style() { + if (history) { return { color: "#c0c0c0" }; - } else if (this.props.active) { + } else if (active) { return { color: COLORS.BS_BLUE_BGRND }; } return {}; } - render() { - return ( - <Breadcrumb.Item - onClick={this.handle_click} - active={this.props.active} - style={this.style()} - > - {this.render_content()} - </Breadcrumb.Item> - ); - } + return ( + <Breadcrumb.Item + onClick={handle_click} + active={active} + style={style()} + > + {render_content()} + </Breadcrumb.Item> + ); }
db04cd61b38ef219744cbae3c6e05bf313d8d3e3
APM-Final/src/app/products/product-detail.component.ts
APM-Final/src/app/products/product-detail.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IProduct } from './product'; import { ProductService } from './product.service'; @Component({ templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.css'] }) export class ProductDetailComponent implements OnInit { pageTitle: string = 'Product Detail'; errorMessage: string; product: IProduct; constructor(private _route: ActivatedRoute, private _router: Router, private _productService: ProductService) { } ngOnInit() { const id = +this._route.snapshot.paramMap.get('id'); this.getProduct(id); } getProduct(id: number) { this._productService.getProduct(id).subscribe( product => this.product = product, error => this.errorMessage = <any>error); } onBack(): void { this._router.navigate(['/products']); } }
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { IProduct } from './product'; import { ProductService } from './product.service'; @Component({ templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.css'] }) export class ProductDetailComponent implements OnInit { pageTitle: string = 'Product Detail'; errorMessage: string; product: IProduct; constructor(private _route: ActivatedRoute, private _router: Router, private _productService: ProductService) { } ngOnInit() { const param = this._route.snapshot.paramMap.get('id'); if (param) { const id = +param; this.getProduct(id); } } getProduct(id: number) { this._productService.getProduct(id).subscribe( product => this.product = product, error => this.errorMessage = <any>error); } onBack(): void { this._router.navigate(['/products']); } }
Add null check to pass strict: true
Add null check to pass strict: true
TypeScript
mit
DeborahK/Angular2-GettingStarted,DeborahK/Angular2-GettingStarted,DeborahK/Angular2-APM,DeborahK/Angular2-GettingStarted,DeborahK/Angular2-APM
--- +++ @@ -19,8 +19,11 @@ } ngOnInit() { - const id = +this._route.snapshot.paramMap.get('id'); - this.getProduct(id); + const param = this._route.snapshot.paramMap.get('id'); + if (param) { + const id = +param; + this.getProduct(id); + } } getProduct(id: number) {
1ecc866cad88bd21120fa2d264aa661007d13ed1
src/app/space/create/apps/apps.component.ts
src/app/space/create/apps/apps.component.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { AppsService, Environment, } from './services/apps.service'; @Component({ encapsulation: ViewEncapsulation.None, selector: 'alm-apps', templateUrl: 'apps.component.html' }) export class AppsComponent implements OnInit { spaceId: string; environments: Environment[]; applications: string[]; constructor( private router: Router, private appsService: AppsService ) { this.spaceId = 'placeholder-space'; } ngOnInit() { this.updateResources(); } private updateResources(): void { this.appsService.getEnvironments(this.spaceId).subscribe(val => this.environments = val); this.appsService.getApplications(this.spaceId).subscribe(val => this.applications = val); } }
import { Component, OnInit, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { AppsService, Environment, } from './services/apps.service'; @Component({ encapsulation: ViewEncapsulation.None, selector: 'alm-apps', templateUrl: 'apps.component.html' }) export class AppsComponent implements OnInit { spaceId: string; environments: Environment[]; applications: string[]; constructor( private router: Router, private appsService: AppsService ) { this.spaceId = 'placeholder-space'; } ngOnInit(): void { this.updateResources(); } private updateResources(): void { this.appsService.getEnvironments(this.spaceId).subscribe(val => this.environments = val); this.appsService.getApplications(this.spaceId).subscribe(val => this.applications = val); } }
Add missing return type declaration
Add missing return type declaration
TypeScript
apache-2.0
fabric8io/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8-ui/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8io/fabric8-ui,fabric8-ui/fabric8-ui
--- +++ @@ -23,7 +23,7 @@ this.spaceId = 'placeholder-space'; } - ngOnInit() { + ngOnInit(): void { this.updateResources(); }
009e8d0dcf201907a9bce3d480608e2a765770e4
src/core/vg-media/i-playable.ts
src/core/vg-media/i-playable.ts
import {Observable} from "rxjs/Observable"; export interface IPlayable { id:string; elem:any; time:any; buffer:any; track?:any; // its optional, need in add custom cue (addTextTrack) canPlay:boolean; canPlayThrough:boolean; isMetadataLoaded:boolean; isWaiting:boolean; isCompleted:boolean; isLive:boolean; state:string; subscriptions:IMediaSubscriptions; duration:number; currentTime:number; play:Function; pause:Function; dispatchEvent?:Function; } export interface IMediaSubscriptions { abort: Observable<any>; bufferDetected: Observable<any>; canPlay: Observable<any>; canPlayThrough: Observable<any>; durationChange: Observable<any>; emptied: Observable<any>; encrypted: Observable<any>; ended: Observable<any>; error: Observable<any>; loadedData: Observable<any>; loadedMetadata: Observable<any>; loadStart: Observable<any>; pause: Observable<any>; play: Observable<any>; playing: Observable<any>; progress: Observable<any>; rateChange: Observable<any>; seeked: Observable<any>; seeking: Observable<any>; stalled: Observable<any>; suspend: Observable<any>; timeUpdate: Observable<any>; volumeChange: Observable<any>; waiting: Observable<any>; // to observe the ads startAds: Observable<any>; endAds: Observable<any>; }
import {Observable} from "rxjs/Observable"; export interface IPlayable { id:string; elem:any; time:any; buffer:any; track?:any; canPlay:boolean; canPlayThrough:boolean; isMetadataLoaded:boolean; isWaiting:boolean; isCompleted:boolean; isLive:boolean; state:string; subscriptions:IMediaSubscriptions; duration:number; currentTime:number; play:Function; pause:Function; dispatchEvent?:Function; } export interface IMediaSubscriptions { abort: Observable<any>; bufferDetected: Observable<any>; canPlay: Observable<any>; canPlayThrough: Observable<any>; durationChange: Observable<any>; emptied: Observable<any>; encrypted: Observable<any>; ended: Observable<any>; error: Observable<any>; loadedData: Observable<any>; loadedMetadata: Observable<any>; loadStart: Observable<any>; pause: Observable<any>; play: Observable<any>; playing: Observable<any>; progress: Observable<any>; rateChange: Observable<any>; seeked: Observable<any>; seeking: Observable<any>; stalled: Observable<any>; suspend: Observable<any>; timeUpdate: Observable<any>; volumeChange: Observable<any>; waiting: Observable<any>; // to observe the ads startAds: Observable<any>; endAds: Observable<any>; }
Add create track and cues dynamically
Add create track and cues dynamically
TypeScript
mit
videogular/videogular2,kwarismian/videogular2,videogular/videogular2,amitkumarmahajan/videogular2,amitkumarmahajan/videogular2,kwarismian/videogular2,kwarismian/videogular2,amitkumarmahajan/videogular2,videogular/videogular2
--- +++ @@ -5,7 +5,7 @@ elem:any; time:any; buffer:any; - track?:any; // its optional, need in add custom cue (addTextTrack) + track?:any; canPlay:boolean; canPlayThrough:boolean; isMetadataLoaded:boolean;
e8c4abaa12787782ef5b452e9c1f46d20ab255f5
src/components/nav-bar-item/nav-bar.spec.ts
src/components/nav-bar-item/nav-bar.spec.ts
import Vue from 'vue'; import '../../utils/polyfills'; import NavBarItemPlugin, { MNavBarItem } from './nav-bar-item'; const SELECTED_CSS: string = 'm--is-selected'; let navbaritem: MNavBarItem; describe('navbar-item', () => { beforeEach(() => { Vue.use(NavBarItemPlugin); navbaritem = new MNavBarItem().$mount(); }); it('skin prop', () => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeFalsy(); navbaritem.selected = true; Vue.nextTick(() => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeTruthy(); navbaritem.selected = false; Vue.nextTick(() => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeFalsy(); }); }); }); it('click event', () => { let clickSpy = jasmine.createSpy('clickSpy'); let vm = new Vue({ template: ` <m-nav-bar-item @click="onClick($event)"></m-nav-bar-item> `, methods: { onClick: clickSpy } }).$mount(); let element = vm.$el; console.log(vm.$el); if (element) { (element as any).click(); } Vue.nextTick(() => { expect(clickSpy).toHaveBeenCalled(); }); }); });
import Vue from 'vue'; import '../../utils/polyfills'; import NavBarItemPlugin, { MNavBarItem } from './nav-bar-item'; const SELECTED_CSS: string = 'm--is-selected'; let navbaritem: MNavBarItem; describe('navbar-item', () => { beforeEach(() => { Vue.use(NavBarItemPlugin); navbaritem = new MNavBarItem().$mount(); }); it('selected prop', () => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeFalsy(); navbaritem.selected = true; Vue.nextTick(() => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeTruthy(); navbaritem.selected = false; Vue.nextTick(() => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeFalsy(); }); }); }); it('click event', () => { let clickSpy = jasmine.createSpy('clickSpy'); let vm = new Vue({ template: ` <m-nav-bar-item @click="onClick($event)"></m-nav-bar-item> `, methods: { onClick: clickSpy } }).$mount(); let element = vm.$el; console.log(vm.$el); if (element) { (element as any).click(); } Vue.nextTick(() => { expect(clickSpy).toHaveBeenCalled(); }); }); });
Change test name in nav-bar-item
Change test name in nav-bar-item
TypeScript
apache-2.0
ulaval/modul-components,ulaval/modul-components,ulaval/modul-components
--- +++ @@ -12,7 +12,7 @@ navbaritem = new MNavBarItem().$mount(); }); - it('skin prop', () => { + it('selected prop', () => { expect(navbaritem.$el.classList.contains(SELECTED_CSS)).toBeFalsy(); navbaritem.selected = true;
a6f0651d054a09772b9bdeaea5d6b00aca255361
output-googleassistant/src/models/Scene.ts
output-googleassistant/src/models/Scene.ts
import { EnumLike, IsEnum, IsNotEmpty, IsObject, IsOptional, IsString, Type, ValidateNested, } from '@jovotech/output'; export class NextScene { @IsString() @IsNotEmpty() name: string; } export enum SlotFillingStatus { Unspecified = 'UNSPECIFIED', Initialized = 'INITIALIZED', Collecting = 'COLLECTING', Final = 'FINAL', } export type SlotFillingStatusLike = EnumLike<SlotFillingStatus>; export class Scene { @IsString() @IsNotEmpty() name: string; @IsOptional() @IsEnum(SlotFillingStatus) slotFillingStatus?: SlotFillingStatusLike; @IsObject() slots: Record<string, unknown>; @IsOptional() @ValidateNested() @Type(() => NextScene) next?: NextScene; }
import { EnumLike, IsEnum, IsNotEmpty, IsObject, IsOptional, IsString, Type, ValidateNested, } from '@jovotech/output'; export class NextScene { @IsString() @IsNotEmpty() name: string; } export enum SlotFillingStatus { Unspecified = 'UNSPECIFIED', Initialized = 'INITIALIZED', Collecting = 'COLLECTING', Final = 'FINAL', } export type SlotFillingStatusLike = EnumLike<SlotFillingStatus>; export class Scene { @IsString() name: string; @IsOptional() @IsEnum(SlotFillingStatus) slotFillingStatus?: SlotFillingStatusLike; @IsObject() slots: Record<string, unknown>; @IsOptional() @ValidateNested() @Type(() => NextScene) next?: NextScene; }
Allow scene.name to be empty to be filled by platform
:recycle: Allow scene.name to be empty to be filled by platform
TypeScript
apache-2.0
jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs
--- +++ @@ -26,7 +26,6 @@ export class Scene { @IsString() - @IsNotEmpty() name: string; @IsOptional()
8d16e762e7ecf359ba2431b42487afeafe694a86
src/open_farm/__tests__/index_test.tsx
src/open_farm/__tests__/index_test.tsx
jest.mock("axios", function () { return { default: { get: function () { return Promise.resolve({ data: { id: 0, data: { attributes: { svg_icon: "<svg>Wow</svg>", slug: "lettuce" } } } }); } } }; }); import { cachedCrop, DATA_URI, OpenFarmAPI } from "../index"; describe("cachedIcon()", () => { it("does an HTTP request if the icon can't be found locally", (done) => { cachedCrop("lettuce") .then(function (item) { expect(item).toContain(DATA_URI); expect(item).toContain(encodeURIComponent("<svg>Wow</svg>")); done(); }) .catch(() => { fail(); }); }); it("has a base URL", () => { expect(OpenFarmAPI.OFBaseURL).toContain("openfarm.cc"); }); });
jest.mock("axios", function () { return { default: { get: function () { return Promise.resolve({ data: { id: 0, data: { attributes: { svg_icon: "<svg>Wow</svg>", slug: "lettuce" } } } }); } } }; }); import { cachedCrop, DATA_URI, OpenFarmAPI } from "../index"; describe("cachedIcon()", () => { it("does an HTTP request if the icon can't be found locally", (done) => { cachedCrop("lettuce") .then(function (item) { expect(item.svg_icon).toContain("<svg>Wow</svg>"); done(); }) .catch((error) => { expect(error).toBeFalsy(); done(); }); }); it("has a base URL", () => { expect(OpenFarmAPI.OFBaseURL).toContain("openfarm.cc"); }); });
Update tests to reflect changes
Update tests to reflect changes
TypeScript
mit
RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,MrChristofferson/Farmbot-Web-API,FarmBot/Farmbot-Web-API,MrChristofferson/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,MrChristofferson/Farmbot-Web-API,MrChristofferson/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/farmbot-web-app
--- +++ @@ -24,12 +24,12 @@ it("does an HTTP request if the icon can't be found locally", (done) => { cachedCrop("lettuce") .then(function (item) { - expect(item).toContain(DATA_URI); - expect(item).toContain(encodeURIComponent("<svg>Wow</svg>")); + expect(item.svg_icon).toContain("<svg>Wow</svg>"); done(); }) - .catch(() => { - fail(); + .catch((error) => { + expect(error).toBeFalsy(); + done(); }); });
88fa2116371ab2e153d41c94a2e6e01171b1a9b8
client/src/app/plants/bed.component.ts
client/src/app/plants/bed.component.ts
import { Component, OnInit } from '@angular/core'; import { PlantListService } from "./plant-list.service"; import { Plant } from "./plant"; import {Params, ActivatedRoute} from "@angular/router"; @Component({ selector: 'bed-component', templateUrl: 'bed.component.html', }) export class BedComponent implements OnInit { public bed : string; public plants: Plant[]; public locations: Plant[]; constructor(private plantListService: PlantListService, private route: ActivatedRoute) { // this.plants = this.plantListService.getPlants() //Get the bed from the params of the route this.bed = this.route.snapshot.params["gardenLocation"]; } ngOnInit(): void{ this.refreshInformation(); } refreshInformation() : void { this.plantListService.getFlowersByBed(this.bed).subscribe ( plants => this.plants = plants, err => { console.log(err); } ); this.plantListService.getGardenLocations().subscribe( locations => this.locations = locations, err => { console.log(err); } ); } }
import { Component, OnInit } from '@angular/core'; import { PlantListService } from "./plant-list.service"; import { Plant } from "./plant"; import {Params, ActivatedRoute, Router} from "@angular/router"; @Component({ selector: 'bed-component', templateUrl: 'bed.component.html', }) export class BedComponent implements OnInit { public bed : string; public plants: Plant[]; public locations: Plant[]; constructor(private plantListService: PlantListService, private route: ActivatedRoute, private router: Router) { // this.plants = this.plantListService.getPlants() //Get the bed from the params of the route this.router.events.subscribe((val) => { this.bed = this.route.snapshot.params["gardenLocation"]; this.refreshInformation(); }); } ngOnInit(): void{ } refreshInformation() : void { this.plantListService.getFlowersByBed(this.bed).subscribe ( plants => this.plants = plants, err => { console.log(err); } ); this.plantListService.getGardenLocations().subscribe( locations => this.locations = locations, err => { console.log(err); } ); } }
Call refreshInformation on URL change
Call refreshInformation on URL change
TypeScript
mit
UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2
--- +++ @@ -1,7 +1,7 @@ import { Component, OnInit } from '@angular/core'; import { PlantListService } from "./plant-list.service"; import { Plant } from "./plant"; -import {Params, ActivatedRoute} from "@angular/router"; +import {Params, ActivatedRoute, Router} from "@angular/router"; @Component({ selector: 'bed-component', @@ -13,16 +13,18 @@ public plants: Plant[]; public locations: Plant[]; - constructor(private plantListService: PlantListService, private route: ActivatedRoute) { + constructor(private plantListService: PlantListService, private route: ActivatedRoute, private router: Router) { // this.plants = this.plantListService.getPlants() //Get the bed from the params of the route - this.bed = this.route.snapshot.params["gardenLocation"]; + this.router.events.subscribe((val) => { + this.bed = this.route.snapshot.params["gardenLocation"]; + this.refreshInformation(); + }); } ngOnInit(): void{ - this.refreshInformation(); } refreshInformation() : void
a1bfd99aeb4e5ee90a9b75ef80de30cc9b00ac78
packages/rev-ui-materialui/src/actions/MUIActionButton.tsx
packages/rev-ui-materialui/src/actions/MUIActionButton.tsx
import * as React from 'react'; import { IActionComponentProps } from 'rev-ui/lib/actions/types'; import Button from 'material-ui/Button'; export const MUIActionButton: React.SFC<IActionComponentProps> = (props) => { const childContent = props.children || props.label; return ( <Button raised color="primary" onClick={() => props.doAction()} style={{ margin: 12 }} disabled={props.disabled} > {childContent} </Button> ); };
import * as React from 'react'; import { IActionComponentProps } from 'rev-ui/lib/actions/types'; import Button from 'material-ui/Button'; export const MUIActionButton: React.SFC<IActionComponentProps> = (props) => { const childContent = props.children || props.label; return ( <Button raised color="primary" onClick={() => props.doAction()} disabled={props.disabled} > {childContent} </Button> ); };
Remove default margin from ActionButton
Remove default margin from ActionButton
TypeScript
mit
RevFramework/rev-framework,RevFramework/rev-framework
--- +++ @@ -11,7 +11,6 @@ return ( <Button raised color="primary" onClick={() => props.doAction()} - style={{ margin: 12 }} disabled={props.disabled} > {childContent}
99678056bc86f3d8bc1b3cc6c2b86a3efe39f3de
Mechanism/Widget.ts
Mechanism/Widget.ts
///<reference path="RenderObject.ts"/> ///<reference path="Animations/Animators.ts"/> class Widget extends RenderObject { children: Widget[] = []; position = Vector2.zero; scale = Vector2.one; rotation = 0; pivot = Vector2.zero; size = new Vector2(100, 100); beforeRender(renderer: Renderer): void { renderer.save(); const offset = this.position.subtract(this.pivot.multiply(new Vector2(this.width, this.height))); renderer.translate(offset.x, offset.y); renderer.rotate(this.rotation); renderer.scale(this.scale.x, this.scale.y); } afterRender(renderer: Renderer): void { renderer.restore(); } get width(): number { return this.size.x; } get height(): number { return this.size.y; } addChild(widget: Widget): void { super.addChild(widget); } static positionAnimator = () => new Vector2Animator("position"); static scaleAnimator = () => new Vector2Animator("scale"); static pivotAnimator = () => new Vector2Animator("pivot"); static sizeAnimator = () => new Vector2Animator("size"); static rotationAnimator = () => new NumberAnimator("rotation"); }
///<reference path="RenderObject.ts"/> ///<reference path="Animations/Animators.ts"/> class Widget extends RenderObject { children: Widget[] = []; position = Vector2.zero; scale = Vector2.one; rotation = 0; pivot = Vector2.zero; size = new Vector2(100, 100); beforeRender(renderer: Renderer): void { renderer.save(); const offset = this.position.subtract(this.pivot.multiply(new Vector2(this.width, this.height))); renderer.translate(offset.x, offset.y); renderer.rotate(this.rotation); renderer.scale(this.scale.x, this.scale.y); } afterRender(renderer: Renderer): void { renderer.restore(); } get x(): number { return this.position.x; } set x(value: number) { this.position.x = value; } get y(): number { return this.position.y; } set y(value: number) { this.position.y = value; } get width(): number { return this.size.x; } set width(value: number) { this.size.x = value; } get height(): number { return this.size.y; } set height(value: number) { this.size.y = value; } addChild(widget: Widget): void { super.addChild(widget); } static positionAnimator = () => new Vector2Animator("position"); static scaleAnimator = () => new Vector2Animator("scale"); static pivotAnimator = () => new Vector2Animator("pivot"); static sizeAnimator = () => new Vector2Animator("size"); static rotationAnimator = () => new NumberAnimator("rotation"); }
Add position and size shortcuts for widget.
Add position and size shortcuts for widget.
TypeScript
apache-2.0
Dia6lo/Mechanism,Dia6lo/Mechanism,Dia6lo/Mechanism
--- +++ @@ -20,12 +20,36 @@ renderer.restore(); } + get x(): number { + return this.position.x; + } + + set x(value: number) { + this.position.x = value; + } + + get y(): number { + return this.position.y; + } + + set y(value: number) { + this.position.y = value; + } + get width(): number { return this.size.x; } + set width(value: number) { + this.size.x = value; + } + get height(): number { return this.size.y; + } + + set height(value: number) { + this.size.y = value; } addChild(widget: Widget): void {
c81350a8902e7f7dc579d59773077a7f5554833d
src/app/components/menu-service.ts
src/app/components/menu-service.ts
import {Router} from '@angular/router'; import {Injectable, NgZone} from '@angular/core'; const ipcRenderer = typeof window !== 'undefined' ? window.require('electron').ipcRenderer : require('electron').ipcRenderer; const remote = typeof window !== 'undefined' ? window.require('electron').remote : require('electron').remote; type MenuContext = 'loading'|'default'|'docedit'|'modal'|'projects'|'geometryedit'; @Injectable() /** * @author Thomas Kleinke */ export class MenuService { constructor(private router: Router, private zone: NgZone) {} public initialize() { ipcRenderer.on('menuItemClicked', async (event: any, menuItem: string) => { await this.onMenuItemClicked(menuItem); }); MenuService.setContext('default'); } public async onMenuItemClicked(menuItem: string) { await this.zone.run(async () => await this.router.navigate([menuItem])); } public static setContext(context: MenuContext) { remote.getGlobal('setMenuContext')(context); } }
import {Router} from '@angular/router'; import {Injectable, NgZone} from '@angular/core'; const ipcRenderer = typeof window !== 'undefined' ? window.require('electron').ipcRenderer : require('electron').ipcRenderer; const remote = typeof window !== 'undefined' ? window.require('electron').remote : require('electron').remote; type MenuContext = 'loading'|'default'|'docedit'|'modal'|'projects'|'geometryedit'; @Injectable() /** * @author Thomas Kleinke */ export class MenuService { constructor(private router: Router, private zone: NgZone) {} public initialize() { ipcRenderer.on('menuItemClicked', async (event: any, menuItem: string) => { await this.onMenuItemClicked(menuItem); }); MenuService.setContext('default'); } public async onMenuItemClicked(menuItem: string) { await this.zone.run(async () => await this.router.navigate([menuItem])); } public static setContext(context: MenuContext) { if (remote) remote.getGlobal('setMenuContext')(context); } }
Check for existence of remote in MenuService to fix unit tests
Check for existence of remote in MenuService to fix unit tests
TypeScript
apache-2.0
codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client
--- +++ @@ -36,6 +36,6 @@ public static setContext(context: MenuContext) { - remote.getGlobal('setMenuContext')(context); + if (remote) remote.getGlobal('setMenuContext')(context); } }
45b520975d515a88ac975ca09035b196ba5abeda
read.ts
read.ts
import { AggregateIdType, DomainEvent, DomainEventType, allDomainEvents, domainEventsByAggregate } from "./event-store"; export function todoListEvents(): Promise<DomainEvent[]> { // This app's domain and event-store are designed to accommodate multiple aggregates of different types. // Currently, the app only has one aggregate type (TodoList) and only allows the user to have one instance of that aggregate. // This todoLists() lookup occurs to get the aggreateId of the user's one TodoList. return allDomainEvents() .then(events => { let lists = todoLists(events); return (lists.length) ? domainEventsByAggregate(lists[0]) : []; }) } function todoLists(events: DomainEvent[]): AggregateIdType[] { return events.reduce<AggregateIdType[]>((p, c) => { if (c.type === DomainEventType.TodoAdded && p.indexOf(c.aggregateId) !== -1) { p.push(c.aggregateId); } return p; }, []); }
import { AggregateIdType, DomainEvent, DomainEventType, allDomainEvents, domainEventsByAggregate } from "./event-store"; export function todoListEvents(): Promise<DomainEvent[]> { // This app's domain and event-store are designed to accommodate multiple aggregates of different types. // Currently, the app only has one aggregate type (TodoList) and only allows the user to have one instance of that aggregate. // This todoLists() lookup occurs to get the aggreateId of the user's one TodoList. return allDomainEvents() .then(events => { let lists = todoLists(events); return (lists.length) ? domainEventsByAggregate(lists[0]) : []; }) } function todoLists(events: DomainEvent[]): AggregateIdType[] { return events.reduce<AggregateIdType[]>((p, c) => { if (c.type === DomainEventType.TodoAdded && p.indexOf(c.aggregateId) === -1) { p.push(c.aggregateId); } return p; }, []); }
Fix domain events not loading on page load
Fix domain events not loading on page load
TypeScript
mit
jbrianskog/static-event-sourcing-todo,jbrianskog/static-event-sourcing-todo
--- +++ @@ -15,7 +15,7 @@ function todoLists(events: DomainEvent[]): AggregateIdType[] { return events.reduce<AggregateIdType[]>((p, c) => { - if (c.type === DomainEventType.TodoAdded && p.indexOf(c.aggregateId) !== -1) { + if (c.type === DomainEventType.TodoAdded && p.indexOf(c.aggregateId) === -1) { p.push(c.aggregateId); } return p;
ea5c960c348b5405e820f98087af1ea182641e12
src/index.ts
src/index.ts
/* eslint-disable @typescript-eslint/no-var-requires */ import * as SegfaultHandler from 'segfault-handler' SegfaultHandler.registerHandler('crash.log') import 'source-map-support/register' export * from './commands/generate' export * from './commands/list' export * from './types' export * from './config' export * from './generator' export * from './gir-module' export * from './logger' export * from './module-loader' export * from './template-processor' export * from './transformation' export * from './utils' export { run } from '@oclif/command' if (require.main === module) { // If we don't catch exceptions, stdout gets truncated try { require('@oclif/command') .run() .then(require('@oclif/command/flush')) .catch((error) => { console.log(error) require('@oclif/errors/handle')(error) }) } catch (ex) { console.log(ex.stack) } }
/* eslint-disable @typescript-eslint/no-var-requires */ import * as SegfaultHandler from 'segfault-handler' SegfaultHandler.registerHandler('crash.log') import 'source-map-support/register' export * from './commands/generate' export * from './commands/list' export * from './types' export * from './config' export * from './generator' export * from './gir-module' export * from './logger' export * from './module-loader' export * from './template-processor' export * from './transformation' export * from './utils' export { run } from '@oclif/command' if (require.main === module) { // If we don't catch exceptions, stdout gets truncated try { require('@oclif/command') .run() .then(require('@oclif/command/flush')) .catch((error) => { console.log(error) require('@oclif/errors/handle')(error) }) } catch (ex: any) { console.log(ex.stack) } }
Add the type for ex
Add the type for ex ... to avoid the type-unknown error during installation.
TypeScript
apache-2.0
sammydre/ts-for-gjs,sammydre/ts-for-gjs
--- +++ @@ -26,7 +26,7 @@ console.log(error) require('@oclif/errors/handle')(error) }) - } catch (ex) { + } catch (ex: any) { console.log(ex.stack) } }
c0b80796e2ec9207bd2edc0f31e5999c40236ed6
src/index.ts
src/index.ts
const express = require('express'); const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectId; const bodyParser = require('body-parser'); const logger = require('morgan'); // SETUP // =================================== const config = require('./config.json'); const app = express(); const port = process.env.PORT || 8080; app.get('/', (req, res) => { res.send('Please select a collection, eg., /collections/messages'); }); // START // =================================== app.listen(port, () => { console.log(`Express server listening on port ${port}`); });
const express = require('express'); const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectId; const bodyParser = require('body-parser'); const logger = require('morgan'); // SETUP // =================================== const config = require('./config.json'); const app = express(); const port = process.env.PORT || 8080; const dbUrl = config.dbUrl; const collectionsList = [ 'comics', 'events', 'series', 'creators', 'characters', ]; // MIDDLEWARES // =================================== app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(logger('dev')); // ROUTES // =================================== const router = express.Router(); router.get('/', (req, res) => { res.json({message: 'Please select a collection, eg., /collections/messages'}); }); app.use('/', router); // START // =================================== app.listen(port, () => { console.log(`Express server listening on port ${port}`); });
Set up basic routing and middlewares
Set up basic routing and middlewares
TypeScript
mit
SBats/marvel-reading-stats-backend
--- +++ @@ -12,10 +12,34 @@ const app = express(); const port = process.env.PORT || 8080; +const dbUrl = config.dbUrl; +const collectionsList = [ + 'comics', + 'events', + 'series', + 'creators', + 'characters', +]; -app.get('/', (req, res) => { - res.send('Please select a collection, eg., /collections/messages'); + +// MIDDLEWARES +// =================================== + +app.use(bodyParser.urlencoded({ extended: true })); +app.use(bodyParser.json()); +app.use(logger('dev')); + + +// ROUTES +// =================================== + +const router = express.Router(); + +router.get('/', (req, res) => { + res.json({message: 'Please select a collection, eg., /collections/messages'}); }); + +app.use('/', router); // START
87e05578aaae011413288664630e35b7d20956e4
src/modules/payment-backend-methods/hooks/afterRegistration.ts
src/modules/payment-backend-methods/hooks/afterRegistration.ts
import * as types from './../store/mutation-types' export function afterRegistration(Vue, config, store, isServer) { // Place the order. Payload is empty as we don't have any specific info to add for this payment method '{}' const placeOrder = function () { Vue.prototype.$bus.$emit('checkout-do-placeOrder', {}) } if (!Vue.prototype.$isServer) { // Update the methods Vue.prototype.$bus.$on('set-unique-payment-methods', methods => { store.commit('payment-backend-methods/' + types.SET_BACKEND_PAYMENT_METHODS, methods) }) // Mount the info component when required. Vue.prototype.$bus.$on('checkout-payment-method-changed', (paymentMethodCode) => { if (store.state['payment-backend-methods'].methods.find(item => item.code === paymentMethodCode)) { // Register the handler for what happens when they click the place order button. Vue.prototype.$bus.$on('checkout-before-placeOrder', placeOrder) } else { // unregister the extensions placeorder handler Vue.prototype.$bus.$off('checkout-before-placeOrder', placeOrder) } }) } }
import * as types from './../store/mutation-types' export function afterRegistration(Vue, config, store, isServer) { // Place the order. Payload is empty as we don't have any specific info to add for this payment method '{}' const placeOrder = function () { Vue.prototype.$bus.$emit('checkout-do-placeOrder', {}) } if (!Vue.prototype.$isServer) { // Update the methods Vue.prototype.$bus.$on('set-unique-payment-methods', methods => { store.commit('payment-backend-methods/' + types.SET_BACKEND_PAYMENT_METHODS, methods) }) // Mount the info component when required. Vue.prototype.$bus.$on('checkout-payment-method-changed', (paymentMethodCode) => { let methods = store.state['payment-backend-methods'].methods if (methods !== null && methods.find(item => item.code === paymentMethodCode)) { // Register the handler for what happens when they click the place order button. Vue.prototype.$bus.$on('checkout-before-placeOrder', placeOrder) } else { // unregister the extensions placeorder handler Vue.prototype.$bus.$off('checkout-before-placeOrder', placeOrder) } }) } }
Check on null for state of payment-backend-methods
Check on null for state of payment-backend-methods
TypeScript
mit
pkarw/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront,DivanteLtd/vue-storefront,pkarw/vue-storefront
--- +++ @@ -14,7 +14,8 @@ // Mount the info component when required. Vue.prototype.$bus.$on('checkout-payment-method-changed', (paymentMethodCode) => { - if (store.state['payment-backend-methods'].methods.find(item => item.code === paymentMethodCode)) { + let methods = store.state['payment-backend-methods'].methods + if (methods !== null && methods.find(item => item.code === paymentMethodCode)) { // Register the handler for what happens when they click the place order button. Vue.prototype.$bus.$on('checkout-before-placeOrder', placeOrder) } else {
3525fbae2e1dcb281500c0395e45339a7cb3f2c1
TameGame/Input/StandardControlBindings.ts
TameGame/Input/StandardControlBindings.ts
/// <reference path="Interface.ts" /> module TameGame { /** * Some well-known control bindings used in many different types of game */ export var standardControls: { [name: string]: ControlBinding } = { /** The WASD control layout. Provides up, down, left, right control actions */ wasd: { up: [ { device: controlDevice.keyboard, control: 'W' } ], down: [ { device: controlDevice.keyboard, control: 'S' } ], left: [ { device: controlDevice.keyboard, control: 'A' } ], right: [ { device: controlDevice.keyboard, control: 'D' } ], }, /** The arrow keys control layout. Provides up, down, left, right control actions */ arrows: { up: [ { device: controlDevice.keyboard, control: keyControl.arrowup } ], down: [ { device: controlDevice.keyboard, control: keyControl.arrowdown } ], left: [ { device: controlDevice.keyboard, control: keyControl.arrowleft } ], right: [ { device: controlDevice.keyboard, control: keyControl.arrowright } ], } }; }
/// <reference path="Interface.ts" /> module TameGame { /** * Some well-known control bindings used in many different types of game */ export var standardControls: { [name: string]: ControlBinding } = { /** The WASD control layout. Provides up, down, left, right control actions */ wasd: { up: [ { device: controlDevice.keyboard, control: 'W' } ], down: [ { device: controlDevice.keyboard, control: 'S' } ], left: [ { device: controlDevice.keyboard, control: 'A' } ], right: [ { device: controlDevice.keyboard, control: 'D' } ], }, /** The arrow keys control layout. Provides up, down, left, right control actions */ arrows: { up: [ { device: controlDevice.keyboard, control: keyControl.arrowup } ], down: [ { device: controlDevice.keyboard, control: keyControl.arrowdown } ], left: [ { device: controlDevice.keyboard, control: keyControl.arrowleft } ], right: [ { device: controlDevice.keyboard, control: keyControl.arrowright } ], }, /** The mouse control layout: makes it possible to track the pointer and respond to clicks */ mouse: { point: [ { device: controlDevice.mouse, control: mouseControl.pointer }], click: [ { device: controlDevice.mouse, control: mouseControl.button1 }], rightclick: [ { device: controlDevice.mouse, control: mouseControl.button3 } ], middleclick: [ { device: controlDevice.mouse, control: mouseControl.button3 } ] } }; }
Add mouse events to the set of standard control bindings
Add mouse events to the set of standard control bindings
TypeScript
apache-2.0
TameGame/Engine,TameGame/Engine,TameGame/Engine
--- +++ @@ -19,6 +19,14 @@ down: [ { device: controlDevice.keyboard, control: keyControl.arrowdown } ], left: [ { device: controlDevice.keyboard, control: keyControl.arrowleft } ], right: [ { device: controlDevice.keyboard, control: keyControl.arrowright } ], + }, + + /** The mouse control layout: makes it possible to track the pointer and respond to clicks */ + mouse: { + point: [ { device: controlDevice.mouse, control: mouseControl.pointer }], + click: [ { device: controlDevice.mouse, control: mouseControl.button1 }], + rightclick: [ { device: controlDevice.mouse, control: mouseControl.button3 } ], + middleclick: [ { device: controlDevice.mouse, control: mouseControl.button3 } ] } }; }
6b95ece8e168628012fea275153c2e614f1ff1a0
src/webauthn-json/schema-format.ts
src/webauthn-json/schema-format.ts
type SchemaLeaf = "copy" | "convert"; export interface SchemaProperty { required: boolean; schema: Schema; derive?: (v: any) => any; } interface SchemaObject { [property: string]: SchemaProperty; } type SchemaArray = [SchemaObject] | [SchemaLeaf]; export type Schema = SchemaLeaf | SchemaArray | SchemaObject;
type SchemaLeaf = "copy" | "convert"; export interface SchemaProperty { required: boolean; schema: Schema; derive?: (v: any) => any; // For client extension results, transports, etc. } interface SchemaObject { [property: string]: SchemaProperty; } type SchemaArray = [SchemaObject] | [SchemaLeaf]; export type Schema = SchemaLeaf | SchemaArray | SchemaObject;
Add a comment to the `derive` declaration with examples.
Add a comment to the `derive` declaration with examples.
TypeScript
mit
github/webauthn-json,github/webauthn-json,github/webauthn-json
--- +++ @@ -2,7 +2,7 @@ export interface SchemaProperty { required: boolean; schema: Schema; - derive?: (v: any) => any; + derive?: (v: any) => any; // For client extension results, transports, etc. } interface SchemaObject { [property: string]: SchemaProperty;
2244ee2736279e0e0b0a41443e189ca8198c3417
src/parser/mage/fire/normalizers/Combustion.tsx
src/parser/mage/fire/normalizers/Combustion.tsx
import SPELLS from 'common/SPELLS'; import EventsNormalizer from 'parser/core/EventsNormalizer'; import { Event, EventType, ApplyBuffEvent, CastEvent } from 'parser/core/Events'; class Combustion extends EventsNormalizer { /** * @param {Array} events * @returns {Array} */ normalize(events: Event<any>[]) { const fixedEvents: Event<any>[] = []; events.forEach((event: Event<any>, eventIndex: number) => { fixedEvents.push(event); if (event.type === EventType.Cast && (event as CastEvent).ability.guid === SPELLS.COMBUSTION.id) { const castTimestamp = event.timestamp; for (let previousEventIndex = eventIndex; previousEventIndex >= 0; previousEventIndex -= 1) { const previousEvent = fixedEvents[previousEventIndex]; if ((castTimestamp - previousEvent.timestamp) > 50) { break; } if (previousEvent.type === EventType.ApplyBuff && (previousEvent as ApplyBuffEvent).ability.guid === SPELLS.COMBUSTION.id && (previousEvent as ApplyBuffEvent).sourceID === (event as CastEvent).sourceID) { fixedEvents.splice(previousEventIndex, 1); fixedEvents.push(previousEvent); previousEvent.__modified = true; break; } } } }); return fixedEvents; } } export default Combustion;
import SPELLS from 'common/SPELLS'; import EventsNormalizer from 'parser/core/EventsNormalizer'; import { AnyEvent, EventType } from 'parser/core/Events'; class Combustion extends EventsNormalizer { normalize(events: AnyEvent[]): AnyEvent[] { const fixedEvents: AnyEvent[] = []; events.forEach((event, eventIndex) => { fixedEvents.push(event); if (event.type === EventType.Cast && event.ability.guid === SPELLS.COMBUSTION.id) { const castTimestamp = event.timestamp; for (let previousEventIndex = eventIndex; previousEventIndex >= 0; previousEventIndex -= 1) { const previousEvent = fixedEvents[previousEventIndex]; if ((castTimestamp - previousEvent.timestamp) > 50) { break; } if (previousEvent.type === EventType.ApplyBuff && previousEvent.ability.guid === SPELLS.COMBUSTION.id && previousEvent.sourceID === event.sourceID) { fixedEvents.splice(previousEventIndex, 1); fixedEvents.push(previousEvent); previousEvent.__modified = true; break; } } } }); return fixedEvents; } } export default Combustion;
Update combustion normalizer to AnyEvent
Update combustion normalizer to AnyEvent
TypeScript
agpl-3.0
yajinni/WoWAnalyzer,anom0ly/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,yajinni/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer
--- +++ @@ -1,19 +1,15 @@ import SPELLS from 'common/SPELLS'; import EventsNormalizer from 'parser/core/EventsNormalizer'; -import { Event, EventType, ApplyBuffEvent, CastEvent } from 'parser/core/Events'; +import { AnyEvent, EventType } from 'parser/core/Events'; class Combustion extends EventsNormalizer { - /** - * @param {Array} events - * @returns {Array} - */ - normalize(events: Event<any>[]) { - const fixedEvents: Event<any>[] = []; - events.forEach((event: Event<any>, eventIndex: number) => { + normalize(events: AnyEvent[]): AnyEvent[] { + const fixedEvents: AnyEvent[] = []; + events.forEach((event, eventIndex) => { fixedEvents.push(event); - if (event.type === EventType.Cast && (event as CastEvent).ability.guid === SPELLS.COMBUSTION.id) { + if (event.type === EventType.Cast && event.ability.guid === SPELLS.COMBUSTION.id) { const castTimestamp = event.timestamp; for (let previousEventIndex = eventIndex; previousEventIndex >= 0; previousEventIndex -= 1) { @@ -21,7 +17,7 @@ if ((castTimestamp - previousEvent.timestamp) > 50) { break; } - if (previousEvent.type === EventType.ApplyBuff && (previousEvent as ApplyBuffEvent).ability.guid === SPELLS.COMBUSTION.id && (previousEvent as ApplyBuffEvent).sourceID === (event as CastEvent).sourceID) { + if (previousEvent.type === EventType.ApplyBuff && previousEvent.ability.guid === SPELLS.COMBUSTION.id && previousEvent.sourceID === event.sourceID) { fixedEvents.splice(previousEventIndex, 1); fixedEvents.push(previousEvent); previousEvent.__modified = true;
b795d676b49e965c7902410dc15e96e063065728
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', 'vor.nachname@gmail.com', '+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', 'vor.nachname@gmail.com', '+234-809-613-2999'); + constructor() {} }
f3acfb61d87a1cfa1a191c0cd194bfe0f2ce4b2b
applications/mail/src/app/components/message/MessageBody.tsx
applications/mail/src/app/components/message/MessageBody.tsx
import React, { useMemo } from 'react'; import { classnames, useToggle, Button } from 'react-components'; import { isPlainText } from '../../helpers/message/messages'; import { MessageExtended } from '../../models/message'; import { locateBlockquote } from '../../helpers/message/messageBlockquote'; import './MessageBody.scss'; interface Props { message: MessageExtended; /** * Needed for print message * true: (default) show button and collapse blockquote (if one founded) * false: don't show button, show full content */ showBlockquote?: boolean; } const MessageBody = ({ message: { document, plainText, data: message }, showBlockquote = true }: Props) => { const { state: expand, toggle } = useToggle(); const plain = isPlainText(message); const [content, blockquote] = useMemo(() => (plain ? [plainText as string, ''] : locateBlockquote(document)), [ document?.innerHTML, plain ]); return ( <div className={classnames(['message-content scroll-horizontal-if-needed bodyDecrypted', plain && 'plain'])}> <div dangerouslySetInnerHTML={{ __html: showBlockquote ? content : content + blockquote }} /> {showBlockquote && blockquote !== '' && ( <> <Button className="pm-button--small m0-5" onClick={toggle}> ... </Button> {expand && <div dangerouslySetInnerHTML={{ __html: blockquote }} />} </> )} </div> ); }; export default MessageBody;
import React, { useMemo } from 'react'; import { classnames, useToggle, Button } from 'react-components'; import { isPlainText } from '../../helpers/message/messages'; import { MessageExtended } from '../../models/message'; import { locateBlockquote } from '../../helpers/message/messageBlockquote'; import './MessageBody.scss'; interface Props { message: MessageExtended; /** * Needed for print message * true: (default) show button and collapse blockquote (if one founded) * false: don't show button, show full content */ showBlockquote?: boolean; } const MessageBody = ({ message: { document, plainText, data: message }, showBlockquote = true }: Props) => { const { state: expand, toggle } = useToggle(); const plain = isPlainText(message); const [content, blockquote] = useMemo(() => (plain ? [plainText as string, ''] : locateBlockquote(document)), [ document?.innerHTML, plain ]); return ( <div className={classnames([ 'message-content scroll-horizontal-if-needed relative bodyDecrypted', plain && 'plain' ])} > <div dangerouslySetInnerHTML={{ __html: showBlockquote ? content : content + blockquote }} /> {showBlockquote && blockquote !== '' && ( <> <Button className="pm-button--small m0-5" onClick={toggle}> ... </Button> {expand && <div dangerouslySetInnerHTML={{ __html: blockquote }} />} </> )} </div> ); }; export default MessageBody;
Fix - add relative class to message-content
Fix - add relative class to message-content
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -29,7 +29,12 @@ ]); return ( - <div className={classnames(['message-content scroll-horizontal-if-needed bodyDecrypted', plain && 'plain'])}> + <div + className={classnames([ + 'message-content scroll-horizontal-if-needed relative bodyDecrypted', + plain && 'plain' + ])} + > <div dangerouslySetInnerHTML={{ __html: showBlockquote ? content : content + blockquote }} /> {showBlockquote && blockquote !== '' && ( <>
91be7571aae9d60dd17fbd5a97311cb087996ab8
src/components/footer.ts
src/components/footer.ts
import Component from 'inferno-component' import h from 'inferno-hyperscript' interface Props { clearCompleted: () => void clearAll: () => void leftCount: number } interface State {} export default class Footer extends Component<Props, State> { render() { return h('div', [ h('span', `${this.props.leftCount} items left`), h('button', { onClick: this.props.clearCompleted }, 'Clear completed'), h('button', { onClick: this.props.clearAll }, 'Clear lll') ]) } }
import Component from 'inferno-component' import h from 'inferno-hyperscript' interface Props { clearCompleted: () => void clearAll: () => void leftCount: number } interface State {} export default class Footer extends Component<Props, State> { leftCountText(count: number): string { if (count === 1) { return `${count} item left` } else { return `${count} items left` } } render() { return h('div', [ h('span', this.leftCountText(this.props.leftCount)), h('button', { onClick: this.props.clearCompleted }, 'Clear completed'), h('button', { onClick: this.props.clearAll }, 'Clear lll') ]) } }
Tweak left count text in Footer component
Tweak left count text in Footer component
TypeScript
mit
y0za/typescript-inferno-todo,y0za/typescript-inferno-todo,y0za/typescript-inferno-todo
--- +++ @@ -9,9 +9,17 @@ interface State {} export default class Footer extends Component<Props, State> { + leftCountText(count: number): string { + if (count === 1) { + return `${count} item left` + } else { + return `${count} items left` + } + } + render() { return h('div', [ - h('span', `${this.props.leftCount} items left`), + h('span', this.leftCountText(this.props.leftCount)), h('button', { onClick: this.props.clearCompleted }, 'Clear completed'), h('button', { onClick: this.props.clearAll }, 'Clear lll') ])
3525b1fe0774448431b299a0efbed245fb9176b2
test/lib/mock-store.ts
test/lib/mock-store.ts
import { RecursiveProxyHandler } from 'electron-remote'; import { Store } from '../../src/lib/store'; import { Updatable } from '../../src/lib/updatable'; import { ChannelBase, User } from '../../src/lib/models/api-shapes'; export function createMockStore(seedData: any): Store { return RecursiveProxyHandler.create('mockStore', (names: Array<string>, params: Array<any>) => { const id = params[0]; const model = seedData[id]; switch (names[1]) { case 'channels': return new Updatable<ChannelBase>(() => Promise.resolve(model)); case 'users': return new Updatable<User>(() => Promise.resolve(model)); default: throw new Error(`${names[1]} not yet implemented in MockStore`); } }); }
import { Api } from '../../src/lib/models/slack-api'; import { ArrayUpdatable } from '../../src/lib/updatable'; import { ChannelBase, Message, User } from '../../src/lib/models/api-shapes'; import { EventType } from '../../src/lib/models/event-type'; import { SparseMap, InMemorySparseMap } from '../../src/lib/sparse-map'; import { Store, MessagesKey, MessageCollection } from '../../src/lib/store'; export interface MockStoreSeedData { channels?: { [key: string]: ChannelBase }; users?: { [key: string]: User }; joinedChannels?: Array<string>; } export class MockStore implements Store { api: Api[]; channels: SparseMap<string, ChannelBase>; users: SparseMap<string, User>; messages: SparseMap<MessagesKey, MessageCollection>; events: SparseMap<EventType, Message>; joinedChannels: ArrayUpdatable<string>; keyValueStore: SparseMap<string, any>; constructor(seedData: MockStoreSeedData) { this.channels = new InMemorySparseMap((id: string) => { return seedData.channels ? Promise.resolve(seedData.channels[id]) : Promise.reject(`No channel for ${id}`); }); this.users = new InMemorySparseMap((id: string) => { return seedData.users ? Promise.resolve(seedData.users[id]) : Promise.reject(`No user for ${id}`); }); this.joinedChannels = new ArrayUpdatable<string>(() => { return seedData.joinedChannels ? Promise.resolve(seedData.joinedChannels) : Promise.reject(`Missing joined channels`); }); } }
Rework MockStore to not be clever.
Rework MockStore to not be clever.
TypeScript
bsd-3-clause
paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline,paulcbetts/trickline
--- +++ @@ -1,21 +1,43 @@ -import { RecursiveProxyHandler } from 'electron-remote'; +import { Api } from '../../src/lib/models/slack-api'; +import { ArrayUpdatable } from '../../src/lib/updatable'; +import { ChannelBase, Message, User } from '../../src/lib/models/api-shapes'; +import { EventType } from '../../src/lib/models/event-type'; +import { SparseMap, InMemorySparseMap } from '../../src/lib/sparse-map'; +import { Store, MessagesKey, MessageCollection } from '../../src/lib/store'; -import { Store } from '../../src/lib/store'; -import { Updatable } from '../../src/lib/updatable'; -import { ChannelBase, User } from '../../src/lib/models/api-shapes'; +export interface MockStoreSeedData { + channels?: { [key: string]: ChannelBase }; + users?: { [key: string]: User }; + joinedChannels?: Array<string>; +} -export function createMockStore(seedData: any): Store { - return RecursiveProxyHandler.create('mockStore', (names: Array<string>, params: Array<any>) => { - const id = params[0]; - const model = seedData[id]; +export class MockStore implements Store { + api: Api[]; - switch (names[1]) { - case 'channels': - return new Updatable<ChannelBase>(() => Promise.resolve(model)); - case 'users': - return new Updatable<User>(() => Promise.resolve(model)); - default: - throw new Error(`${names[1]} not yet implemented in MockStore`); - } - }); + channels: SparseMap<string, ChannelBase>; + users: SparseMap<string, User>; + messages: SparseMap<MessagesKey, MessageCollection>; + events: SparseMap<EventType, Message>; + joinedChannels: ArrayUpdatable<string>; + keyValueStore: SparseMap<string, any>; + + constructor(seedData: MockStoreSeedData) { + this.channels = new InMemorySparseMap((id: string) => { + return seedData.channels ? + Promise.resolve(seedData.channels[id]) : + Promise.reject(`No channel for ${id}`); + }); + + this.users = new InMemorySparseMap((id: string) => { + return seedData.users ? + Promise.resolve(seedData.users[id]) : + Promise.reject(`No user for ${id}`); + }); + + this.joinedChannels = new ArrayUpdatable<string>(() => { + return seedData.joinedChannels ? + Promise.resolve(seedData.joinedChannels) : + Promise.reject(`Missing joined channels`); + }); + } }
4ff63dd1d58808598ae77fb72c4ff5496dd25a07
app/src/ui/branches/no-branches.tsx
app/src/ui/branches/no-branches.tsx
import * as React from 'react' import { Button } from '../lib/button' const BlankSlateImage = `file:///${__dirname}/static/empty-no-branches.svg` interface INoBranchesProps { readonly onCreateNewBranch: () => void } export class NoBranches extends React.Component<INoBranchesProps> { public render() { const shortcut = __DARWIN__ ? '⌘' : 'Ctrl' return ( <div className="no-branches"> <img src={BlankSlateImage} className="blankslate-image" /> <div className="title">Sorry, I can't find that branch</div> <div className="subtitle"> Do you want to create a new branch instead? </div> <Button className="create-branch-button" onClick={this.props.onCreateNewBranch} > {__DARWIN__ ? 'Create New Branch' : 'Create new branch'} </Button> <div className="protip"> ProTip! Press <kbd>{shortcut}</kbd> + <kbd>⇧</kbd> + <kbd>N</kbd> to quickly create a new branch from anywhere within the app </div> </div> ) } }
import * as React from 'react' import { Button } from '../lib/button' const BlankSlateImage = `file:///${__dirname}/static/empty-no-branches.svg` interface INoBranchesProps { readonly onCreateNewBranch: () => void } export class NoBranches extends React.Component<INoBranchesProps> { public render() { const shortcut = __DARWIN__ ? '⌘' : 'Ctrl' return ( <div className="no-branches"> <img src={BlankSlateImage} className="blankslate-image" /> <div className="title">Sorry, I can't find that branch</div> <div className="subtitle"> Do you want to create a new branch instead? </div> <Button className="create-branch-button" onClick={this.props.onCreateNewBranch} type="submit" > {__DARWIN__ ? 'Create New Branch' : 'Create new branch'} </Button> <div className="protip"> ProTip! Press <kbd>{shortcut}</kbd> + <kbd>⇧</kbd> + <kbd>N</kbd> to quickly create a new branch from anywhere within the app </div> </div> ) } }
Make it a blue button
Make it a blue button
TypeScript
mit
shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,say25/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,desktop/desktop,j-f1/forked-desktop,artivilla/desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,artivilla/desktop,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop
--- +++ @@ -23,6 +23,7 @@ <Button className="create-branch-button" onClick={this.props.onCreateNewBranch} + type="submit" > {__DARWIN__ ? 'Create New Branch' : 'Create new branch'} </Button>
0f5d99e55d0ae7ca25a87b9aaf896aaefeeda425
src/appInsightsClient.ts
src/appInsightsClient.ts
'use strict'; import * as vscode from 'vscode'; const appInsights = require("applicationinsights"); export class AppInsightsClient { private _client; private _enableAppInsights; constructor() { this._client = appInsights.getClient("a25ddf11-20fc-45c6-96ae-524f47754f28"); let config = vscode.workspace.getConfiguration('code-runner'); this._enableAppInsights = config.get<boolean>('enableAppInsights'); } public sendEvent(eventName: string): void { if (this._enableAppInsights) { this._client.trackEvent(eventName); } } }
'use strict'; import * as vscode from 'vscode'; const appInsights = require("applicationinsights"); export class AppInsightsClient { private _client; private _enableAppInsights; constructor() { this._client = appInsights.getClient('a25ddf11-20fc-45c6-96ae-524f47754f28'); let config = vscode.workspace.getConfiguration('code-runner'); this._enableAppInsights = config.get<boolean>('enableAppInsights'); } public sendEvent(eventName: string): void { if (this._enableAppInsights) { this._client.trackEvent(eventName === '' ? 'bat' : eventName); } } }
Handle tracking evernt for bat (the executor is '')
Handle tracking evernt for bat (the executor is '')
TypeScript
mit
formulahendry/vscode-code-runner
--- +++ @@ -8,14 +8,14 @@ private _enableAppInsights; constructor() { - this._client = appInsights.getClient("a25ddf11-20fc-45c6-96ae-524f47754f28"); + this._client = appInsights.getClient('a25ddf11-20fc-45c6-96ae-524f47754f28'); let config = vscode.workspace.getConfiguration('code-runner'); this._enableAppInsights = config.get<boolean>('enableAppInsights'); } public sendEvent(eventName: string): void { if (this._enableAppInsights) { - this._client.trackEvent(eventName); + this._client.trackEvent(eventName === '' ? 'bat' : eventName); } } }
2b7e1a93a88e238f9b51c77b402cbbca1010fab5
src/shared/components/query/filteredSearch/SearchBox.tsx
src/shared/components/query/filteredSearch/SearchBox.tsx
import * as React from 'react'; import { FunctionComponent, useEffect, useState } from 'react'; import { useDebounce } from 'shared/components/query/filteredSearch/useDebounce'; type SearchBoxProps = { queryString: string; onType: (changed: string) => void; }; export const SearchBox: FunctionComponent<SearchBoxProps> = props => { const [inputValue, setInputValue] = useState(props.queryString); const debouncedInput: string = useDebounce<string>(inputValue, 500); useEffect(() => { if (debouncedInput !== props.queryString) { props.onType(debouncedInput); } }, [debouncedInput]); useEffect(() => { setInputValue(props.queryString); }, [props.queryString]); return ( <> <input autoComplete="off" className="form-control" placeholder="Search..." type="text" value={inputValue} onChange={e => setInputValue(e.target.value)} style={{ width: '300px', }} /> </> ); };
import * as React from 'react'; import { FunctionComponent, useEffect, useState } from 'react'; import { useDebounce } from 'shared/components/query/filteredSearch/useDebounce'; type SearchBoxProps = { queryString: string; onType: (changed: string) => void; }; export const SearchBox: FunctionComponent<SearchBoxProps> = props => { const [inputValue, setInputValue] = useState(props.queryString); const debouncedInput: string = useDebounce<string>(inputValue, 500); useEffect(() => { if (debouncedInput !== props.queryString) { props.onType(debouncedInput); } }, [debouncedInput]); useEffect(() => { setInputValue(props.queryString); }, [props.queryString]); return ( <> <input autoComplete="off" spellCheck="false" className="form-control" placeholder="Search..." type="text" value={inputValue} onChange={e => setInputValue(e.target.value)} style={{ width: '300px', }} /> </> ); };
Disable spellchecking in search box
Disable spellchecking in search box
TypeScript
agpl-3.0
cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend
--- +++ @@ -25,6 +25,7 @@ <> <input autoComplete="off" + spellCheck="false" className="form-control" placeholder="Search..." type="text"
8f4361d61aaf82de5503a426456b5cf24096685a
bokehjs/src/coffee/core/util/dom.ts
bokehjs/src/coffee/core/util/dom.ts
import * as _ from "underscore"; export function createElement(type: string, props: { [name: string]: any }, ...children: (string | HTMLElement)[]): HTMLElement { let elem; if (type === "fragment") { elem = document.createDocumentFragment(); } else { elem = document.createElement(type); for (let k in props) { let v = props[k]; if (k === "className") k = "class"; if (k === "class" && _.isArray(v)) v = v.filter(c => c != null).join(" "); if (v == null || _.isBoolean(v) && v) continue elem.setAttribute(k, v); } } for (const v of children) { if (v instanceof HTMLElement) elem.appendChild(v); else if (_.isString(v)) elem.appendChild(document.createTextNode(v)) } return elem; }
import {isBoolean, isString, isArray, flatten} from "underscore"; export function createElement(type: string, props: { [name: string]: any }, ...children: Array<string | HTMLElement | Array<string | HTMLElement>>): HTMLElement { let elem; if (type === "fragment") { elem = document.createDocumentFragment(); } else { elem = document.createElement(type); for (let k in props) { let v = props[k]; if (k === "className") k = "class"; if (k === "class" && isArray(v)) v = v.filter(c => c != null).join(" "); if (v == null || isBoolean(v) && !v) continue elem.setAttribute(k, v); } } for (const v of flatten(children, true)) { if (v instanceof HTMLElement) elem.appendChild(v); else if (isString(v)) elem.appendChild(document.createTextNode(v)) } return elem; }
Handle children arrays (not ...) in createElement()
Handle children arrays (not ...) in createElement()
TypeScript
bsd-3-clause
schoolie/bokeh,draperjames/bokeh,percyfal/bokeh,bokeh/bokeh,draperjames/bokeh,percyfal/bokeh,jakirkham/bokeh,jakirkham/bokeh,DuCorey/bokeh,mindriot101/bokeh,bokeh/bokeh,dennisobrien/bokeh,mindriot101/bokeh,mindriot101/bokeh,aavanian/bokeh,draperjames/bokeh,timsnyder/bokeh,stonebig/bokeh,schoolie/bokeh,azjps/bokeh,jakirkham/bokeh,aiguofer/bokeh,rs2/bokeh,stonebig/bokeh,ericmjl/bokeh,aiguofer/bokeh,Karel-van-de-Plassche/bokeh,rs2/bokeh,schoolie/bokeh,azjps/bokeh,aavanian/bokeh,aavanian/bokeh,timsnyder/bokeh,percyfal/bokeh,philippjfr/bokeh,schoolie/bokeh,azjps/bokeh,philippjfr/bokeh,bokeh/bokeh,azjps/bokeh,aiguofer/bokeh,stonebig/bokeh,rs2/bokeh,percyfal/bokeh,ericmjl/bokeh,jakirkham/bokeh,timsnyder/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,stonebig/bokeh,aiguofer/bokeh,dennisobrien/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,bokeh/bokeh,aavanian/bokeh,timsnyder/bokeh,aavanian/bokeh,percyfal/bokeh,Karel-van-de-Plassche/bokeh,dennisobrien/bokeh,dennisobrien/bokeh,DuCorey/bokeh,bokeh/bokeh,philippjfr/bokeh,draperjames/bokeh,timsnyder/bokeh,draperjames/bokeh,philippjfr/bokeh,ericmjl/bokeh,DuCorey/bokeh,Karel-van-de-Plassche/bokeh,philippjfr/bokeh,schoolie/bokeh,aiguofer/bokeh,rs2/bokeh,dennisobrien/bokeh,DuCorey/bokeh,rs2/bokeh,DuCorey/bokeh,mindriot101/bokeh,jakirkham/bokeh,azjps/bokeh
--- +++ @@ -1,6 +1,7 @@ -import * as _ from "underscore"; +import {isBoolean, isString, isArray, flatten} from "underscore"; -export function createElement(type: string, props: { [name: string]: any }, ...children: (string | HTMLElement)[]): HTMLElement { +export function createElement(type: string, props: { [name: string]: any }, + ...children: Array<string | HTMLElement | Array<string | HTMLElement>>): HTMLElement { let elem; if (type === "fragment") { elem = document.createDocumentFragment(); @@ -10,18 +11,18 @@ let v = props[k]; if (k === "className") k = "class"; - if (k === "class" && _.isArray(v)) + if (k === "class" && isArray(v)) v = v.filter(c => c != null).join(" "); - if (v == null || _.isBoolean(v) && v) + if (v == null || isBoolean(v) && !v) continue elem.setAttribute(k, v); } } - for (const v of children) { + for (const v of flatten(children, true)) { if (v instanceof HTMLElement) elem.appendChild(v); - else if (_.isString(v)) + else if (isString(v)) elem.appendChild(document.createTextNode(v)) }
b7a6006a2df87d1d942683085066b787356685b8
src/controls/peripherals/peripheral_list.tsx
src/controls/peripherals/peripheral_list.tsx
import * as React from "react"; import { ToggleButton } from "../toggle_button"; import { pinToggle } from "../../devices/actions"; import { Row, Col } from "../../ui"; import { PeripheralListProps } from "./interfaces"; export function PeripheralList(props: PeripheralListProps) { return <div> {props.peripherals.map(p => { let status = JSON.stringify(props.pins[p.body.pin || 0]); return <Row> <Col xs={4}> <label>{p.body.label}</label> </Col> <Col xs={4}> <p>{p.body.pin}</p> </Col> <Col xs={4}> <ToggleButton toggleval={status} toggleAction={() => p.body.pin && pinToggle(p.body.pin)} /> </Col> </Row> })} </div> };
import * as React from "react"; import { ToggleButton } from "../toggle_button"; import { pinToggle } from "../../devices/actions"; import { Row, Col } from "../../ui"; import { PeripheralListProps } from "./interfaces"; export function PeripheralList(props: PeripheralListProps) { let { pins } = props; return <div> {props.peripherals.map(p => { let value = (pins[p.body.pin || -1] || { value: undefined }).value; return <Row> <Col xs={4}> <label>{p.body.label}</label> </Col> <Col xs={4}> <p>{p.body.pin}</p> </Col> <Col xs={4}> <ToggleButton toggleval={value} toggleAction={() => p.body.pin && pinToggle(p.body.pin)} /> </Col> </Row> })} </div> };
Change how pins are rendered
Change how pins are rendered
TypeScript
mit
RickCarlino/farmbot-web-frontend,FarmBot/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend,RickCarlino/farmbot-web-frontend,MrChristofferson/farmbot-web-frontend,FarmBot/farmbot-web-frontend
--- +++ @@ -5,9 +5,10 @@ import { PeripheralListProps } from "./interfaces"; export function PeripheralList(props: PeripheralListProps) { + let { pins } = props; return <div> {props.peripherals.map(p => { - let status = JSON.stringify(props.pins[p.body.pin || 0]); + let value = (pins[p.body.pin || -1] || { value: undefined }).value; return <Row> <Col xs={4}> <label>{p.body.label}</label> @@ -17,7 +18,7 @@ </Col> <Col xs={4}> <ToggleButton - toggleval={status} + toggleval={value} toggleAction={() => p.body.pin && pinToggle(p.body.pin)} /> </Col> </Row>
603b14630f8fc36f1c0312ac72be34842b0870b6
figma-plugin/src/server_requests.ts
figma-plugin/src/server_requests.ts
import { API, RETURN_OVERLAY_REQUEST, ExportOverlayRequest, setError, makePostData } from './helper' /** Method that sends the (decoded) fetched overlay, along with its * ID and display name. */ export async function sendOverlay(msg: ExportOverlayRequest) { const data: string = makePostData(msg); console.log("sending ", data) var request = new XMLHttpRequest() request.open('POST', API + "/result") request.onerror = () => { setError("Connection timed out. Please request the overlay again.") } request.send(data) } /** Method that requests the overlay ID to be fetched * from Android Studio plugin local server */ export function requestOverlayId() { var request = new XMLHttpRequest() request.open('GET', API + "/overlay_id") request.onload = () => { window.parent.postMessage({ pluginMessage: { type: RETURN_OVERLAY_REQUEST, id: request.response } }, '*') }; request.onerror = () => { setError("Connection timed out. Please request the overlay again.") } request.send() } /** This is a simple call to the local server * which stops the server. */ export function cancelOverlay() { var request = new XMLHttpRequest(); request.open('GET', API + "/cancel"); request.send(); }
import { API, RETURN_OVERLAY_REQUEST, ExportOverlayRequest, setError, makePostData } from './helper' /** Method that sends the (decoded) fetched overlay, along with its * ID and display name. */ export async function sendOverlay(msg: ExportOverlayRequest) { const data: string = makePostData(msg); console.log("sending ", data) var request = new XMLHttpRequest() request.open('POST', API + "/result") request.onerror = () => { setError("Connection timed out. Please request the overlay again.") } request.send(data) } /** Method that requests the overlay ID to be fetched * from Android Studio plugin local server */ export function requestOverlayId() { var request = new XMLHttpRequest() request.open('GET', API + "/overlay_id") request.onload = () => { window.parent.postMessage({ pluginMessage: { type: RETURN_OVERLAY_REQUEST, id: request.response } }, '*') }; request.onerror = () => { setError("Connection timed out. Please request the overlay again.") } request.send() } /** This is a simple call to the local server * which stops the server. */ export function cancelOverlay() { var request = new XMLHttpRequest(); request.open('GET', API + "/cancel"); request.send(); } /** This is a simple call to the local server * which stops the server,triggered * when the user manually closes the plugin */ export function manualCancelOverlay() { var request = new XMLHttpRequest(); request.open('GET', API + "/manual_cancel"); request.send(); }
Add method for manual cancellation of the plugin.
Add method for manual cancellation of the plugin. bug: 106757419 Change-Id: I5e64848eba4ba29fcc500d882e5391109d965f35
TypeScript
apache-2.0
googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay,googleinterns/android-studio-figma-overlay
--- +++ @@ -37,3 +37,12 @@ request.open('GET', API + "/cancel"); request.send(); } + +/** This is a simple call to the local server + * which stops the server,triggered + * when the user manually closes the plugin */ +export function manualCancelOverlay() { + var request = new XMLHttpRequest(); + request.open('GET', API + "/manual_cancel"); + request.send(); +}
df64e5bcfccbe3829e6fdcfa9849dccba5b7c1df
src/Apps/Search/Routes/Artworks/index.tsx
src/Apps/Search/Routes/Artworks/index.tsx
import { Box } from "@artsy/palette" import { AnalyticsSchema, useTracking } from "Artsy/Analytics" import { Location } from "found" import React from "react" import { ArtworkFilter_viewer } from "__generated__/ArtworkFilter_viewer.graphql" import { ZeroState } from "Apps/Search/Components/ZeroState" import { ArtworkFilter } from "Components/v2/ArtworkFilter" import { updateUrl } from "Components/v2/ArtworkFilter/Utils/urlBuilder" interface SearchResultsRouteProps { viewer: ArtworkFilter_viewer location: Location } export const SearchResultsArtworksRoute: React.FC< SearchResultsRouteProps > = props => { const tracking = useTracking() return ( <Box pt={2}> <ArtworkFilter viewer={props.viewer} filters={props.location.query as any} onChange={updateUrl} onFilterClick={(key, value, filterState) => { tracking.trackEvent({ action_type: AnalyticsSchema.ActionType.CommercialFilterParamsChanged, changed: { [key]: value }, current: filterState, }) }} ZeroState={ZeroState} /> </Box> ) }
import { Box } from "@artsy/palette" import { AnalyticsSchema, useTracking } from "Artsy/Analytics" import { Location } from "found" import React from "react" import { ArtworkFilter_viewer } from "__generated__/ArtworkFilter_viewer.graphql" import { ZeroState } from "Apps/Search/Components/ZeroState" import { ArtworkFilter } from "Components/v2/ArtworkFilter" import { updateUrl } from "Components/v2/ArtworkFilter/Utils/urlBuilder" interface SearchResultsRouteProps { viewer: ArtworkFilter_viewer location: Location } export const SearchResultsArtworksRoute: React.FC< SearchResultsRouteProps > = props => { const tracking = useTracking() return ( <Box pt={2}> <ArtworkFilter viewer={props.viewer} filters={props.location.query} onChange={updateUrl} onArtworkBrickClick={(artwork, artworkBrickProps) => { tracking.trackEvent({ action_type: AnalyticsSchema.ActionType.SelectedItemFromSearchPage, query: artworkBrickProps.term, item_type: "Artwork", item_id: artwork.id, destination_path: artwork.href, }) }} onFilterClick={(key, value, filterState) => { tracking.trackEvent({ action_type: AnalyticsSchema.ActionType.CommercialFilterParamsChanged, changed: { [key]: value }, current: filterState, }) }} ZeroState={ZeroState} /> </Box> ) }
Fix analytics event on /search
[Bugfix] Fix analytics event on /search
TypeScript
mit
artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,artsy/reaction
--- +++ @@ -22,8 +22,17 @@ <Box pt={2}> <ArtworkFilter viewer={props.viewer} - filters={props.location.query as any} + filters={props.location.query} onChange={updateUrl} + onArtworkBrickClick={(artwork, artworkBrickProps) => { + tracking.trackEvent({ + action_type: AnalyticsSchema.ActionType.SelectedItemFromSearchPage, + query: artworkBrickProps.term, + item_type: "Artwork", + item_id: artwork.id, + destination_path: artwork.href, + }) + }} onFilterClick={(key, value, filterState) => { tracking.trackEvent({ action_type:
0ef821d0c9be3170dd8094bb5a4dc78e2111b301
src/extra/DeepPartial.ts
src/extra/DeepPartial.ts
/** * Version of TypeScript's `Partial` type that considers nested properties as optional too, recursively. * * FIXME This type undermines type safety, e.g. the compiler will not check function signatures. An eye must be kept on * https://github.com/Microsoft/TypeScript/issues/12424. */ export type DeepPartial<T> = { [P in keyof T]?: T[P] | DeepPartial<T[P]> }
/** * Version of TypeScript's `Partial` type that considers nested properties as optional too, recursively. * * FIXME This type undermines type safety, e.g. the compiler will not check function signatures. An eye must be kept on * https://github.com/Microsoft/TypeScript/issues/12424. * * TODO Consider the alternative proposed in https://github.com/Microsoft/TypeScript/issues/12424. */ export type DeepPartial<T> = { [P in keyof T]?: T[P] | DeepPartial<T[P]> }
Add link to alternative implementation
Add link to alternative implementation
TypeScript
agpl-3.0
inad9300/Soil,inad9300/Soil
--- +++ @@ -3,6 +3,8 @@ * * FIXME This type undermines type safety, e.g. the compiler will not check function signatures. An eye must be kept on * https://github.com/Microsoft/TypeScript/issues/12424. + * + * TODO Consider the alternative proposed in https://github.com/Microsoft/TypeScript/issues/12424. */ export type DeepPartial<T> = { [P in keyof T]?: T[P] | DeepPartial<T[P]>
17e0ce594a81a88f37fabcc39cea6ee2ddb2db29
src/app/recipe.service.ts
src/app/recipe.service.ts
import { Injectable } from '@angular/core'; import { Recipe } from './recipe'; import { RECIPES } from './mock-recipes' @Injectable() export class RecipeService { constructor() { } getRecipes(): Promise<Recipe[]> { return Promise.resolve(RECIPES); } getRecipe(id: number): Promise<Recipe> { return this.getRecipes() .then(recipes => recipes.find(recipe => recipe.id === id)); } }
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import { Recipe } from './recipe'; import 'rxjs/add/operator/toPromise'; @Injectable() export class RecipeService { private recipesUrl = '/api/recipes'; constructor(private http: Http) { } getRecipes(): Promise<Recipe[]> { return this.http.get(this.recipesUrl) .toPromise() .then(response => response.json() as Recipe[]) .catch(this.handleError); } getRecipe(id: number): Promise<Recipe> { const url = `${this.recipesUrl}/${id}`; return this.http.get(url) .toPromise() .then(response => response.json() as Recipe) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
Read recipes from web API
Read recipes from web API
TypeScript
mpl-2.0
mkozina/cookbook,mkozina/cookbook,mkozina/cookbook
--- +++ @@ -1,20 +1,35 @@ import { Injectable } from '@angular/core'; +import { Headers, Http } from '@angular/http'; import { Recipe } from './recipe'; -import { RECIPES } from './mock-recipes' + +import 'rxjs/add/operator/toPromise'; @Injectable() export class RecipeService { - constructor() { } + private recipesUrl = '/api/recipes'; + + constructor(private http: Http) { } getRecipes(): Promise<Recipe[]> { - return Promise.resolve(RECIPES); + return this.http.get(this.recipesUrl) + .toPromise() + .then(response => response.json() as Recipe[]) + .catch(this.handleError); } getRecipe(id: number): Promise<Recipe> { - return this.getRecipes() - .then(recipes => recipes.find(recipe => recipe.id === id)); + const url = `${this.recipesUrl}/${id}`; + return this.http.get(url) + .toPromise() + .then(response => response.json() as Recipe) + .catch(this.handleError); + } + + private handleError(error: any): Promise<any> { + console.error('An error occurred', error); + return Promise.reject(error.message || error); } }
f794cf4dead09652eae471fd751260dad97bb0a7
types/detox/test/detox-jest-setup-tests.ts
types/detox/test/detox-jest-setup-tests.ts
declare var beforeAll: (callback: () => void) => void; declare var beforeEach: (callback: () => void) => void; declare var afterAll: (callback: () => void) => void; import adapter from "detox/runners/jest/adapter"; // Normally the Detox configuration from the project's package.json like so: // const config = require("./package.json").detox; declare const config: any; declare const jasmine: any; jasmine.getEnv().addReporter(adapter); beforeAll(async () => { await detox.init(config); const initOptions: Detox.DetoxInitOptions = { initGlobals: false, launchApp: false, }; await detox.init(config, initOptions); }); beforeEach(async () => { await adapter.beforeEach(); }); afterAll(async () => { await adapter.afterAll(); await detox.cleanup(); });
declare var beforeAll: (callback: () => void) => void; declare var beforeEach: (callback: () => void) => void; declare var afterAll: (callback: () => void) => void; import defaultDetox from "detox"; import adapter from "detox/runners/jest/adapter"; // Normally the Detox configuration from the project's package.json like so: // const config = require("./package.json").detox; declare const config: any; declare const jasmine: any; jasmine.getEnv().addReporter(adapter); beforeAll(async () => { await detox.init(config); const initOptions: Detox.DetoxInitOptions = { initGlobals: false, launchApp: false, }; await defaultDetox.init(config, initOptions); }); beforeEach(async () => { await adapter.beforeEach(); }); afterAll(async () => { await adapter.afterAll(); await detox.cleanup(); });
Add test for importing default export
[detox] Add test for importing default export
TypeScript
mit
dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped
--- +++ @@ -2,6 +2,7 @@ declare var beforeEach: (callback: () => void) => void; declare var afterAll: (callback: () => void) => void; +import defaultDetox from "detox"; import adapter from "detox/runners/jest/adapter"; // Normally the Detox configuration from the project's package.json like so: @@ -18,7 +19,7 @@ initGlobals: false, launchApp: false, }; - await detox.init(config, initOptions); + await defaultDetox.init(config, initOptions); }); beforeEach(async () => {
c73b9be174158c16f674d25c078cd0534dacfa98
src/vs/editor/contrib/codeAction/codeActionContributions.ts
src/vs/editor/contrib/codeAction/codeActionContributions.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { registerEditorAction, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { CodeActionCommand, OrganizeImportsAction, QuickFixAction, QuickFixController, RefactorAction, SourceAction, AutoFixAction } from 'vs/editor/contrib/codeAction/codeActionCommands'; registerEditorContribution(QuickFixController); registerEditorAction(QuickFixAction); registerEditorAction(RefactorAction); registerEditorAction(SourceAction); registerEditorAction(OrganizeImportsAction); registerEditorAction(AutoFixAction); registerEditorCommand(new CodeActionCommand());
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { registerEditorAction, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; import { CodeActionCommand, OrganizeImportsAction, QuickFixAction, QuickFixController, RefactorAction, SourceAction, AutoFixAction, FixAllAction } from 'vs/editor/contrib/codeAction/codeActionCommands'; registerEditorContribution(QuickFixController); registerEditorAction(QuickFixAction); registerEditorAction(RefactorAction); registerEditorAction(SourceAction); registerEditorAction(OrganizeImportsAction); registerEditorAction(AutoFixAction); registerEditorAction(FixAllAction); registerEditorCommand(new CodeActionCommand());
Fix all action not registered
Fix all action not registered https://github.com/Microsoft/vscode-typescript-tslint-plugin/issues/81
TypeScript
mit
Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,joaomoreno/vscode,the-ress/vscode,the-ress/vscode,Microsoft/vscode,joaomoreno/vscode,hoovercj/vscode,joaomoreno/vscode,the-ress/vscode,eamodio/vscode,microsoft/vscode,joaomoreno/vscode,hoovercj/vscode,hoovercj/vscode,joaomoreno/vscode,eamodio/vscode,mjbvz/vscode,the-ress/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,joaomoreno/vscode,mjbvz/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,mjbvz/vscode,joaomoreno/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,eamodio/vscode,the-ress/vscode,hoovercj/vscode,mjbvz/vscode,joaomoreno/vscode,joaomoreno/vscode,eamodio/vscode,the-ress/vscode,hoovercj/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,joaomoreno/vscode,Microsoft/vscode,joaomoreno/vscode,Microsoft/vscode,Microsoft/vscode,hoovercj/vscode,mjbvz/vscode,eamodio/vscode,eamodio/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,microsoft/vscode,joaomoreno/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,mjbvz/vscode,the-ress/vscode,microsoft/vscode,microsoft/vscode,Microsoft/vscode,hoovercj/vscode,joaomoreno/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,Microsoft/vscode,hoovercj/vscode,mjbvz/vscode,mjbvz/vscode,hoovercj/vscode,microsoft/vscode,microsoft/vscode,the-ress/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,hoovercj/vscode,eamodio/vscode,joaomoreno/vscode,the-ress/vscode,mjbvz/vscode,the-ress/vscode,eamodio/vscode,hoovercj/vscode,the-ress/vscode,mjbvz/vscode,hoovercj/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,eamodio/vscode,microsoft/vscode,mjbvz/vscode,microsoft/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,mjbvz/vscode,the-ress/vscode,Microsoft/vscode,hoovercj/vscode,Microsoft/vscode
--- +++ @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { registerEditorAction, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions'; -import { CodeActionCommand, OrganizeImportsAction, QuickFixAction, QuickFixController, RefactorAction, SourceAction, AutoFixAction } from 'vs/editor/contrib/codeAction/codeActionCommands'; +import { CodeActionCommand, OrganizeImportsAction, QuickFixAction, QuickFixController, RefactorAction, SourceAction, AutoFixAction, FixAllAction } from 'vs/editor/contrib/codeAction/codeActionCommands'; registerEditorContribution(QuickFixController); @@ -13,4 +13,5 @@ registerEditorAction(SourceAction); registerEditorAction(OrganizeImportsAction); registerEditorAction(AutoFixAction); +registerEditorAction(FixAllAction); registerEditorCommand(new CodeActionCommand());
9094ea1d86dd3e3134d69dce0c3c5038031d2cd3
app/src/ui/repository-settings/git-ignore.tsx
app/src/ui/repository-settings/git-ignore.tsx
import * as React from 'react' import { DialogContent } from '../dialog' import { TextArea } from '../lib/text-area' import { LinkButton } from '../lib/link-button' interface IGitIgnoreProps { readonly text: string | null readonly isDefaultBranch: boolean readonly onIgnoreTextChanged: (text: string) => void readonly onShowExamples: () => void } /** A view for creating or modifying the repository's gitignore file */ export class GitIgnore extends React.Component<IGitIgnoreProps, {}> { private renderBranchWarning(): JSX.Element | null { if (this.props.isDefaultBranch) { return null } return ( <p> You are not on the default branch, so changes here may not be applied to the repository when you switch branches. </p> ) } public render() { return ( <DialogContent> <p> The .gitignore file controls which files are tracked by Git and which are ignored. Check out{' '} <LinkButton onClick={this.props.onShowExamples}> git-scm.com </LinkButton>{' '} for more information about the file format, or simply ignore a file by right clicking on it in the uncommitted changes view. </p> {this.renderBranchWarning()} <TextArea placeholder="Ignored files" value={this.props.text || ''} onValueChanged={this.props.onIgnoreTextChanged} rows={6} /> </DialogContent> ) } }
import * as React from 'react' import { DialogContent } from '../dialog' import { TextArea } from '../lib/text-area' import { LinkButton } from '../lib/link-button' interface IGitIgnoreProps { readonly text: string | null readonly isDefaultBranch: boolean readonly onIgnoreTextChanged: (text: string) => void readonly onShowExamples: () => void } /** A view for creating or modifying the repository's gitignore file */ export class GitIgnore extends React.Component<IGitIgnoreProps, {}> { private renderBranchWarning(): JSX.Element | null { if (this.props.isDefaultBranch) { return null } return ( <p> You are not on the default branch, changes here will only be stored locally on this branch. </p> ) } public render() { return ( <DialogContent> <p> The .gitignore file controls which files are tracked by Git and which are ignored. Check out{' '} <LinkButton onClick={this.props.onShowExamples}> git-scm.com </LinkButton>{' '} for more information about the file format, or simply ignore a file by right clicking on it in the uncommitted changes view. </p> {this.renderBranchWarning()} <TextArea placeholder="Ignored files" value={this.props.text || ''} onValueChanged={this.props.onIgnoreTextChanged} rows={6} /> </DialogContent> ) } }
Update message to state changes will only be stored on the current branch
Update message to state changes will only be stored on the current branch
TypeScript
mit
kactus-io/kactus,artivilla/desktop,shiftkey/desktop,say25/desktop,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,say25/desktop,say25/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,desktop/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,say25/desktop
--- +++ @@ -19,8 +19,8 @@ return ( <p> - You are not on the default branch, so changes here may not be applied to - the repository when you switch branches. + You are not on the default branch, changes here will only be stored + locally on this branch. </p> ) }
64bbfb53bf127469ba4eda285b2fdf90fea4d9d3
src/pipes/stationName.ts
src/pipes/stationName.ts
import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'stationName', //pure: false // needed to react to array changes }) @Injectable() export class StationName implements PipeTransform { public transform(station: any, showNumber: boolean): string { let nameWithoutNumber = station.name.replace(/[0-9]+ *- */, ''); if (showNumber) { return `${nameWithoutNumber} (${station.number})`; } else { return nameWithoutNumber; } } }
import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'stationName', //pure: false // needed to react to array changes }) @Injectable() export class StationName implements PipeTransform { public transform(station: any, showNumber: boolean): string { let nameWithoutNumber = station.name.replace(/[0-9]+ *- */, ''); if (showNumber) { return `${nameWithoutNumber} (no. ${station.number})`; } else { return nameWithoutNumber; } } }
Add no. to station display name
Add no. to station display name
TypeScript
mit
255kb/city-bike-routes,255kb/city-bike-routes,255kb/city-bike-routes
--- +++ @@ -9,7 +9,7 @@ public transform(station: any, showNumber: boolean): string { let nameWithoutNumber = station.name.replace(/[0-9]+ *- */, ''); if (showNumber) { - return `${nameWithoutNumber} (${station.number})`; + return `${nameWithoutNumber} (no. ${station.number})`; } else { return nameWithoutNumber; }
6d34f3761e3a355d7327f142c9984ba8bf4afcd1
src/server_manager/infrastructure/crypto.ts
src/server_manager/infrastructure/crypto.ts
// Copyright 2018 The Outline Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as forge from 'node-forge'; // Keys are in OpenSSH format export class KeyPair { public: string; private: string; } // Generates an RSA keypair using forge export function generateKeyPair(): Promise<KeyPair> { return new Promise((resolve, reject) => { forge.pki.rsa.generateKeyPair({bits: 3072, workers: -1}, (forgeError, keypair) => { if (forgeError) { reject(`Failed to generate SSH key: ${forgeError}`); } // trim() the string because forge adds a trailing space to // public keys which really messes things up later. resolve({ public: forge.ssh.publicKeyToOpenSSH(keypair.publicKey, '').trim(), private: forge.ssh.privateKeyToOpenSSH(keypair.privateKey, '').trim() }); }); }); }
// Copyright 2018 The Outline Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as forge from 'node-forge'; // Keys are in OpenSSH format export class KeyPair { public: string; private: string; } // Generates an RSA keypair using forge export function generateKeyPair(): Promise<KeyPair> { return new Promise((resolve, reject) => { forge.pki.rsa.generateKeyPair({bits: 4096, workers: -1}, (forgeError, keypair) => { if (forgeError) { reject(`Failed to generate SSH key: ${forgeError}`); } // trim() the string because forge adds a trailing space to // public keys which really messes things up later. resolve({ public: forge.ssh.publicKeyToOpenSSH(keypair.publicKey, '').trim(), private: forge.ssh.privateKeyToOpenSSH(keypair.privateKey, '').trim() }); }); }); }
Increase key sized to 4096.
Increase key sized to 4096.
TypeScript
apache-2.0
Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server,Jigsaw-Code/outline-server
--- +++ @@ -23,7 +23,7 @@ // Generates an RSA keypair using forge export function generateKeyPair(): Promise<KeyPair> { return new Promise((resolve, reject) => { - forge.pki.rsa.generateKeyPair({bits: 3072, workers: -1}, (forgeError, keypair) => { + forge.pki.rsa.generateKeyPair({bits: 4096, workers: -1}, (forgeError, keypair) => { if (forgeError) { reject(`Failed to generate SSH key: ${forgeError}`); }
02ff5f70ab2c134aee031596fa575ee78ac1ed88
tests/helpers.ts
tests/helpers.ts
import fs from 'fs-extra'; import { PixelDiffer } from 'mugshot'; import { dirname, join } from 'path'; /** * Use PixelDiffer to compare two screenshots. * * Assume that PixelDiffer passes all of its tests. */ export async function expectIdenticalScreenshots( screenshot: Buffer | string, baselinePath: string ) { if (!(await fs.pathExists(baselinePath)) && typeof screenshot !== 'string') { await fs.mkdirp(dirname(baselinePath)); await fs.writeFile(baselinePath, screenshot); throw new Error(`${baselinePath} didn't exist so I wrote a new one.`); } const baseline = await fs.readFile(baselinePath); if (typeof screenshot === 'string') { // eslint-disable-next-line no-param-reassign screenshot = await fs.readFile(screenshot); } const differ = new PixelDiffer({ threshold: 0 }); const result = await differ.compare(baseline, screenshot); if (!result.matches) { const tmpPath = await fs.mkdtemp(`/tmp/`); const diffPath = join(tmpPath, 'diff.png'); const actualPath = join(tmpPath, 'actual.png'); await fs.writeFile(diffPath, result.diff); await fs.writeFile(actualPath, screenshot); throw new Error( `Screenshot didn't match ${baselinePath}. Diff was written at ${diffPath}, actual was written at ${actualPath}` ); } }
import fs from 'fs-extra'; import { PixelDiffer } from 'mugshot'; import { dirname, join } from 'path'; /** * Use PixelDiffer to compare two screenshots. * * Assume that PixelDiffer passes all of its tests. */ export async function expectIdenticalScreenshots( screenshot: Buffer, baselinePath: string ) { if (!(await fs.pathExists(baselinePath))) { await fs.mkdirp(dirname(baselinePath)); await fs.writeFile(baselinePath, screenshot); throw new Error(`${baselinePath} didn't exist so I wrote a new one.`); } const baseline = await fs.readFile(baselinePath); const differ = new PixelDiffer({ threshold: 0 }); const result = await differ.compare(baseline, screenshot); if (!result.matches) { const tmpPath = await fs.mkdtemp(`/tmp/`); const diffPath = join(tmpPath, 'diff.png'); const actualPath = join(tmpPath, 'actual.png'); await fs.writeFile(diffPath, result.diff); await fs.writeFile(actualPath, screenshot); throw new Error( `Screenshot didn't match ${baselinePath}. Diff was written at ${diffPath}, actual was written at ${actualPath}` ); } }
Remove support for reading screenshots
test: Remove support for reading screenshots This is an artifact of old ways of writing tests.
TypeScript
mit
uberVU/mugshot,uberVU/mugshot
--- +++ @@ -8,10 +8,10 @@ * Assume that PixelDiffer passes all of its tests. */ export async function expectIdenticalScreenshots( - screenshot: Buffer | string, + screenshot: Buffer, baselinePath: string ) { - if (!(await fs.pathExists(baselinePath)) && typeof screenshot !== 'string') { + if (!(await fs.pathExists(baselinePath))) { await fs.mkdirp(dirname(baselinePath)); await fs.writeFile(baselinePath, screenshot); @@ -19,11 +19,6 @@ } const baseline = await fs.readFile(baselinePath); - - if (typeof screenshot === 'string') { - // eslint-disable-next-line no-param-reassign - screenshot = await fs.readFile(screenshot); - } const differ = new PixelDiffer({ threshold: 0 }); const result = await differ.compare(baseline, screenshot);
c8bcc3cf8d7c7635e29833bffed5ae717c4aa771
src/Styleguide/Components/MarketInsights.tsx
src/Styleguide/Components/MarketInsights.tsx
import React from "react" import { Responsive } from "../Utils/Responsive" import { BorderBox } from "../Elements/Box" import { Sans } from "@artsy/palette" import { themeGet } from "styled-system" import styled from "styled-components" const TextWrap = styled.div` display: block; @media ${themeGet("mediaQueries.xs")} { display: flex; flex-direction: column; margin-bottom: 10px; } ` export interface MarketInsight { primaryLabel: string secondaryLabel: string } export interface MarketInsightsProps { insights: MarketInsight[] } export class MarketInsights extends React.Component<MarketInsightsProps> { render() { return ( <Responsive> {({ xs }) => { return ( <BorderBox flexDirection="column"> {this.props.insights.map(insight => { return ( <TextWrap> <Sans size="2" weight="medium" display="inline" mr={3}> {insight.primaryLabel} </Sans> <Sans size="2" display="inline" color="black60"> {insight.secondaryLabel} </Sans> </TextWrap> ) })} </BorderBox> ) }} </Responsive> ) } }
import React from "react" import { Responsive } from "../Utils/Responsive" import { Box, BorderBox } from "../Elements/Box" import { Flex } from "../Elements/Flex" import { Sans } from "@artsy/palette" const wrapper = xs => props => xs ? <Flex flexDirection="column" mb={3} {...props} /> : <Box {...props} /> export interface MarketInsight { primaryLabel: string secondaryLabel: string } export interface MarketInsightsProps { insights: MarketInsight[] } export class MarketInsights extends React.Component<MarketInsightsProps> { render() { return ( <BorderBox flexDirection="column"> <Responsive> {({ xs }) => { const TextWrap = wrapper(xs) return this.props.insights.map(insight => { return ( <TextWrap> <Sans size="2" weight="medium" display="inline" mr={3}> {insight.primaryLabel} k{" "} </Sans> <Sans size="2" display="inline" color="black60"> {insight.secondaryLabel} </Sans> </TextWrap> ) }) }} </Responsive> </BorderBox> ) } }
Update market insights to be RN safe(r)
Update market insights to be RN safe(r)
TypeScript
mit
artsy/reaction,artsy/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction-force
--- +++ @@ -1,19 +1,11 @@ import React from "react" import { Responsive } from "../Utils/Responsive" -import { BorderBox } from "../Elements/Box" +import { Box, BorderBox } from "../Elements/Box" +import { Flex } from "../Elements/Flex" import { Sans } from "@artsy/palette" -import { themeGet } from "styled-system" -import styled from "styled-components" -const TextWrap = styled.div` - display: block; - - @media ${themeGet("mediaQueries.xs")} { - display: flex; - flex-direction: column; - margin-bottom: 10px; - } -` +const wrapper = xs => props => + xs ? <Flex flexDirection="column" mb={3} {...props} /> : <Box {...props} /> export interface MarketInsight { primaryLabel: string @@ -27,26 +19,26 @@ export class MarketInsights extends React.Component<MarketInsightsProps> { render() { return ( - <Responsive> - {({ xs }) => { - return ( - <BorderBox flexDirection="column"> - {this.props.insights.map(insight => { - return ( - <TextWrap> - <Sans size="2" weight="medium" display="inline" mr={3}> - {insight.primaryLabel} - </Sans> - <Sans size="2" display="inline" color="black60"> - {insight.secondaryLabel} - </Sans> - </TextWrap> - ) - })} - </BorderBox> - ) - }} - </Responsive> + <BorderBox flexDirection="column"> + <Responsive> + {({ xs }) => { + const TextWrap = wrapper(xs) + return this.props.insights.map(insight => { + return ( + <TextWrap> + <Sans size="2" weight="medium" display="inline" mr={3}> + {insight.primaryLabel} + k{" "} + </Sans> + <Sans size="2" display="inline" color="black60"> + {insight.secondaryLabel} + </Sans> + </TextWrap> + ) + }) + }} + </Responsive> + </BorderBox> ) } }
5a51e25de97eb29a0e876a218c10e0a121b3f4f3
tests/cases/fourslash/formattingCrash.ts
tests/cases/fourslash/formattingCrash.ts
/// <reference path='fourslash.ts' /> /////**/module Default{ ////} format.setOption("PlaceOpenBraceOnNewLineForFunctions", true); format.setOption("PlaceOpenBraceOnNewLineForControlBlocks", true); format.document(); goTo.marker(); verify.currentLineContentIs('module Default');
/// <reference path='fourslash.ts' /> /////**/module Default{ ////} format.setOption("PlaceOpenBraceOnNewLineForFunctions", true); format.setOption("PlaceOpenBraceOnNewLineForControlBlocks", true); format.document(); goTo.marker(); verify.currentLineContentIs('module Default');
Test for crash in formatter
Test for crash in formatter
TypeScript
apache-2.0
mbebenita/shumway.ts,hippich/typescript,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,popravich/typescript,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,mbrowne/typescript-dci,mbebenita/shumway.ts,hippich/typescript,popravich/typescript,popravich/typescript,fdecampredon/jsx-typescript-old-version,mbrowne/typescript-dci,mbebenita/shumway.ts,hippich/typescript
ebbecca947ceb17067a6dee9e97411a2299ba538
test/push-pop.test.ts
test/push-pop.test.ts
import { Expect, TestCase } from "alsatian"; import { Stack } from "../stack"; export class PushPopTestFixture { @TestCase(15) @TestCase(20) @TestCase("some string") @TestCase("another string") @TestCase(false) @TestCase(true) @TestCase(1.25) public afterPushPopShouldReturnValue(value: any) { let stack = new Stack(); stack.push(value); let popped = stack.pop(); Expect(popped).toBe(value); } }
import { Expect, TestCase } from "alsatian"; import { Stack } from "../stack"; export class PushPopTestFixture { @TestCase(15) @TestCase(20) @TestCase("some string") @TestCase("another string") @TestCase(false) @TestCase(true) @TestCase(1.25) public afterPushPopShouldReturnValue(value: any) { let stack = new Stack(); stack.push(value); let popped = stack.pop(); Expect(popped).toBe(value); } @TestCase(15) @TestCase(20) @TestCase("some string") @TestCase("another string") @TestCase(false) @TestCase(true) @TestCase(1.25) public afterPushPopShouldReturnTopValue(value: any) { let stack = new Stack(); // push some junk to the stack stack.push(5); stack.push(10); stack.push(value); let popped = stack.pop(); Expect(popped).toBe(value); } }
Test that pop gets the top
Test that pop gets the top
TypeScript
mit
ts-data/stack
--- +++ @@ -20,4 +20,25 @@ Expect(popped).toBe(value); } + @TestCase(15) + @TestCase(20) + @TestCase("some string") + @TestCase("another string") + @TestCase(false) + @TestCase(true) + @TestCase(1.25) + public afterPushPopShouldReturnTopValue(value: any) { + let stack = new Stack(); + + // push some junk to the stack + stack.push(5); + stack.push(10); + + stack.push(value); + + let popped = stack.pop(); + + Expect(popped).toBe(value); + } + }
0b52e3275f2b3b586f0fb29c4a06709164d1b57a
components/responsive-dimensions/responsive-dimensions-directive.ts
components/responsive-dimensions/responsive-dimensions-directive.ts
import { Directive, Inject, Input, OnChanges, SimpleChanges } from 'ng-metadata/core'; import { Screen } from './../screen/screen-service'; import { Ruler } from './../ruler/ruler-service'; @Directive({ selector: '[gj-responsive-dimensions]', }) export class ResponsiveDimensionsDirective implements OnChanges { @Input( '<responsiveDimensionsRatio' ) ratio: number; element: HTMLImageElement; constructor( @Inject( '$element' ) $element: ng.IAugmentedJQuery, @Inject( '$scope' ) private $scope: ng.IScope, @Inject( 'Screen' ) screen: Screen, @Inject( 'Ruler' ) private ruler: Ruler, ) { this.element = $element[0] as HTMLImageElement; screen.setResizeSpy( $scope, () => this.updateDimensions() ); } ngOnChanges( changes: SimpleChanges ) { if ( changes['ratio'] ) { this.updateDimensions(); } } private updateDimensions() { this.$scope.$applyAsync( () => { const containerWidth = this.ruler.width( this.element.parentNode as HTMLElement ); this.element.style.height = `${containerWidth / this.ratio}px`; } ); } }
import { Directive, Inject, Input, OnChanges, SimpleChanges } from 'ng-metadata/core'; import { Screen } from './../screen/screen-service'; import { Ruler } from './../ruler/ruler-service'; @Directive({ selector: '[gj-responsive-dimensions]', }) export class ResponsiveDimensionsDirective implements OnChanges { @Input( '<responsiveDimensionsRatio' ) ratio: number; element: HTMLImageElement; constructor( @Inject( '$element' ) $element: ng.IAugmentedJQuery, @Inject( '$scope' ) $scope: ng.IScope, @Inject( 'Screen' ) screen: Screen, @Inject( 'Ruler' ) private ruler: Ruler, ) { this.element = $element[0] as HTMLImageElement; screen.setResizeSpy( $scope, () => this.updateDimensions() ); } ngOnChanges( changes: SimpleChanges ) { if ( changes['ratio'] ) { this.updateDimensions(); } } private updateDimensions() { const containerWidth = this.ruler.width( this.element.parentNode as HTMLElement ); this.element.style.height = `${containerWidth / this.ratio}px`; } }
Make responsive dimensions happen immediately.
Make responsive dimensions happen immediately.
TypeScript
mit
gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib
--- +++ @@ -13,7 +13,7 @@ constructor( @Inject( '$element' ) $element: ng.IAugmentedJQuery, - @Inject( '$scope' ) private $scope: ng.IScope, + @Inject( '$scope' ) $scope: ng.IScope, @Inject( 'Screen' ) screen: Screen, @Inject( 'Ruler' ) private ruler: Ruler, ) @@ -31,10 +31,7 @@ private updateDimensions() { - this.$scope.$applyAsync( () => - { - const containerWidth = this.ruler.width( this.element.parentNode as HTMLElement ); - this.element.style.height = `${containerWidth / this.ratio}px`; - } ); + const containerWidth = this.ruler.width( this.element.parentNode as HTMLElement ); + this.element.style.height = `${containerWidth / this.ratio}px`; } }
b7c929e50be3476e91dd819e09bf5313502e0b73
src/navigation/AnonymousLayout.tsx
src/navigation/AnonymousLayout.tsx
import { UIView, useCurrentStateAndParams } from '@uirouter/react'; import { FunctionComponent } from 'react'; import { AppFooter } from './AppFooter'; import { CookiesConsent } from './cookies/CookiesConsent'; import { SiteHeader } from './header/SiteHeader'; export const AnonymousLayout: FunctionComponent = () => { const { state } = useCurrentStateAndParams(); return ( <> <CookiesConsent /> <div className="app-wrap footer-indent"> {!state.data.hideHeader && <SiteHeader />} <UIView className="app-content"></UIView> </div> <AppFooter /> </> ); };
import { UIView, useCurrentStateAndParams } from '@uirouter/react'; import { FunctionComponent } from 'react'; import { AppFooter } from './AppFooter'; import { CookiesConsent } from './cookies/CookiesConsent'; import { SiteHeader } from './header/SiteHeader'; export const AnonymousLayout: FunctionComponent = () => { const { state } = useCurrentStateAndParams(); return ( <> <CookiesConsent /> <div className="app-wrap footer-indent"> {!state.data?.hideHeader && <SiteHeader />} <UIView className="app-content"></UIView> </div> <AppFooter /> </> ); };
Add a workaround for checking if header should be hidden.
Add a workaround for checking if header should be hidden.
TypeScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -11,7 +11,7 @@ <> <CookiesConsent /> <div className="app-wrap footer-indent"> - {!state.data.hideHeader && <SiteHeader />} + {!state.data?.hideHeader && <SiteHeader />} <UIView className="app-content"></UIView> </div> <AppFooter />
e0ff22834eae4956ce079e60fd000de841c3d5e8
dropbox/src/main/endpoints/WebhookEndpoint.ts
dropbox/src/main/endpoints/WebhookEndpoint.ts
/** Classes in this module handle the protocol-level tasks of handling Events and returning HTTP responses. */ import { event, callback, challenge, uri } from "../Api"; import { pathTo, redirectTo } from "../clients/Http"; import { Notification, NotificationProcessor } from "../services/ServiceApi" const complete = <T>(cb: callback, p: Promise<T>) => p.then(res => cb(null, res)).catch(err => cb(err, null)); export class WebhookEndpoint { constructor(readonly service: NotificationProcessor) {} challenge(cb: callback, event: event) { cb(null, { statusCode: 200, body: event.queryStringParameters.challenge }); } notify(cb: callback, event: event) { console.log(event.body); complete(cb, this.processAndReturn(JSON.parse(event.body))); } private async processAndReturn(notification: Notification): Promise<any> { await this.service.processNotification(notification); return { statusCode: 200 }; } }
/** Classes in this module handle the protocol-level tasks of handling Events and returning HTTP responses. */ import { event, callback, challenge, uri } from "../Api"; import { pathTo, redirectTo } from "../clients/Http"; import { Notification, NotificationProcessor } from "../services/ServiceApi" const complete = <T>(cb: callback, p: Promise<T>) => p.then(res => cb(null, res)).catch(err => cb(err, null)); export class WebhookEndpoint { constructor(readonly service: NotificationProcessor) {} challenge(cb: callback, event: event) { cb(null, { statusCode: 200, body: event.queryStringParameters.challenge }); } notify(cb: callback, event: event) { complete(cb, this.processAndReturn(JSON.parse(event.body))); } private async processAndReturn(notification: Notification): Promise<any> { await this.service.processNotification(notification); return { statusCode: 200 }; } }
Stop writing notification to console
Stop writing notification to console
TypeScript
apache-2.0
poetix/bentham,poetix/bentham
--- +++ @@ -22,7 +22,6 @@ } notify(cb: callback, event: event) { - console.log(event.body); complete(cb, this.processAndReturn(JSON.parse(event.body))); }
b7f170964880b1e7376853d236912c74ca869f30
spec/laws/must.spec.ts
spec/laws/must.spec.ts
///<reference path="../../typings/main.d.ts" /> import expect = require('expect.js'); import { MustLaw } from 'courtroom/courtroom/laws/must'; describe('MustLaw', () => { describe('constructor', () => { it('should have correct name', function () { let mustFunction = function func () { return false; }; let law = new MustLaw(mustFunction); expect(law.getName()).to.be('must'); }); }); });
///<reference path="../../typings/main.d.ts" /> import expect = require('expect.js'); import { MustLaw } from 'courtroom/courtroom/laws/must'; describe('MustLaw', () => { describe('constructor', () => { it('should have correct name', function () { let mustFunction = function func () { return false; }; let law = new MustLaw(mustFunction); expect(law.getName()).to.be('must'); }); }); describe('verdict', () => { it('should call into function with given string', () => { let functionCalled = false; let mustFunction = function func () { functionCalled = true; return false; }; let law = new MustLaw(mustFunction); law.verdict('a'); expect(functionCalled).to.be(true); }); }); });
Test that function is called
Test that function is called
TypeScript
mit
Jameskmonger/courtroom,Jameskmonger/courtroom
--- +++ @@ -17,4 +17,22 @@ }); + describe('verdict', () => { + + it('should call into function with given string', () => { + let functionCalled = false; + let mustFunction = function func () { + functionCalled = true; + + return false; + }; + + let law = new MustLaw(mustFunction); + law.verdict('a'); + + expect(functionCalled).to.be(true); + }); + + }); + });
be5b7e429d0592770b7ffc8bc7d02be933f19b87
src/lib/Errors.ts
src/lib/Errors.ts
export abstract class NestedError extends Error { readonly inner?: Error readonly id: Number public constructor(message: string, id: Number, inner?: Error) { super(message) this.inner = inner this.id = id } toString(): string { const string = this.name + ": " + this.message if (this.inner) { return string + ':\n' + this.inner } return string } } export class DatabaseError extends NestedError { } export class DataError extends NestedError { }
export abstract class NestedError extends Error { readonly inner?: Error readonly id: Number public constructor(message: string, id: Number, inner?: Error) { super(message) this.inner = inner this.id = id this.name = this.constructor.name } toString(): string { const string = this.name + ": " + this.message if (this.inner) { return string + ':\n' + this.inner } return string } } export class DatabaseError extends NestedError { } export class DataError extends NestedError { }
Set the name of the errors correctly
Set the name of the errors correctly
TypeScript
mit
Belphemur/node-json-db,Belphemur/node-json-db
--- +++ @@ -7,6 +7,7 @@ super(message) this.inner = inner this.id = id + this.name = this.constructor.name } @@ -23,5 +24,4 @@ } export class DataError extends NestedError { - }
f79b8dd26f3ecf2c8d0dbfa22f24e612016cda83
src/api/configuration/get.ts
src/api/configuration/get.ts
import { RequestHandler } from 'express' import { get } from './db' const handler: RequestHandler = async (_, res) => { try { const config = await get() res.json(config) } catch (ex) { res.status(500).json({ message: ex.message || ex }) } } export default handler
import { RequestHandler } from 'express' import { getConfig as get } from './db' const handler: RequestHandler = async (_, res) => { try { const config = await get() res.json(config) } catch (ex) { res.status(500).json({ message: ex.message || ex }) } } export default handler
Use managed config cache in GET config responses
Use managed config cache in GET config responses
TypeScript
mit
the-concierge/concierge,the-concierge/concierge,the-concierge/concierge
--- +++ @@ -1,5 +1,5 @@ import { RequestHandler } from 'express' -import { get } from './db' +import { getConfig as get } from './db' const handler: RequestHandler = async (_, res) => { try {
dd2cdba95e842fe044eac1356f0b0d0916cc621a
src/app/services/settings.ts
src/app/services/settings.ts
import {Injectable} from 'angular2/angular2'; let languages = require('app/lib/languages'); @Injectable() export class Settings { private language: {key: string, value: string}; private availableLanguages: Array<{key: string, value: string}>; constructor() { let defaultLanguage = 'EN'; let language = localStorage.getItem('language'); this.availableLanguages = languages.map(language => { let key = language['alpha-2']; return { key: key, value: language.name }; }); this.changeLanguage(language || defaultLanguage); } changeLanguage(newLanguageKey: string): any { localStorage.setItem('language', newLanguageKey); this.language = { key: newLanguageKey, value: _.find(this.availableLanguages, {key: newLanguageKey}).value }; } getLanguage() { return this.language; } getAvailableLanguages() { return this.availableLanguages; } }
import {Injectable} from 'angular2/angular2'; let languages = require('app/lib/languages'); @Injectable() export class Settings { private language: {key: string, value: string}; private availableLanguages: Array<{key: string, value: string}>; constructor() { let defaultLanguage = 'US'; let language = localStorage.getItem('language'); this.availableLanguages = languages.map(language => { let key = language['alpha-2']; return { key: key, value: language.name }; }); this.changeLanguage(language || defaultLanguage); } changeLanguage(newLanguageKey: string): any { localStorage.setItem('language', newLanguageKey); this.language = { key: newLanguageKey, value: _.find(this.availableLanguages, {key: newLanguageKey}).value }; } getLanguage() { return this.language; } getAvailableLanguages() { return this.availableLanguages; } }
Fix wrong initial values for language
Fix wrong initial values for language
TypeScript
mit
dotcs/cueonthespot-web,dotcs/cueonthespot-web,dotcs/cueonthespot-web
--- +++ @@ -9,7 +9,7 @@ constructor() { - let defaultLanguage = 'EN'; + let defaultLanguage = 'US'; let language = localStorage.getItem('language'); this.availableLanguages = languages.map(language => {
3ce1a8ca28fc6fd255b5a7155f6e0c529c4c91e5
lib/config.ts
lib/config.ts
///<reference path=".d.ts"/> import path = require("path"); import util = require("util"); export class StaticConfig implements IStaticConfig { public PROJECT_FILE_NAME = ".tnsproject"; public CLIENT_NAME = "nativescript"; public CLIENT_NAME_ALIAS = "tns"; public ANALYTICS_API_KEY = "5752dabccfc54c4ab82aea9626b7338e"; public TRACK_FEATURE_USAGE_SETTING_NAME = "TrackFeatureUsage"; public ANALYTICS_INSTALLATION_ID_SETTING_NAME = "AnalyticsInstallationID"; public START_PACKAGE_ACTIVITY_NAME = "com.tns.NativeScriptActivity"; public version = require("../package.json").version; public get helpTextPath(): string { return path.join(__dirname, "../resources/help.txt"); } public get adbFilePath(): string { return path.join(__dirname, util.format("../resources/platform-tools/android/%s/adb", process.platform)); } } $injector.register("staticConfig", StaticConfig);
///<reference path=".d.ts"/> import path = require("path"); import util = require("util"); export class StaticConfig implements IStaticConfig { public PROJECT_FILE_NAME = ".tnsproject"; public CLIENT_NAME = "NativeScript"; public CLIENT_NAME_ALIAS = "tns"; public ANALYTICS_API_KEY = "5752dabccfc54c4ab82aea9626b7338e"; public TRACK_FEATURE_USAGE_SETTING_NAME = "TrackFeatureUsage"; public ANALYTICS_INSTALLATION_ID_SETTING_NAME = "AnalyticsInstallationID"; public START_PACKAGE_ACTIVITY_NAME = "com.tns.NativeScriptActivity"; public version = require("../package.json").version; public get helpTextPath(): string { return path.join(__dirname, "../resources/help.txt"); } public get adbFilePath(): string { return path.join(__dirname, util.format("../resources/platform-tools/android/%s/adb", process.platform)); } } $injector.register("staticConfig", StaticConfig);
Fix message from analytics consent prompt
Fix message from analytics consent prompt
TypeScript
apache-2.0
NativeScript/nativescript-cli,tsvetie/nativescript-cli,NathanaelA/nativescript-cli,tsvetie/nativescript-cli,tsvetie/nativescript-cli,NativeScript/nativescript-cli,jbristowe/nativescript-cli,NathanaelA/nativescript-cli,tsvetie/nativescript-cli,NathanaelA/nativescript-cli,NativeScript/nativescript-cli,e2l3n/nativescript-cli,jbristowe/nativescript-cli,e2l3n/nativescript-cli,lokilandon/nativescript-cli,NativeScript/nativescript-cli,NathanaelA/nativescript-cli,tsvetie/nativescript-cli,lokilandon/nativescript-cli,jbristowe/nativescript-cli,e2l3n/nativescript-cli,lokilandon/nativescript-cli
--- +++ @@ -5,7 +5,7 @@ export class StaticConfig implements IStaticConfig { public PROJECT_FILE_NAME = ".tnsproject"; - public CLIENT_NAME = "nativescript"; + public CLIENT_NAME = "NativeScript"; public CLIENT_NAME_ALIAS = "tns"; public ANALYTICS_API_KEY = "5752dabccfc54c4ab82aea9626b7338e"; public TRACK_FEATURE_USAGE_SETTING_NAME = "TrackFeatureUsage";
c0362b7a8f67d8d1153ec27e84a2f1b6aef43344
packages/lesswrong/server/bookmarkMutation.ts
packages/lesswrong/server/bookmarkMutation.ts
import { addGraphQLMutation, addGraphQLResolvers } from './vulcan-lib'; import Users from '../lib/collections/users/collection'; import { updateMutator } from './vulcan-lib/mutators'; import * as _ from 'underscore'; addGraphQLMutation('setIsBookmarked(postId: String!, isBookmarked: Boolean!): User!'); addGraphQLResolvers({ Mutation: { async setIsBookmarked(root: void, {postId,isBookmarked}: {postId: string, isBookmarked: boolean}, context: ResolverContext) { const {currentUser} = context; if (!currentUser) throw new Error("Log in to use bookmarks"); const oldBookmarksList = currentUser.bookmarkedPostsMetadata; const alreadyBookmarked = _.some(oldBookmarksList, bookmark=>bookmark.postId===postId); const newBookmarksList = (isBookmarked ? (alreadyBookmarked ? oldBookmarksList : [...oldBookmarksList, {postId}]) : _.reject(oldBookmarksList, bookmark=>bookmark.postId===postId) ); await updateMutator({ collection: Users, documentId: currentUser._id, set: {bookmarkedPostsMetadata: newBookmarksList}, currentUser, context, validate: false, }); const updatedUser = Users.findOne(currentUser._id); return updatedUser; } } });
import { addGraphQLMutation, addGraphQLResolvers } from './vulcan-lib'; import Users from '../lib/collections/users/collection'; import { updateMutator } from './vulcan-lib/mutators'; import * as _ from 'underscore'; addGraphQLMutation('setIsBookmarked(postId: String!, isBookmarked: Boolean!): User!'); addGraphQLResolvers({ Mutation: { async setIsBookmarked(root: void, {postId,isBookmarked}: {postId: string, isBookmarked: boolean}, context: ResolverContext) { const {currentUser} = context; if (!currentUser) throw new Error("Log in to use bookmarks"); const oldBookmarksList = currentUser.bookmarkedPostsMetadata; const alreadyBookmarked = _.some(oldBookmarksList, bookmark=>bookmark.postId===postId); const newBookmarksList = (isBookmarked ? (alreadyBookmarked ? oldBookmarksList : [...(oldBookmarksList||[]), {postId}]) : _.reject(oldBookmarksList, bookmark=>bookmark.postId===postId) ); await updateMutator({ collection: Users, documentId: currentUser._id, set: {bookmarkedPostsMetadata: newBookmarksList}, currentUser, context, validate: false, }); const updatedUser = Users.findOne(currentUser._id); return updatedUser; } } });
Fix crash from oldBookmarksList being null, seen in Sentry
Fix crash from oldBookmarksList being null, seen in Sentry
TypeScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
--- +++ @@ -14,7 +14,7 @@ const oldBookmarksList = currentUser.bookmarkedPostsMetadata; const alreadyBookmarked = _.some(oldBookmarksList, bookmark=>bookmark.postId===postId); const newBookmarksList = (isBookmarked - ? (alreadyBookmarked ? oldBookmarksList : [...oldBookmarksList, {postId}]) + ? (alreadyBookmarked ? oldBookmarksList : [...(oldBookmarksList||[]), {postId}]) : _.reject(oldBookmarksList, bookmark=>bookmark.postId===postId) );
212ed488a1c0c156d41882e31ef7766e974a45bc
app/demo-app.component.ts
app/demo-app.component.ts
import {Component} from 'angular2/core'; import {SvgIconComponent} from './svg-icon.component'; @Component({ selector: 'demo-app', directives: [ SvgIconComponent ], template: ` <div style="width:100px;"> <div style="fill:red;"> <svg-icon src="images/eye.svg"></svg-icon> </div> <div style="fill:green;"> <svg-icon src="images/eye.svg"></svg-icon> </div> <div style="fill:blue;"> <svg-icon src="images/eye.svg"></svg-icon> </div> </div> ` }) export class DemoAppComponent { }
import {Component} from 'angular2/core'; import {SvgIconComponent} from './svg-icon.component'; @Component({ selector: 'demo-app', directives: [ SvgIconComponent ], template: ` <div style="width:100px;"> <svg-icon src="images/eye.svg" style="fill:red;"></svg-icon> <svg-icon src="images/eye.svg" style="fill:green;"></svg-icon> <svg-icon src="images/eye.svg" style="fill:blue;"></svg-icon> </div> ` }) export class DemoAppComponent { }
Remove containing div and style svg-icon directly.
Remove containing div and style svg-icon directly.
TypeScript
mit
czeckd/angular-svg-icon,czeckd/angular2-svg-icon,czeckd/angular2-svg-icon,czeckd/angular-svg-icon,czeckd/angular-svg-icon,czeckd/angular2-svg-icon
--- +++ @@ -6,15 +6,9 @@ directives: [ SvgIconComponent ], template: ` <div style="width:100px;"> - <div style="fill:red;"> - <svg-icon src="images/eye.svg"></svg-icon> - </div> - <div style="fill:green;"> - <svg-icon src="images/eye.svg"></svg-icon> - </div> - <div style="fill:blue;"> - <svg-icon src="images/eye.svg"></svg-icon> - </div> + <svg-icon src="images/eye.svg" style="fill:red;"></svg-icon> + <svg-icon src="images/eye.svg" style="fill:green;"></svg-icon> + <svg-icon src="images/eye.svg" style="fill:blue;"></svg-icon> </div> ` })
a71fb3a46ce2b8cf692a5003b591bdc8eae2cc5a
client/Library/Components/EncounterLibraryViewModel.tsx
client/Library/Components/EncounterLibraryViewModel.tsx
import * as React from "react"; import { ListingViewModel } from "./Listing"; import { EncounterLibrary } from "../EncounterLibrary"; import { SavedEncounter, SavedCombatant } from "../../Encounter/SavedEncounter"; import { Listing } from "../Listing"; import { TrackerViewModel } from "../../TrackerViewModel"; import { LibraryFilter } from "./LibraryFilter"; export type EncounterLibraryViewModelProps = { tracker: TrackerViewModel; library: EncounterLibrary }; interface State { filter: string; } export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps, State> { constructor(props) { super(props); this.state = { filter: "" }; } public render() { const filteredListings = this.props.library.Encounters(); const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter)); }; const deleteListing = (listing: Listing<SavedEncounter<SavedCombatant>>) => { if (confirm(`Delete saved encounter "${listing.CurrentName()}"?`)) { this.props.library.Delete(listing); } }; return ([ <LibraryFilter applyFilterFn={filter => this.setState({ filter })}/>, <ul className="listings"> {filteredListings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} </ul> ]); } }
import * as React from "react"; import { ListingViewModel } from "./Listing"; import { EncounterLibrary } from "../EncounterLibrary"; import { SavedEncounter, SavedCombatant } from "../../Encounter/SavedEncounter"; import { Listing, DedupeByRankAndFilterListings } from "../Listing"; import { TrackerViewModel } from "../../TrackerViewModel"; import { LibraryFilter } from "./LibraryFilter"; export type EncounterLibraryViewModelProps = { tracker: TrackerViewModel; library: EncounterLibrary }; interface State { filter: string; } export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps, State> { constructor(props) { super(props); this.state = { filter: "" }; } public render() { const filteredListings = DedupeByRankAndFilterListings(this.props.library.Encounters(), this.state.filter); const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter)); }; const deleteListing = (listing: Listing<SavedEncounter<SavedCombatant>>) => { if (confirm(`Delete saved encounter "${listing.CurrentName()}"?`)) { this.props.library.Delete(listing); } }; return ([ <LibraryFilter applyFilterFn={filter => this.setState({ filter })}/>, <ul className="listings"> {filteredListings.map(l => <ListingViewModel name={l.CurrentName()} onAdd={loadSavedEncounter} onDelete={deleteListing} listing={l} />)} </ul> ]); } }
Call DedupeByRankAndFilterListings to apply filter to listings
Call DedupeByRankAndFilterListings to apply filter to listings
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -2,7 +2,7 @@ import { ListingViewModel } from "./Listing"; import { EncounterLibrary } from "../EncounterLibrary"; import { SavedEncounter, SavedCombatant } from "../../Encounter/SavedEncounter"; -import { Listing } from "../Listing"; +import { Listing, DedupeByRankAndFilterListings } from "../Listing"; import { TrackerViewModel } from "../../TrackerViewModel"; import { LibraryFilter } from "./LibraryFilter"; @@ -15,7 +15,6 @@ filter: string; } - export class EncounterLibraryViewModel extends React.Component<EncounterLibraryViewModelProps, State> { constructor(props) { super(props); @@ -24,7 +23,7 @@ }; } public render() { - const filteredListings = this.props.library.Encounters(); + const filteredListings = DedupeByRankAndFilterListings(this.props.library.Encounters(), this.state.filter); const loadSavedEncounter = (listing: Listing<SavedEncounter<SavedCombatant>>) => { listing.GetAsync(savedEncounter => this.props.tracker.Encounter.LoadSavedEncounter(savedEncounter));
af8bbd9d5de7d49a7a3d6c6106e2472bcd5d8659
web/typescript/main/controls.tsx
web/typescript/main/controls.tsx
/// <reference path="react-global.d.ts" /> class ControlsProps { public controls: any; } class ControlsJSX extends React.Component<ControlsProps, any> { constructor(props: ControlsProps) { super(props); this.clickPlay = this.clickPlay.bind(this); this.clickStop = this.clickStop.bind(this); this.clickPrev = this.clickPrev.bind(this); this.clickNext = this.clickNext.bind(this); } private clickPlay() { this.props.controls.play(); } private clickStop() { this.props.controls.stop(); } private clickPrev() { this.props.controls.prev(); } private clickNext() { this.props.controls.next(); } render() { return (<div> <input type="button" value="Play" onClick={this.clickPlay} /> <input type="button" value="Stop" onClick={this.clickStop} /> <input type="button" value="Prev" onClick={this.clickPrev} /> <input type="button" value="Next" onClick={this.clickNext} /> </div>); } }
/// <reference path="react-global.d.ts" /> class ControlsProps { public controls: any; } class ControlsJSX extends React.Component<ControlsProps, any> { private clickPlay; private clickStop; private clickPrev; private clickNext; constructor(props: ControlsProps) { super(props); this.clickPlay = () => props.controls.play(); this.clickStop = () => props.controls.stop(); this.clickPrev = () => props.controls.prev(); this.clickNext = () => props.controls.next(); } render() { return (<div> <input type="button" value="Play" onClick={this.clickPlay} /> <input type="button" value="Stop" onClick={this.clickStop} /> <input type="button" value="Prev" onClick={this.clickPrev} /> <input type="button" value="Next" onClick={this.clickNext} /> </div>); } }
Replace 'bind' with local access
Replace 'bind' with local access
TypeScript
apache-2.0
jotak/mipod.x,jotak/mipod.x,jotak/mipod.x,jotak/mipod.x
--- +++ @@ -6,28 +6,17 @@ class ControlsJSX extends React.Component<ControlsProps, any> { + private clickPlay; + private clickStop; + private clickPrev; + private clickNext; + constructor(props: ControlsProps) { super(props); - this.clickPlay = this.clickPlay.bind(this); - this.clickStop = this.clickStop.bind(this); - this.clickPrev = this.clickPrev.bind(this); - this.clickNext = this.clickNext.bind(this); - } - - private clickPlay() { - this.props.controls.play(); - } - - private clickStop() { - this.props.controls.stop(); - } - - private clickPrev() { - this.props.controls.prev(); - } - - private clickNext() { - this.props.controls.next(); + this.clickPlay = () => props.controls.play(); + this.clickStop = () => props.controls.stop(); + this.clickPrev = () => props.controls.prev(); + this.clickNext = () => props.controls.next(); } render() {
9074c44233aa4fa506f855a4367d38baadecc644
src/index.ts
src/index.ts
export { TransitionEvent, TimelineType, IAbstractTransitionControllerOptions, ICreateTimelineOptions, } from 'transition-controller'; // Export util classes export { default as FlowManager } from './lib/util/FlowManager'; export { default as AbstractTransitionController, } from './lib/util/AbstractVueTransitionController'; // Export enums export { default as FlowType } from './lib/enum/FlowType'; // Export events export { default as FlowEvent } from './lib/event/FlowEvent'; // Export interfaces export { IAbstractPageTransitionComponent } from './lib/interface/IAbstractPageTransitionComponent'; export { IAbstractRegistrableComponent } from './lib/interface/IAbstractRegistrableComponent'; export { IAbstractTransitionComponent } from './lib/interface/IAbstractTransitionComponent'; export { IRoute } from './lib/interface/IRoute'; // Export vue mixins export { default as AbstractRegistrableComponent } from './lib/mixin/AbstractRegistrableComponent'; export { default as AbstractTransitionComponent } from './lib/mixin/AbstractTransitionComponent'; export { default as AbstractPageTransitionComponent, } from './lib/mixin/AbstractPageTransitionComponent';
export { TransitionEvent, TimelineType, TransitionDirection, IAbstractTransitionControllerOptions, ICreateTimelineOptions, } from 'transition-controller'; // Export util classes export { default as FlowManager } from './lib/util/FlowManager'; export { default as AbstractTransitionController, } from './lib/util/AbstractVueTransitionController'; // Export enums export { default as FlowType } from './lib/enum/FlowType'; // Export events export { default as FlowEvent } from './lib/event/FlowEvent'; // Export interfaces export { IAbstractPageTransitionComponent } from './lib/interface/IAbstractPageTransitionComponent'; export { IAbstractRegistrableComponent } from './lib/interface/IAbstractRegistrableComponent'; export { IAbstractTransitionComponent } from './lib/interface/IAbstractTransitionComponent'; export { IRoute } from './lib/interface/IRoute'; // Export vue mixins export { default as AbstractRegistrableComponent } from './lib/mixin/AbstractRegistrableComponent'; export { default as AbstractTransitionComponent } from './lib/mixin/AbstractTransitionComponent'; export { default as AbstractPageTransitionComponent, } from './lib/mixin/AbstractPageTransitionComponent';
Add the transition direction to the exports
Add the transition direction to the exports
TypeScript
mit
larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component
--- +++ @@ -1,6 +1,7 @@ export { TransitionEvent, TimelineType, + TransitionDirection, IAbstractTransitionControllerOptions, ICreateTimelineOptions, } from 'transition-controller';
48954be484e41a6720fe4bdf139da4d3d292fd21
test/enum.ts
test/enum.ts
import { types, unprotect } from "../src" import { test } from "ava" test("should support enums", t => { const TrafficLight = types.model({ color: types.enumeration("Color", ["Red", "Orange", "Green"]) }) t.is(TrafficLight.is({ color: "Green" }), true) t.is(TrafficLight.is({ color: "Blue" }), false) t.is(TrafficLight.is({ color: undefined }), false) const l = TrafficLight.create({ color: "Orange" }) unprotect(l) l.color = "Red" t.is(TrafficLight.describe(), '{ color: ("Orange" | "Green" | "Red") }') // Note, any cast needed, compiler should correctly error otherwise t.throws(() => (l.color = "Blue" as any), /Error while converting `"Blue"` to `Color`/) }) test("should support anonymous enums", t => { const TrafficLight = types.model({ color: types.enumeration(["Red", "Orange", "Green"]) }) const l = TrafficLight.create({ color: "Orange" }) unprotect(l) l.color = "Red" t.is(TrafficLight.describe(), '{ color: ("Orange" | "Green" | "Red") }') // Note, any cast needed, compiler should correctly error otherwise t.throws( () => (l.color = "Blue" as any), /Error while converting `"Blue"` to `Orange | Green | Red`/ ) })
import { types, unprotect } from "../src" import { test } from "ava" test("should support enums", t => { const TrafficLight = types.model({ color: types.enumeration("Color", ["Red", "Orange", "Green"]) }) t.is(TrafficLight.is({ color: "Green" }), true) t.is(TrafficLight.is({ color: "Blue" }), false) t.is(TrafficLight.is({ color: undefined }), false) const l = TrafficLight.create({ color: "Orange" }) unprotect(l) l.color = "Red" t.is(TrafficLight.describe(), '{ color: ("Orange" | "Green" | "Red") }') // Note, any cast needed, compiler should correctly error otherwise t.throws(() => (l.color = "Blue" as any), /Error while converting `"Blue"` to `Color`/) }) test("should support anonymous enums", t => { const TrafficLight = types.model({ color: types.enumeration(["Red", "Orange", "Green"]) }) const l = TrafficLight.create({ color: "Orange" }) unprotect(l) l.color = "Red" t.is(TrafficLight.describe(), '{ color: ("Orange" | "Green" | "Red") }') // Note, any cast needed, compiler should correctly error otherwise t.throws( () => (l.color = "Blue" as any), /Error while converting `"Blue"` to `"Orange" | "Green" | "Red"`/ ) })
Fix a test written before the rebase
Fix a test written before the rebase
TypeScript
mit
mobxjs/mobx-state-tree,mweststrate/mobx-state-tree,mobxjs/mobx-state-tree,mweststrate/mobx-state-tree,mobxjs/mobx-state-tree,mobxjs/mobx-state-tree
--- +++ @@ -36,6 +36,6 @@ // Note, any cast needed, compiler should correctly error otherwise t.throws( () => (l.color = "Blue" as any), - /Error while converting `"Blue"` to `Orange | Green | Red`/ + /Error while converting `"Blue"` to `"Orange" | "Green" | "Red"`/ ) })
2e609094a51937b588a16b8b131e214f28abf85e
packages/async-hook-context/src/services/PlatformAsyncHookContext.ts
packages/async-hook-context/src/services/PlatformAsyncHookContext.ts
import {Inject, Injectable, PlatformContext, PlatformHandler} from "@tsed/common"; import {Logger} from "@tsed/logger"; import {AsyncLocalStorage} from "async_hooks"; @Injectable() export class PlatformAsyncHookContext { @Inject() protected logger: Logger; @Inject() protected platformHandler: PlatformHandler; protected store: AsyncLocalStorage<PlatformContext>; getContext() { return this.store?.getStore(); } $onInit() { /* istanbul ignore */ if (AsyncLocalStorage) { this.store = new AsyncLocalStorage(); // override this.platformHandler.run = (ctx: PlatformContext, cb: any) => { return PlatformAsyncHookContext.run(ctx, cb, this.store); }; } else { this.logger.warn( `AsyncLocalStorage is not available for your Node.js version (${process.versions.node}). Please upgrade your version at least to v13.10.0.` ); } } static run(ctx: PlatformContext, cb: any, store = new AsyncLocalStorage()) { return store.run(ctx, cb); } }
import {Inject, Injectable, PlatformContext, PlatformHandler, PlatformTest} from "@tsed/common"; import {Logger} from "@tsed/logger"; import {AsyncLocalStorage} from "async_hooks"; let store: AsyncLocalStorage<PlatformContext>; @Injectable() export class PlatformAsyncHookContext { @Inject() protected logger: Logger; @Inject() protected platformHandler: PlatformHandler; getContext() { return store?.getStore(); } static getStore() { store = store || new AsyncLocalStorage(); return store; } run = (ctx: PlatformContext, cb: any) => { return PlatformAsyncHookContext.run(ctx, cb); }; $onInit() { /* istanbul ignore */ if (AsyncLocalStorage) { PlatformAsyncHookContext.getStore(); // override this.platformHandler.run = this.run; } else { this.logger.warn( `AsyncLocalStorage is not available for your Node.js version (${process.versions.node}). Please upgrade your version at least to v13.10.0.` ); } } static run(ctx: PlatformContext, cb: any) { return PlatformAsyncHookContext.getStore().run(ctx, cb); } }
Fix asyncHookContext when running unit test
fix(async-hook-context): Fix asyncHookContext when running unit test
TypeScript
mit
Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators
--- +++ @@ -1,6 +1,8 @@ -import {Inject, Injectable, PlatformContext, PlatformHandler} from "@tsed/common"; +import {Inject, Injectable, PlatformContext, PlatformHandler, PlatformTest} from "@tsed/common"; import {Logger} from "@tsed/logger"; import {AsyncLocalStorage} from "async_hooks"; + +let store: AsyncLocalStorage<PlatformContext>; @Injectable() export class PlatformAsyncHookContext { @@ -10,20 +12,25 @@ @Inject() protected platformHandler: PlatformHandler; - protected store: AsyncLocalStorage<PlatformContext>; + getContext() { + return store?.getStore(); + } - getContext() { - return this.store?.getStore(); + static getStore() { + store = store || new AsyncLocalStorage(); + return store; } + + run = (ctx: PlatformContext, cb: any) => { + return PlatformAsyncHookContext.run(ctx, cb); + }; $onInit() { /* istanbul ignore */ if (AsyncLocalStorage) { - this.store = new AsyncLocalStorage(); + PlatformAsyncHookContext.getStore(); // override - this.platformHandler.run = (ctx: PlatformContext, cb: any) => { - return PlatformAsyncHookContext.run(ctx, cb, this.store); - }; + this.platformHandler.run = this.run; } else { this.logger.warn( `AsyncLocalStorage is not available for your Node.js version (${process.versions.node}). Please upgrade your version at least to v13.10.0.` @@ -31,7 +38,7 @@ } } - static run(ctx: PlatformContext, cb: any, store = new AsyncLocalStorage()) { - return store.run(ctx, cb); + static run(ctx: PlatformContext, cb: any) { + return PlatformAsyncHookContext.getStore().run(ctx, cb); } }
5a50e547ad465c0f340cb029a5e4ed0ddb9594fb
aquarium-web/src/app/api.service.ts
aquarium-web/src/app/api.service.ts
import { Injectable } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class ApiService { private baseUrl = 'https://aqua.gerty.roga.czedik.at/api'; private registeredComponent; constructor(private http: Http) { } register(component) { this.registeredComponent = component; this.updateState(); } updateState() { this.getState().subscribe(state => this.registeredComponent.state = state); } getState(): Observable<any> { const state$ = this.http .get(`${this.baseUrl}/controller/aqua`) .map(this.toJSON); return state$; } sendValues(values) { const state = { 'controllerId': 'aqua', 'values': values }; const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); this.http .post(`${this.baseUrl}/updateController`, JSON.stringify(state), options) .toPromise() .then(() => this.updateState()); } toJSON(response: Response): any { const json = response.json(); return json; } }
import { Injectable } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class ApiService { private baseUrl = 'https://aqua.gerty.roga.czedik.at/api'; private registeredComponent; constructor(private http: Http) { } register(component) { this.registeredComponent = component; this.updateState(); } updateState() { this.getState().subscribe(state => this.registeredComponent.state = state); } getState(): Observable<any> { const state$ = this.http .get(`${this.baseUrl}/controller/aqua`) .map(this.toJSON); return state$; } sendValues(values) { const state = { 'controllerId': 'aqua', 'values': values }; const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); this.http .post(`${this.baseUrl}/updateController`, JSON.stringify(state), options) .toPromise() .then(() => this.updateState()) .catch((e) => { console.log(e); this.updateState() }); } toJSON(response: Response): any { const json = response.json(); return json; } }
Handle error more graceful. Still update state afterwards.
Handle error more graceful. Still update state afterwards.
TypeScript
mit
Bronkoknorb/hm-aquarium,Bronkoknorb/hm-aquarium,Bronkoknorb/hm-aquarium,Bronkoknorb/hm-aquarium
--- +++ @@ -41,7 +41,11 @@ this.http .post(`${this.baseUrl}/updateController`, JSON.stringify(state), options) .toPromise() - .then(() => this.updateState()); + .then(() => this.updateState()) + .catch((e) => { + console.log(e); + this.updateState() + }); } toJSON(response: Response): any {
a140aa90159f19f669bcfcf384d8093fc5f41e35
src/components/SearchTable/SortingForm.tsx
src/components/SearchTable/SortingForm.tsx
import * as React from 'react'; import { Card, FormLayout, Select } from '@shopify/polaris'; import { SortingOption } from '../../types'; import SearchTableButtons from './SearchTableButtons'; export interface Props { readonly value: SortingOption; } export interface Handlers { readonly onChange: (option: SortingOption) => void; } const options: SortingOption[] = [ 'Reward', 'Batch Size', 'Latest' ]; const SortingForm = ({ value, onChange }: Props & Handlers) => { return ( <Card.Section> <FormLayout> <Select label="Sorting Options" id="select-sort-option" name="Sorting Options" options={options} value={value} onChange={onChange} /> <SearchTableButtons /> </FormLayout> </Card.Section> ); }; export default SortingForm;
import * as React from 'react'; import { Card, FormLayout, Select } from '@shopify/polaris'; import { SortingOption } from '../../types'; import SearchTableButtons from './SearchTableButtons'; export interface Props { readonly value: SortingOption; } export interface Handlers { readonly onChange: (option: SortingOption) => void; } const options: SortingOption[] = [ 'Reward', 'Batch Size', 'Latest' ]; const SortingForm = ({ value, onChange }: Props & Handlers) => { return ( <Card.Section> <FormLayout> <Select label="Sort Results By" id="select-sort-option" name="Sorting Options" options={options} value={value} onChange={onChange} /> <SearchTableButtons /> </FormLayout> </Card.Section> ); }; export default SortingForm;
Change sorting select field label.
Change sorting select field label.
TypeScript
mit
Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine
--- +++ @@ -18,7 +18,7 @@ <Card.Section> <FormLayout> <Select - label="Sorting Options" + label="Sort Results By" id="select-sort-option" name="Sorting Options" options={options}
0af86d7309ebc2914564829c8beb02112d0acc0e
app/app.ts
app/app.ts
import command = require("./lib/command"); import common = require("./lib/common"); import errHandler = require("./lib/errorhandler"); import loader = require("./lib/loader"); import path = require("path"); function patchPromisify() { // Monkey-patch promisify if we are NodeJS <8.0 const nodeVersion = process.version.substr(1); if (parseInt(nodeVersion.charAt(0)) < 8) { require("util.promisify/shim")(); } } // Set app root common.APP_ROOT = __dirname; namespace Bootstrap { export async function begin() { const cmd = await command.getCommand(); common.EXEC_PATH = cmd.execPath; const tfCommand = await loader.load(cmd.execPath, cmd.args); await tfCommand.showBanner(); const executor = await tfCommand.ensureInitialized(); return executor(cmd); } } patchPromisify(); Bootstrap.begin() .then(() => {}) .catch(reason => { errHandler.errLog(reason); });
import command = require("./lib/command"); import common = require("./lib/common"); import errHandler = require("./lib/errorhandler"); import loader = require("./lib/loader"); import path = require("path"); function patchPromisify() { // Monkey-patch promisify if we are NodeJS <8.0 or Chakra const nodeVersion = process.version.substr(1); // Chakra has a compatibility bug that causes promisify to not work. // See https://github.com/nodejs/node-chakracore/issues/395 const jsEngine = process["jsEngine"] || "v8"; const isChakra = jsEngine.indexOf("chakra") >= 0; if (isChakra) { require("util").promisify = undefined; } if (parseInt(nodeVersion.charAt(0)) < 8 || isChakra) { require("util.promisify/shim")(); } } // Set app root common.APP_ROOT = __dirname; namespace Bootstrap { export async function begin() { const cmd = await command.getCommand(); common.EXEC_PATH = cmd.execPath; const tfCommand = await loader.load(cmd.execPath, cmd.args); await tfCommand.showBanner(); const executor = await tfCommand.ensureInitialized(); return executor(cmd); } } patchPromisify(); Bootstrap.begin() .then(() => {}) .catch(reason => { errHandler.errLog(reason); });
Work around a bug preventing TFX from running under node backed by chakra-core.
Work around a bug preventing TFX from running under node backed by chakra-core.
TypeScript
mit
Microsoft/tfs-cli,grawcho/tfs-cli,grawcho/tfs-cli,Microsoft/tfs-cli,grawcho/tfs-cli
--- +++ @@ -5,9 +5,18 @@ import path = require("path"); function patchPromisify() { - // Monkey-patch promisify if we are NodeJS <8.0 + // Monkey-patch promisify if we are NodeJS <8.0 or Chakra const nodeVersion = process.version.substr(1); - if (parseInt(nodeVersion.charAt(0)) < 8) { + + // Chakra has a compatibility bug that causes promisify to not work. + // See https://github.com/nodejs/node-chakracore/issues/395 + const jsEngine = process["jsEngine"] || "v8"; + const isChakra = jsEngine.indexOf("chakra") >= 0; + if (isChakra) { + require("util").promisify = undefined; + } + + if (parseInt(nodeVersion.charAt(0)) < 8 || isChakra) { require("util.promisify/shim")(); } }
1e46a53375e13b73042a5a7796f4204f40858a17
src/ts/model/countersStore.ts
src/ts/model/countersStore.ts
/// <reference path="../core/model" /> namespace YJMCNT { export interface CountersSchema { id: string, value: number, defaltValue: number, } /** * Counter */ export class CountersStore extends Core.Model { storeName = "counters"; constructor() { super(); } /** * add */ public add(counter: CountersSchema) { var transaction = this.db.transaction([this.storeName], Config.DB.READWRITE); var store = transaction.objectStore(this.storeName); var request = store.add(counter); request.onsuccess = (event) => { this.notifyObservers(); }; } } }
/// <reference path="../core/model" /> namespace YJMCNT { export interface CountersSchema { id: string, value: number, defaltValue: number, } /** * Counter */ export class CountersStore extends Core.Model { storeName = "counters"; constructor() { super(); } /** * add */ public add(counter: CountersSchema) { var transaction = this.db.transaction([this.storeName], Config.DB.READWRITE); var store = transaction.objectStore(this.storeName); var request = store.add(counter); request.onsuccess = (event) => { this.notifyObservers(); }; } /** * getAll */ public getAll(callback: (counterList: Counter[]) => void) { var counters: Counter[] = []; var transaction = this.db.transaction([this.storeName], Config.DB.READWRITE); var store = transaction.objectStore(this.storeName); var request = store.openCursor(); request.onsuccess = (event) => { var target = <IDBRequest>event.target; var cursor: IDBCursorWithValue = target.result; if (!!cursor == false) { callback(counters); return; } var data:CountersSchema = cursor.value; counters.push(Counter.deserialize(data)); cursor.continue(); } } } }
Add method: get all counters from store
Add method: get all counters from store
TypeScript
mit
yajamon/chrome-ext-counter,yajamon/chrome-ext-counter,yajamon/chrome-ext-counter
--- +++ @@ -29,5 +29,28 @@ this.notifyObservers(); }; } + + /** + * getAll + */ + public getAll(callback: (counterList: Counter[]) => void) { + var counters: Counter[] = []; + var transaction = this.db.transaction([this.storeName], Config.DB.READWRITE); + var store = transaction.objectStore(this.storeName); + var request = store.openCursor(); + request.onsuccess = (event) => { + var target = <IDBRequest>event.target; + var cursor: IDBCursorWithValue = target.result; + + if (!!cursor == false) { + callback(counters); + return; + } + var data:CountersSchema = cursor.value; + counters.push(Counter.deserialize(data)); + cursor.continue(); + } + + } } }
e1facf9e0689d38b7f6747aecc36511c020f2d51
packages/tux/src/components/fields/Dropdown.tsx
packages/tux/src/components/fields/Dropdown.tsx
import React, { Component } from 'react' import { tuxColors, tuxInputStyles } from '../../styles' interface Dropdown { id: string value: string label: string helpText: string dropdownValues: Array<string> onChange: (e: React.FormEvent<any>) => void } export interface State { selectedValue: string | null, } class Dropdown extends Component<any, State> { state: State = { selectedValue: null, } componentDidMount() { const { value } = this.props console.log(value) this.setState({ selectedValue: value }) } handleChange = (value: string) => { const { onChange } = this.props this.setState({ selectedValue: value }) onChange(value) } render() { const { id, value, label, dropdownValues, onChange } = this.props const { selectedValue } = this.state return ( <div className="Dropdown"> <label className="InputLabel">{label}</label> <select onChange={(event: React.ChangeEvent<any>) => this.handleChange(event.target.value)} > {dropdownValues.map((value: string) => ( <option key={value} selected={value === selectedValue}>{value}</option> ))} </select> <style jsx>{` .Dropdown { } `}</style> </div> ) } } export default Dropdown
import React, { Component } from 'react' import { tuxColors, tuxInputStyles } from '../../styles' interface Dropdown { id: string value: string label: string helpText: string dropdownValues: Array<string> onChange: (e: React.FormEvent<any>) => void } export interface State { selectedValue: string | undefined, } class Dropdown extends Component<any, State> { state: State = { selectedValue: undefined, } componentDidMount() { const { value } = this.props this.setState({ selectedValue: value }) } handleChange = (value: string) => { const { onChange } = this.props this.setState({ selectedValue: value }) onChange(value) } render() { const { id, value, label, dropdownValues, onChange } = this.props const { selectedValue } = this.state return ( <div className="Dropdown"> <label className="InputLabel">{label}</label> <select onChange={(event: React.ChangeEvent<any>) => this.handleChange(event.target.value)} value={selectedValue} > {dropdownValues.map((value: string) => ( <option key={value}>{value}</option> ))} </select> <style jsx>{` .Dropdown { } `}</style> </div> ) } } export default Dropdown
Use 'value' instead of 'defaultValue'
Use 'value' instead of 'defaultValue'
TypeScript
mit
aranja/tux,aranja/tux,aranja/tux
--- +++ @@ -11,17 +11,17 @@ } export interface State { - selectedValue: string | null, + selectedValue: string | undefined, } class Dropdown extends Component<any, State> { state: State = { - selectedValue: null, + selectedValue: undefined, } componentDidMount() { const { value } = this.props - console.log(value) + this.setState({ selectedValue: value }) @@ -46,9 +46,10 @@ <label className="InputLabel">{label}</label> <select onChange={(event: React.ChangeEvent<any>) => this.handleChange(event.target.value)} + value={selectedValue} > {dropdownValues.map((value: string) => ( - <option key={value} selected={value === selectedValue}>{value}</option> + <option key={value}>{value}</option> ))} </select> <style jsx>{`
c7f210ff7023d17b788b4fc408878544c94bc99e
app/elements/element.component.ts
app/elements/element.component.ts
import { Component, Input, Output, EventEmitter, OnChanges } from '@angular/core'; import { Element } from './element'; @Component({ moduleId: module.id, selector: 'pt-element', templateUrl: 'element.component.html', styleUrls: ['element.component.css'] }) export class ElementComponent implements OnChanges { @Input() elementData: Element; // ^ exposes elementData property to parent component, listens for parent component to send data to child @Output() elementHovered: EventEmitter<Object> = new EventEmitter<Object>(); // ^ exposes which element is being hovered on to the parent component, sends proper data to hoverReceived fxn elementStyle: Object = {}; ngOnChanges(): void { console.log('this ran'); if (this.elementData.highlight) { this.elementStyle = {'background-color': 'pink'}; } } onHover(): void { console.log(this.elementData); this.elementHovered.emit(this.elementData); } // ^ sends data into emit channel to be picked up by parent component }
import { Component, Input, Output, EventEmitter, DoCheck } from '@angular/core'; import { Element } from './element'; @Component({ moduleId: module.id, selector: 'pt-element', templateUrl: 'element.component.html', styleUrls: ['element.component.css'] }) export class ElementComponent implements DoCheck { @Input() elementData: Element; // ^ exposes elementData property to parent component, listens for parent component to send data to child @Output() elementHovered: EventEmitter<Object> = new EventEmitter<Object>(); // ^ exposes which element is being hovered on to the parent component, sends proper data to hoverReceived fxn elementStyle: Object = {}; ngDoCheck() { if (this.elementData.highlight) { this.elementStyle = {'background-color': 'pink'}; } else { this.elementStyle = {'background-color': 'transparent'}; } } onHover(): void { this.elementHovered.emit(this.elementData); } // ^ sends data into emit channel to be picked up by parent component }
Add working transition metal highlight
Add working transition metal highlight
TypeScript
mit
joyceky/interactive-periodic-table,joyceky/interactive-periodic-table,joyceky/interactive-periodic-table
--- +++ @@ -1,4 +1,4 @@ -import { Component, Input, Output, EventEmitter, OnChanges } from '@angular/core'; +import { Component, Input, Output, EventEmitter, DoCheck } from '@angular/core'; import { Element } from './element'; @Component({ @@ -9,7 +9,7 @@ }) -export class ElementComponent implements OnChanges { +export class ElementComponent implements DoCheck { @Input() elementData: Element; // ^ exposes elementData property to parent component, listens for parent component to send data to child @@ -18,15 +18,15 @@ elementStyle: Object = {}; - ngOnChanges(): void { - console.log('this ran'); + ngDoCheck() { if (this.elementData.highlight) { this.elementStyle = {'background-color': 'pink'}; + } else { + this.elementStyle = {'background-color': 'transparent'}; } } onHover(): void { - console.log(this.elementData); this.elementHovered.emit(this.elementData); } // ^ sends data into emit channel to be picked up by parent component
b102312ac99faed18dde95f5b5cca898625398d4
types/htmlbars-inline-precompile/index.d.ts
types/htmlbars-inline-precompile/index.d.ts
// Type definitions for htmlbars-inline-precompile 1.0 // Project: ember-cli-htmlbars-inline-precompile // Definitions by: Chris Krycho <https://github.com/chriskrycho> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // This is a bit of a funky one: it's from a [Babel plugin], but is exported for // Ember applications as the module `"htmlbars-inline-precompile"`. It acts // like a tagged string from the perspective of consumers, but is actually an // AST transformation which generates a function as its output. That function in // turn [generates a string or array of strings][output] to use with the Ember // testing helper `this.render()`. // // [Babel plugin]: https://github.com/ember-cli/babel-plugin-htmlbars-inline-precompile#babel-plugin-htmlbars-inline-precompile- // [output]: https://github.com/emberjs/ember-test-helpers/blob/77f9a53da9d8c19a85b3122788caadbcc59274c2/lib/ember-test-helpers/-legacy-overrides.js#L17-L42 export default function hbs(tagged: TemplateStringsArray): string | string[];
// Type definitions for htmlbars-inline-precompile 1.0 // Project: https://github.com/ember-cli/ember-cli-htmlbars-inline-precompile // Definitions by: Chris Krycho <https://github.com/chriskrycho> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // This is a bit of a funky one: it's from a [Babel plugin], but is exported for // Ember applications as the module `"htmlbars-inline-precompile"`. It acts // like a tagged string from the perspective of consumers, but is actually an // AST transformation which generates a function as its output. That function in // turn [generates a string or array of strings][output] to use with the Ember // testing helper `this.render()`. // // [Babel plugin]: https://github.com/ember-cli/babel-plugin-htmlbars-inline-precompile#babel-plugin-htmlbars-inline-precompile- // [output]: https://github.com/emberjs/ember-test-helpers/blob/77f9a53da9d8c19a85b3122788caadbcc59274c2/lib/ember-test-helpers/-legacy-overrides.js#L17-L42 export default function hbs(tagged: TemplateStringsArray): string | string[];
Change project to URL for htmlbars-inline-precompile.
Change project to URL for htmlbars-inline-precompile.
TypeScript
mit
benishouga/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,nycdotnet/DefinitelyTyped,dsebastien/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,arusakov/DefinitelyTyped,rolandzwaga/DefinitelyTyped,aciccarello/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,one-pieces/DefinitelyTyped,magny/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,mcliment/DefinitelyTyped,zuzusik/DefinitelyTyped,chrootsu/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,abbasmhd/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,nycdotnet/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,alexdresko/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,abbasmhd/DefinitelyTyped,jimthedev/DefinitelyTyped,benliddicott/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,markogresak/DefinitelyTyped,benishouga/DefinitelyTyped,jimthedev/DefinitelyTyped,benishouga/DefinitelyTyped,zuzusik/DefinitelyTyped,borisyankov/DefinitelyTyped
--- +++ @@ -1,5 +1,5 @@ // Type definitions for htmlbars-inline-precompile 1.0 -// Project: ember-cli-htmlbars-inline-precompile +// Project: https://github.com/ember-cli/ember-cli-htmlbars-inline-precompile // Definitions by: Chris Krycho <https://github.com/chriskrycho> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
e3296fbb4c729f61f1a1394ea839412b83cd7269
client/src/queryEditor/DocumentTitle.ts
client/src/queryEditor/DocumentTitle.ts
import { useEffect } from 'react'; import { useSessionQueryName } from '../stores/editor-store'; /** * This component isolates the work of updating the document title on query name changes. * This is a component to prevent the main QueryEditor component from rendering on name change. * @param {object} props */ function DocumentTitle({ queryId }: { queryId: string }) { const queryName = useSessionQueryName(); const title = queryId === '' ? 'New query' : queryName; useEffect(() => { document.title = title; }, [title]); return null; } export default DocumentTitle;
import { useSessionQueryName } from '../stores/editor-store'; /** * This component isolates the work of updating the document title on query name changes. * This is a component to prevent the main QueryEditor component from rendering on name change. * @param {object} props */ function DocumentTitle({ queryId }: { queryId: string }) { const queryName = useSessionQueryName(); const title = queryId === '' ? 'New query' : queryName; if (document.title !== title) { console.log('updating title'); document.title = title; } return null; } export default DocumentTitle;
Fix document title not changing on sign in
Fix document title not changing on sign in
TypeScript
mit
rickbergfalk/sqlpad,rickbergfalk/sqlpad,rickbergfalk/sqlpad
--- +++ @@ -1,4 +1,3 @@ -import { useEffect } from 'react'; import { useSessionQueryName } from '../stores/editor-store'; /** @@ -10,9 +9,10 @@ const queryName = useSessionQueryName(); const title = queryId === '' ? 'New query' : queryName; - useEffect(() => { + if (document.title !== title) { + console.log('updating title'); document.title = title; - }, [title]); + } return null; }
468522f07b6b465fb54c4d718f7892e1c6988875
test/functional/migrations/show-command/command.ts
test/functional/migrations/show-command/command.ts
import "reflect-metadata"; import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../../utils/test-utils"; import {Connection} from "../../../../src/connection/Connection"; describe("migrations > show command", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ migrations: [__dirname + "/migration/*.js"], enabledDrivers: ["mysql", "mariadb", "oracle", "mssql", "sqljs", "sqlite", "postgres"], schemaCreate: true, dropSchema: true, })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("can recognise pending migrations", () => Promise.all(connections.map(async connection => { const migrations = await connection.showMigrations(); migrations.should.be.equal(true); }))); it("can recognise no pending migrations", () => Promise.all(connections.map(async connection => { await connection.runMigrations(); const migrations = await connection.showMigrations(); migrations.should.be.equal(false); }))); });
import "reflect-metadata"; import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../../utils/test-utils"; import {Connection} from "../../../../src/connection/Connection"; describe("migrations > show command", () => { let connections: Connection[]; before(async () => connections = await createTestingConnections({ migrations: [__dirname + "/migration/*.js"], enabledDrivers: ["postgres"], schemaCreate: true, dropSchema: true, })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("can recognise pending migrations", () => Promise.all(connections.map(async connection => { const migrations = await connection.showMigrations(); migrations.should.be.equal(true); }))); it("can recognise no pending migrations", () => Promise.all(connections.map(async connection => { await connection.runMigrations(); const migrations = await connection.showMigrations(); migrations.should.be.equal(false); }))); });
Revert "enable test for all db drivers"
Revert "enable test for all db drivers" This reverts commit ff505cc98c93bb2132571ce23f86af116f8ea43a.
TypeScript
mit
typeorm/typeorm,typeorm/typeorm,typeorm/typeorm,gintsgints/typeorm,gintsgints/typeorm
--- +++ @@ -6,7 +6,7 @@ let connections: Connection[]; before(async () => connections = await createTestingConnections({ migrations: [__dirname + "/migration/*.js"], - enabledDrivers: ["mysql", "mariadb", "oracle", "mssql", "sqljs", "sqlite", "postgres"], + enabledDrivers: ["postgres"], schemaCreate: true, dropSchema: true, }));
88a59afc31807fac8a09f8edf89b31b22161ab96
connect-flash/connect-flash-tests.ts
connect-flash/connect-flash-tests.ts
/// <reference path="./connect-flash.d.ts" /> import express = require('express'); import flash = require('connect-flash'); var app = express(); app.use(flash()); app.use(flash({ unsafe: false })); app.use(function(req: Express.Request, res, next) { req.flash('Message'); req.flash('info', 'Message'); });
/// <reference path="./connect-flash.d.ts" /> import express = require('express'); import flash = require('connect-flash'); var app = express(); app.use(flash()); app.use(flash({ unsafe: false })); app.use(function(req: Express.Request, res: Express.Response, next: Function) { req.flash('Message'); req.flash('info', 'Message'); });
Fix Travis CI failing because of "error TS7006: Parameter 'res' and 'next' implicitly have an 'any' type."
Fix Travis CI failing because of "error TS7006: Parameter 'res' and 'next' implicitly have an 'any' type."
TypeScript
mit
dpsthree/DefinitelyTyped,AGBrown/DefinitelyTyped-ABContrib,GregOnNet/DefinitelyTyped,ajtowf/DefinitelyTyped,Karabur/DefinitelyTyped,forumone/DefinitelyTyped,Deathspike/DefinitelyTyped,billccn/DefinitelyTyped,donnut/DefinitelyTyped,scriby/DefinitelyTyped,gregoryagu/DefinitelyTyped,brainded/DefinitelyTyped,abmohan/DefinitelyTyped,progre/DefinitelyTyped,leoromanovsky/DefinitelyTyped,rolandzwaga/DefinitelyTyped,muenchdo/DefinitelyTyped,Dashlane/DefinitelyTyped,mjjames/DefinitelyTyped,pocesar/DefinitelyTyped,arusakov/DefinitelyTyped,nainslie/DefinitelyTyped,dmoonfire/DefinitelyTyped,jsaelhof/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,danfma/DefinitelyTyped,behzad888/DefinitelyTyped,Dashlane/DefinitelyTyped,HPFOD/DefinitelyTyped,amanmahajan7/DefinitelyTyped,ml-workshare/DefinitelyTyped,lbesson/DefinitelyTyped,EnableSoftware/DefinitelyTyped,jesseschalken/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,magny/DefinitelyTyped,gildorwang/DefinitelyTyped,nabeix/DefinitelyTyped,Ridermansb/DefinitelyTyped,lseguin42/DefinitelyTyped,Ptival/DefinitelyTyped,nainslie/DefinitelyTyped,flyfishMT/DefinitelyTyped,vasek17/DefinitelyTyped,bencoveney/DefinitelyTyped,timjk/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,psnider/DefinitelyTyped,applesaucers/lodash-invokeMap,johan-gorter/DefinitelyTyped,jasonswearingen/DefinitelyTyped,pocesar/DefinitelyTyped,paulmorphy/DefinitelyTyped,mareek/DefinitelyTyped,giggio/DefinitelyTyped,fishgoh0nk/DefinitelyTyped,zuohaocheng/DefinitelyTyped,OpenMaths/DefinitelyTyped,mendix/DefinitelyTyped,teves-castro/DefinitelyTyped,DustinWehr/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,scsouthw/DefinitelyTyped,gcastre/DefinitelyTyped,mattblang/DefinitelyTyped,isman-usoh/DefinitelyTyped,vagarenko/DefinitelyTyped,dariajung/DefinitelyTyped,Karabur/DefinitelyTyped,bdoss/DefinitelyTyped,wcomartin/DefinitelyTyped,vagarenko/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,evandrewry/DefinitelyTyped,dsebastien/DefinitelyTyped,the41/DefinitelyTyped,dreampulse/DefinitelyTyped,mcliment/DefinitelyTyped,glenndierckx/DefinitelyTyped,Nemo157/DefinitelyTyped,aindlq/DefinitelyTyped,use-strict/DefinitelyTyped,ErykB2000/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,aciccarello/DefinitelyTyped,jaysoo/DefinitelyTyped,davidsidlinger/DefinitelyTyped,arcticwaters/DefinitelyTyped,ciriarte/DefinitelyTyped,abbasmhd/DefinitelyTyped,pwelter34/DefinitelyTyped,dmoonfire/DefinitelyTyped,nakakura/DefinitelyTyped,Almouro/DefinitelyTyped,superduper/DefinitelyTyped,behzad888/DefinitelyTyped,mcrawshaw/DefinitelyTyped,Dominator008/DefinitelyTyped,xswordsx/DefinitelyTyped,danfma/DefinitelyTyped,Zorgatone/DefinitelyTyped,rcchen/DefinitelyTyped,jeffbcross/DefinitelyTyped,biomassives/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,benishouga/DefinitelyTyped,mshmelev/DefinitelyTyped,rschmukler/DefinitelyTyped,alextkachman/DefinitelyTyped,wkrueger/DefinitelyTyped,frogcjn/DefinitelyTyped,martinduparc/DefinitelyTyped,nycdotnet/DefinitelyTyped,micurs/DefinitelyTyped,dwango-js/DefinitelyTyped,Riron/DefinitelyTyped,samwgoldman/DefinitelyTyped,NelsonLamprecht/DefinitelyTyped,arma-gast/DefinitelyTyped,jbrantly/DefinitelyTyped,flyfishMT/DefinitelyTyped,sandersky/DefinitelyTyped,pocke/DefinitelyTyped,abbasmhd/DefinitelyTyped,AgentME/DefinitelyTyped,jsaelhof/DefinitelyTyped,davidpricedev/DefinitelyTyped,chocolatechipui/DefinitelyTyped,Dominator008/DefinitelyTyped,takenet/DefinitelyTyped,greglockwood/DefinitelyTyped,olemp/DefinitelyTyped,nfriend/DefinitelyTyped,hesselink/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,axelcostaspena/DefinitelyTyped,tinganho/DefinitelyTyped,johan-gorter/DefinitelyTyped,nodeframe/DefinitelyTyped,aqua89/DefinitelyTyped,amir-arad/DefinitelyTyped,bpowers/DefinitelyTyped,chrootsu/DefinitelyTyped,gandjustas/DefinitelyTyped,davidpricedev/DefinitelyTyped,quantumman/DefinitelyTyped,rcchen/DefinitelyTyped,reppners/DefinitelyTyped,stanislavHamara/DefinitelyTyped,PascalSenn/DefinitelyTyped,tigerxy/DefinitelyTyped,paulmorphy/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,MarlonFan/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,arma-gast/DefinitelyTyped,shlomiassaf/DefinitelyTyped,alextkachman/DefinitelyTyped,sledorze/DefinitelyTyped,Jwsonic/DefinitelyTyped,gandjustas/DefinitelyTyped,jraymakers/DefinitelyTyped,gedaiu/DefinitelyTyped,innerverse/DefinitelyTyped,psnider/DefinitelyTyped,robl499/DefinitelyTyped,BrandonCKrueger/DefinitelyTyped,emanuelhp/DefinitelyTyped,tan9/DefinitelyTyped,tarruda/DefinitelyTyped,Trapulo/DefinitelyTyped,mcrawshaw/DefinitelyTyped,newclear/DefinitelyTyped,QuatroCode/DefinitelyTyped,bennett000/DefinitelyTyped,furny/DefinitelyTyped,hellopao/DefinitelyTyped,scriby/DefinitelyTyped,magny/DefinitelyTyped,shahata/DefinitelyTyped,Syati/DefinitelyTyped,moonpyk/DefinitelyTyped,jacqt/DefinitelyTyped,masonkmeyer/DefinitelyTyped,uestcNaldo/DefinitelyTyped,wilfrem/DefinitelyTyped,wbuchwalter/DefinitelyTyped,musically-ut/DefinitelyTyped,nojaf/DefinitelyTyped,one-pieces/DefinitelyTyped,chrismbarr/DefinitelyTyped,erosb/DefinitelyTyped,UzEE/DefinitelyTyped,rfranco/DefinitelyTyped,florentpoujol/DefinitelyTyped,martinduparc/DefinitelyTyped,hiraash/DefinitelyTyped,progre/DefinitelyTyped,smrq/DefinitelyTyped,dydek/DefinitelyTyped,kmeurer/DefinitelyTyped,aroder/DefinitelyTyped,Minishlink/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,Pro/DefinitelyTyped,trystanclarke/DefinitelyTyped,algorithme/DefinitelyTyped,benliddicott/DefinitelyTyped,Pipe-shen/DefinitelyTyped,vincentw56/DefinitelyTyped,takenet/DefinitelyTyped,blink1073/DefinitelyTyped,Chris380/DefinitelyTyped,AgentME/DefinitelyTyped,theyelllowdart/DefinitelyTyped,deeleman/DefinitelyTyped,HereSinceres/DefinitelyTyped,JaminFarr/DefinitelyTyped,abner/DefinitelyTyped,jasonswearingen/DefinitelyTyped,rschmukler/DefinitelyTyped,duongphuhiep/DefinitelyTyped,emanuelhp/DefinitelyTyped,Lorisu/DefinitelyTyped,esperco/DefinitelyTyped,paxibay/DefinitelyTyped,mwain/DefinitelyTyped,glenndierckx/DefinitelyTyped,robertbaker/DefinitelyTyped,bilou84/DefinitelyTyped,MidnightDesign/DefinitelyTyped,manekovskiy/DefinitelyTyped,IAPark/DefinitelyTyped,esperco/DefinitelyTyped,stacktracejs/DefinitelyTyped,bardt/DefinitelyTyped,fredgalvao/DefinitelyTyped,mattanja/DefinitelyTyped,subjectix/DefinitelyTyped,felipe3dfx/DefinitelyTyped,Syati/DefinitelyTyped,schmuli/DefinitelyTyped,sixinli/DefinitelyTyped,alexdresko/DefinitelyTyped,teves-castro/DefinitelyTyped,mareek/DefinitelyTyped,benishouga/DefinitelyTyped,xica/DefinitelyTyped,minodisk/DefinitelyTyped,greglo/DefinitelyTyped,QuatroCode/DefinitelyTyped,rerezz/DefinitelyTyped,bruennijs/DefinitelyTyped,basp/DefinitelyTyped,borisyankov/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,grahammendick/DefinitelyTyped,drinchev/DefinitelyTyped,shlomiassaf/DefinitelyTyped,borisyankov/DefinitelyTyped,subash-a/DefinitelyTyped,nmalaguti/DefinitelyTyped,pwelter34/DefinitelyTyped,maxlang/DefinitelyTyped,alainsahli/DefinitelyTyped,Kuniwak/DefinitelyTyped,Litee/DefinitelyTyped,TheBay0r/DefinitelyTyped,TildaLabs/DefinitelyTyped,adamcarr/DefinitelyTyped,mattanja/DefinitelyTyped,newclear/DefinitelyTyped,zuzusik/DefinitelyTyped,bjfletcher/DefinitelyTyped,Bunkerbewohner/DefinitelyTyped,Bobjoy/DefinitelyTyped,onecentlin/DefinitelyTyped,lucyhe/DefinitelyTyped,amanmahajan7/DefinitelyTyped,UzEE/DefinitelyTyped,dflor003/DefinitelyTyped,ayanoin/DefinitelyTyped,eekboom/DefinitelyTyped,syuilo/DefinitelyTyped,fredgalvao/DefinitelyTyped,Penryn/DefinitelyTyped,kuon/DefinitelyTyped,YousefED/DefinitelyTyped,zuzusik/DefinitelyTyped,WritingPanda/DefinitelyTyped,use-strict/DefinitelyTyped,Zenorbi/DefinitelyTyped,pkhayundi/DefinitelyTyped,raijinsetsu/DefinitelyTyped,jraymakers/DefinitelyTyped,YousefED/DefinitelyTyped,elisee/DefinitelyTyped,Garciat/DefinitelyTyped,Gmulti/DefinitelyTyped,NCARalph/DefinitelyTyped,reppners/DefinitelyTyped,PopSugar/DefinitelyTyped,icereed/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,donnut/DefinitelyTyped,hellopao/DefinitelyTyped,kalloc/DefinitelyTyped,corps/DefinitelyTyped,KonaTeam/DefinitelyTyped,martinduparc/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,egeland/DefinitelyTyped,yuit/DefinitelyTyped,ryan10132/DefinitelyTyped,stephenjelfs/DefinitelyTyped,isman-usoh/DefinitelyTyped,ecramer89/DefinitelyTyped,nseckinoral/DefinitelyTyped,wilfrem/DefinitelyTyped,ashwinr/DefinitelyTyped,mhegazy/DefinitelyTyped,iCoreSolutions/DefinitelyTyped,applesaucers/lodash-invokeMap,brentonhouse/DefinitelyTyped,OpenMaths/DefinitelyTyped,optical/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,sclausen/DefinitelyTyped,hypno2000/typings,hor-crux/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jimthedev/DefinitelyTyped,daptiv/DefinitelyTyped,mvarblow/DefinitelyTyped,nelsonmorais/DefinitelyTyped,acepoblete/DefinitelyTyped,cherrydev/DefinitelyTyped,LordJZ/DefinitelyTyped,eugenpodaru/DefinitelyTyped,EnableSoftware/DefinitelyTyped,michalczukm/DefinitelyTyped,Carreau/DefinitelyTyped,nakakura/DefinitelyTyped,stacktracejs/DefinitelyTyped,dsebastien/DefinitelyTyped,dydek/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,jccarvalhosa/DefinitelyTyped,jtlan/DefinitelyTyped,tboyce/DefinitelyTyped,nitintutlani/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,haskellcamargo/DefinitelyTyped,gdi2290/DefinitelyTyped,pafflique/DefinitelyTyped,florentpoujol/DefinitelyTyped,syuilo/DefinitelyTyped,alexdresko/DefinitelyTyped,onecentlin/DefinitelyTyped,greglo/DefinitelyTyped,mweststrate/DefinitelyTyped,chrootsu/DefinitelyTyped,schmuli/DefinitelyTyped,adammartin1981/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,alvarorahul/DefinitelyTyped,jiaz/DefinitelyTyped,digitalpixies/DefinitelyTyped,mshmelev/DefinitelyTyped,chrismbarr/DefinitelyTyped,Penryn/DefinitelyTyped,zuzusik/DefinitelyTyped,stephenjelfs/DefinitelyTyped,yuit/DefinitelyTyped,maglar0/DefinitelyTyped,Fraegle/DefinitelyTyped,OfficeDev/DefinitelyTyped,fearthecowboy/DefinitelyTyped,lbguilherme/DefinitelyTyped,dragouf/DefinitelyTyped,egeland/DefinitelyTyped,nobuoka/DefinitelyTyped,olivierlemasle/DefinitelyTyped,laball/DefinitelyTyped,musicist288/DefinitelyTyped,ashwinr/DefinitelyTyped,Zzzen/DefinitelyTyped,georgemarshall/DefinitelyTyped,bluong/DefinitelyTyped,hatz48/DefinitelyTyped,alvarorahul/DefinitelyTyped,vsavkin/DefinitelyTyped,almstrand/DefinitelyTyped,philippstucki/DefinitelyTyped,Mek7/DefinitelyTyped,SebastianCoetzee/DefinitelyTyped,gyohk/DefinitelyTyped,aciccarello/DefinitelyTyped,omidkrad/DefinitelyTyped,raijinsetsu/DefinitelyTyped,nitintutlani/DefinitelyTyped,aciccarello/DefinitelyTyped,lightswitch05/DefinitelyTyped,bdoss/DefinitelyTyped,jeremyhayes/DefinitelyTyped,CSharpFan/DefinitelyTyped,chrilith/DefinitelyTyped,mrk21/DefinitelyTyped,gyohk/DefinitelyTyped,goaty92/DefinitelyTyped,angelobelchior8/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,nobuoka/DefinitelyTyped,RX14/DefinitelyTyped,optical/DefinitelyTyped,sclausen/DefinitelyTyped,zalamtech/DefinitelyTyped,damianog/DefinitelyTyped,damianog/DefinitelyTyped,whoeverest/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,drinchev/DefinitelyTyped,psnider/DefinitelyTyped,Litee/DefinitelyTyped,dumbmatter/DefinitelyTyped,zhiyiting/DefinitelyTyped,laco0416/DefinitelyTyped,AgentME/DefinitelyTyped,herrmanno/DefinitelyTyped,duncanmak/DefinitelyTyped,Seltzer/DefinitelyTyped,scatcher/DefinitelyTyped,Pro/DefinitelyTyped,frogcjn/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,MugeSo/DefinitelyTyped,olemp/DefinitelyTyped,minodisk/DefinitelyTyped,TanakaYutaro/DefinitelyTyped,hx0day/DefinitelyTyped,tomtarrot/DefinitelyTyped,M-Zuber/DefinitelyTyped,trystanclarke/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,georgemarshall/DefinitelyTyped,musakarakas/DefinitelyTyped,sledorze/DefinitelyTyped,unknownloner/DefinitelyTyped,munxar/DefinitelyTyped,robert-voica/DefinitelyTyped,elisee/DefinitelyTyped,mhegazy/DefinitelyTyped,markogresak/DefinitelyTyped,bridge-ufsc/DefinitelyTyped,Shiak1/DefinitelyTyped,MugeSo/DefinitelyTyped,kanreisa/DefinitelyTyped,lekaha/DefinitelyTyped,igorraush/DefinitelyTyped,Zorgatone/DefinitelyTyped,Ptival/DefinitelyTyped,arusakov/DefinitelyTyped,drillbits/DefinitelyTyped,tan9/DefinitelyTyped,igorsechyn/DefinitelyTyped,rockclimber90/DefinitelyTyped,TrabacchinLuigi/DefinitelyTyped,opichals/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,takfjt/DefinitelyTyped,jimthedev/DefinitelyTyped,DeadAlready/DefinitelyTyped,spearhead-ea/DefinitelyTyped,timramone/DefinitelyTyped,shovon/DefinitelyTyped,benishouga/DefinitelyTyped,cesarmarinhorj/DefinitelyTyped,fnipo/DefinitelyTyped,mjjames/DefinitelyTyped,rushi216/DefinitelyTyped,stylelab-io/DefinitelyTyped,hellopao/DefinitelyTyped,nycdotnet/DefinitelyTyped,tjoskar/DefinitelyTyped,syntax42/DefinitelyTyped,GodsBreath/DefinitelyTyped,pocesar/DefinitelyTyped,nmalaguti/DefinitelyTyped,teddyward/DefinitelyTyped,Zzzen/DefinitelyTyped,xStrom/DefinitelyTyped,chadoliver/DefinitelyTyped,arusakov/DefinitelyTyped,philippstucki/DefinitelyTyped,hafenr/DefinitelyTyped,georgemarshall/DefinitelyTyped,subash-a/DefinitelyTyped,DenEwout/DefinitelyTyped,abner/DefinitelyTyped,cvrajeesh/DefinitelyTyped,richardTowers/DefinitelyTyped,chbrown/DefinitelyTyped,ahmedalsudani/DefinitelyTyped,AgentME/DefinitelyTyped,brettle/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,aldo-roman/DefinitelyTyped,mattblang/DefinitelyTyped,ducin/DefinitelyTyped,xStrom/DefinitelyTyped,ajtowf/DefinitelyTyped,HPFOD/DefinitelyTyped,mszczepaniak/DefinitelyTyped,DeluxZ/DefinitelyTyped,bennett000/DefinitelyTyped,arcticwaters/DefinitelyTyped,RedSeal-co/DefinitelyTyped,hatz48/DefinitelyTyped,bkristensen/DefinitelyTyped,Saneyan/DefinitelyTyped,RX14/DefinitelyTyped,schmuli/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,vpineda1996/DefinitelyTyped,Seikho/DefinitelyTyped,tdmckinn/DefinitelyTyped,zensh/DefinitelyTyped,smrq/DefinitelyTyped,gorcz/DefinitelyTyped,gcastre/DefinitelyTyped,tscho/DefinitelyTyped
--- +++ @@ -10,7 +10,7 @@ unsafe: false })); -app.use(function(req: Express.Request, res, next) { +app.use(function(req: Express.Request, res: Express.Response, next: Function) { req.flash('Message'); req.flash('info', 'Message'); });
c05248057e9cbdc48382ecb58ec38e600d178673
packages/shared/lib/authentication/cryptoHelper.ts
packages/shared/lib/authentication/cryptoHelper.ts
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; const IV_LENGTH = 16; const ALGORITHM = 'AES-GCM'; export const getKey = (key: Uint8Array, keyUsage: KeyUsage[] = ['decrypt', 'encrypt']) => { return window.crypto.subtle.importKey('raw', key.buffer, ALGORITHM, false, keyUsage); }; export const encryptData = async (key: CryptoKey, data: Uint8Array) => { const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH)); const cipher = await window.crypto.subtle.encrypt( { name: ALGORITHM, iv, }, key, data ); return mergeUint8Arrays([iv, new Uint8Array(cipher)]); }; export const decryptData = async (key: CryptoKey, data: Uint8Array) => { const iv = data.slice(0, IV_LENGTH); const cipher = data.slice(IV_LENGTH, data.length); const result = await window.crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, cipher); return new Uint8Array(result); };
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; const IV_LENGTH = 16; const ALGORITHM = 'AES-GCM'; export const getKey = (key: Uint8Array, keyUsage: KeyUsage[] = ['decrypt', 'encrypt']) => { return crypto.subtle.importKey('raw', key.buffer, ALGORITHM, false, keyUsage); }; export const encryptData = async (key: CryptoKey, data: Uint8Array) => { const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH)); const cipher = await crypto.subtle.encrypt( { name: ALGORITHM, iv, }, key, data ); return mergeUint8Arrays([iv, new Uint8Array(cipher)]); }; export const decryptData = async (key: CryptoKey, data: Uint8Array) => { const iv = data.slice(0, IV_LENGTH); const cipher = data.slice(IV_LENGTH, data.length); const result = await crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, cipher); return new Uint8Array(result); };
Replace window.crypto references in crypto helpers
Replace window.crypto references in crypto helpers - Agnostic global access to crypto (needed for usage in service workers)
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -4,12 +4,12 @@ const ALGORITHM = 'AES-GCM'; export const getKey = (key: Uint8Array, keyUsage: KeyUsage[] = ['decrypt', 'encrypt']) => { - return window.crypto.subtle.importKey('raw', key.buffer, ALGORITHM, false, keyUsage); + return crypto.subtle.importKey('raw', key.buffer, ALGORITHM, false, keyUsage); }; export const encryptData = async (key: CryptoKey, data: Uint8Array) => { - const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH)); - const cipher = await window.crypto.subtle.encrypt( + const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH)); + const cipher = await crypto.subtle.encrypt( { name: ALGORITHM, iv, @@ -23,6 +23,6 @@ export const decryptData = async (key: CryptoKey, data: Uint8Array) => { const iv = data.slice(0, IV_LENGTH); const cipher = data.slice(IV_LENGTH, data.length); - const result = await window.crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, cipher); + const result = await crypto.subtle.decrypt({ name: ALGORITHM, iv }, key, cipher); return new Uint8Array(result); };
e45a7268501b63562d9c8591c437212c589716b5
src/index.tsx
src/index.tsx
import "react-app-polyfill/ie9"; import "react-app-polyfill/stable"; import "core-js/es/array/is-array"; import "core-js/es/map"; import "core-js/es/set"; import "core-js/es/object/define-property"; import "core-js/es/object/keys"; import "core-js/es/object/set-prototype-of"; import "./polyfills/classlist"; import React from "react"; import ReactDOM from "react-dom"; import App from "./app"; import ApiClient from "./api"; import "./index.scss"; // grid configuration const gridConfig = { cols: 12, margin: [10, 10], containerPadding: [10, 10], rowHeight: 80, }; const root = document.getElementById("ld-app"); if (root) { root.className = ""; const widgetsEls = Array.prototype.slice.call(root!.querySelectorAll("div")); const widgets = widgetsEls.map(el => ({ html: el.innerHTML, config: JSON.parse(el.getAttribute("data-grid")), })); const api = new ApiClient(root.getAttribute("data-dashboard-endpoint") || ""); ReactDOM.render( <App widgets={widgets} dashboardId={root.getAttribute("data-dashboard")} api={api} widgetTypes={JSON.parse(root.getAttribute("data-widget-types") || "[]")} gridConfig={gridConfig} />, root, ); }
import "react-app-polyfill/ie9"; import "react-app-polyfill/stable"; import "core-js/es/array/is-array"; import "core-js/es/map"; import "core-js/es/set"; import "core-js/es/object/define-property"; import "core-js/es/object/keys"; import "core-js/es/object/set-prototype-of"; import "./polyfills/classlist"; import React from "react"; import ReactDOM from "react-dom"; import App from "./app"; import ApiClient from "./api"; import "./index.scss"; const gridConfig = { cols: 12, margin: [10, 10], containerPadding: [10, 10], rowHeight: 80, }; const root = document.getElementById("ld-app"); if (root) { root.className = ""; const widgetsEls = Array.prototype.slice.call(document.querySelectorAll("#ld-app > div")); const widgets = widgetsEls.map(el => ({ html: el.innerHTML, config: JSON.parse(el.getAttribute("data-grid")), })); const api = new ApiClient(root.getAttribute("data-dashboard-endpoint") || ""); ReactDOM.render( <App widgets={widgets} dashboardId={root.getAttribute("data-dashboard")} api={api} widgetTypes={JSON.parse(root.getAttribute("data-widget-types") || "[]")} gridConfig={gridConfig} />, root, ); }
Fix query of widgets to only get direct children
Fix query of widgets to only get direct children
TypeScript
agpl-3.0
ctrlo/GADS,ctrlo/GADS,ctrlo/GADS,ctrlo/GADS,ctrlo/GADS
--- +++ @@ -16,7 +16,6 @@ import ApiClient from "./api"; import "./index.scss"; -// grid configuration const gridConfig = { cols: 12, margin: [10, 10], @@ -28,7 +27,7 @@ if (root) { root.className = ""; - const widgetsEls = Array.prototype.slice.call(root!.querySelectorAll("div")); + const widgetsEls = Array.prototype.slice.call(document.querySelectorAll("#ld-app > div")); const widgets = widgetsEls.map(el => ({ html: el.innerHTML, config: JSON.parse(el.getAttribute("data-grid")),
75b5819d73266e9efbc1d18e2368062900679b66
server/src/client/client-controller.ts
server/src/client/client-controller.ts
import express = require('express'); import path = require('path'); import fs = require('fs'); import edge = require('edge'); const app = require('../application'); const createClientEdge = edge.func(function () {/* async (input) => { return ".NET Welcomes " + input.ToString(); } */}); export function createNewClient(req: express.Request, res: express.Response): void { console.log('res body-->', req.body);//roberto res.status(200).send('New client added'); return; }
import express = require('express'); import path = require('path'); import fs = require('fs'); import edge = require('edge'); const app = require('../application'); const createClientEdge = edge.func(function () {/* async (input) => { return ".NET Welcomes " + input.ToString(); } */}); export function createNewClient(req: express.Request, res: express.Response): void { createClientEdge(null, function (error, result) { if (error) { res.status(500).send('Error executing the createClientEdge function'); return; }; console.log('result-->', result);//roberto res.status(200).send('New client added'); return; }); }
Call the create client edge function
Call the create client edge function
TypeScript
mit
RobertoMSousa/node-api-edge,RobertoMSousa/node-api-edge
--- +++ @@ -17,7 +17,13 @@ export function createNewClient(req: express.Request, res: express.Response): void { - console.log('res body-->', req.body);//roberto - res.status(200).send('New client added'); - return; + createClientEdge(null, function (error, result) { + if (error) { + res.status(500).send('Error executing the createClientEdge function'); + return; + }; + console.log('result-->', result);//roberto + res.status(200).send('New client added'); + return; + }); }
17fdb693a1eae0058f56eb5116dade5eca3d4b44
lib/msal-core/test/ScopeSet.spec.ts
lib/msal-core/test/ScopeSet.spec.ts
import { expect } from "chai"; import sinon from "sinon"; import { ScopeSet } from "../src/ScopeSet"; describe("ScopeSet.ts Unit Tests", () => { it("tests trimAndConvertArrayToLowerCase", () => { const scopeSet = ["S1", " S2", " S3 "]; expect(ScopeSet.trimAndConvertArrayToLowerCase(scopeSet)).to.be.deep.eq(["s1", "s2", "s3"]); }); it("tests trimAndConvertToLowerCase", () => { const scope = " S1 "; expect(ScopeSet.trimAndConvertToLowerCase(scope)).to.be.eq("s1"); }) });
import { expect } from "chai"; import sinon from "sinon"; import { ScopeSet } from "../src/ScopeSet"; describe("ScopeSet.ts Unit Tests", () => { it("tests trimAndConvertArrayToLowerCase", () => { const scopeSet = ["S1", " S2", " S3 "]; expect(ScopeSet.trimAndConvertArrayToLowerCase(scopeSet)).to.be.deep.eq(["s1", "s2", "s3"]); }); it("tests trimAndConvertToLowerCase", () => { const scope = " S1 "; expect(ScopeSet.trimAndConvertToLowerCase(scope)).to.be.eq("s1"); }); it("tests trimScopes", () => { const scopeSet = ["S1", " S2 ", " S3 "]; expect(ScopeSet.trimScopes(scopeSet)).to.be.deep.eq(["S1", "S2", "S3"]); }); });
Add unit test for trimScopes
Add unit test for trimScopes
TypeScript
mit
AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js
--- +++ @@ -12,5 +12,10 @@ it("tests trimAndConvertToLowerCase", () => { const scope = " S1 "; expect(ScopeSet.trimAndConvertToLowerCase(scope)).to.be.eq("s1"); - }) + }); + + it("tests trimScopes", () => { + const scopeSet = ["S1", " S2 ", " S3 "]; + expect(ScopeSet.trimScopes(scopeSet)).to.be.deep.eq(["S1", "S2", "S3"]); + }); });
eae74da28d31bbbceca2e3dfcdfd8c9788bf6683
packages/bitcore-node/test/unit/logger.spec.ts
packages/bitcore-node/test/unit/logger.spec.ts
import { expect } from 'chai'; import { unitAfterHelper, unitBeforeHelper } from '../helpers/unit'; describe('logger', function() { before(unitBeforeHelper); after(unitAfterHelper); it('should have a test which runs', function() { expect(true).to.equal(true); }); });
import { expect } from 'chai'; describe('logger', function() { it('should have a test which runs', function() { expect(true).to.equal(true); }); });
Remove before and after for empty tests
Remove before and after for empty tests
TypeScript
mit
martindale/bitcore,bitpay/bitcore,martindale/bitcore,bitpay/bitcore,bitpay/bitcore,bitpay/bitcore,martindale/bitcore,martindale/bitcore
--- +++ @@ -1,10 +1,6 @@ import { expect } from 'chai'; -import { unitAfterHelper, unitBeforeHelper } from '../helpers/unit'; describe('logger', function() { - before(unitBeforeHelper); - after(unitAfterHelper); - it('should have a test which runs', function() { expect(true).to.equal(true); });
b1ff1b71e5358cef21162f89f5ab3e6b25b4f574
src/app/data.service.ts
src/app/data.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; interface ItemsResponse { name: string; string: string; } @Injectable() export class DataService { url = 'http://localhost/artezian-info-web/src/assets/data.php'; usn: string = 'myusernamemyusername'; psd: string = 'mypasswordmypassword'; body: string = `username=${this.usn}&password=${this.psd}`; constructor(private http: HttpClient) {} getData() { const req = this.http.post<ItemsResponse> (this.url, this.body, { headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') }) .subscribe( res => { console.log(res.name + ' ' + res.string); }, err => { console.log(err); } ); } }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { MenuItem } from './interfaces/menu-item'; @Injectable() export class DataService { url = 'http://localhost/artezian-info-web/src/assets/data.php'; // req: string = `username=${this.usn}&password=${this.psd}`; req: string = 'get=menu'; constructor(private http: HttpClient) { } getMenu(): Observable<MenuItem[]> { return this.http.post(this.url, this.req, { headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') }).map((resp: MenuItem[]) => { let menu: MenuItem[] = resp; return menu; }); } }
Add get menu data to data servise
Add get menu data to data servise
TypeScript
mit
KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web,KeJSaR/artezian-info-web
--- +++ @@ -1,37 +1,28 @@ -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; import { HttpHeaders } from '@angular/common/http'; +import { Observable } from 'rxjs/Observable'; -interface ItemsResponse { - name: string; - string: string; -} +import 'rxjs/add/operator/map'; + +import { MenuItem } from './interfaces/menu-item'; @Injectable() export class DataService { + + url = 'http://localhost/artezian-info-web/src/assets/data.php'; + // req: string = `username=${this.usn}&password=${this.psd}`; + req: string = 'get=menu'; - url = 'http://localhost/artezian-info-web/src/assets/data.php'; - usn: string = 'myusernamemyusername'; - psd: string = 'mypasswordmypassword'; - body: string = `username=${this.usn}&password=${this.psd}`; + constructor(private http: HttpClient) { } - constructor(private http: HttpClient) {} - - getData() { - - const req = this.http.post<ItemsResponse> - (this.url, this.body, { + getMenu(): Observable<MenuItem[]> { + return this.http.post(this.url, this.req, { headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded') - }) - .subscribe( - res => { - console.log(res.name + ' ' + res.string); - }, - err => { - console.log(err); - } - ); - + }).map((resp: MenuItem[]) => { + let menu: MenuItem[] = resp; + return menu; + }); } }
3245edf9ea36f36d6573c6f35dbb0fa3686c235e
tests/main.ts
tests/main.ts
import * as fs from 'fs'; import build from './build'; import * as parseArgs from 'minimist'; for (let arg of parseArgs(process.argv.slice(2))._) { console.log(build(fs.readFileSync(arg, {encoding:'utf8'}))); }
import * as fs from 'fs'; import build from './build'; import * as parseArgs from 'minimist'; for (let inFile of parseArgs(process.argv.slice(2))._) { let outFile = inFile.substring(0, inFile.length - ".in.hledger".length) + ".want"; let converted = build(fs.readFileSync(inFile, {encoding:'utf8'})); fs.writeFileSync(outFile, converted, {encoding: 'utf8'}); }
Make it possible to convert an entire directory at once
Make it possible to convert an entire directory at once $ ts-node tests/main.ts tests/cases/**.in.hledger
TypeScript
mit
mhansen/hledger-vscode
--- +++ @@ -2,6 +2,8 @@ import build from './build'; import * as parseArgs from 'minimist'; -for (let arg of parseArgs(process.argv.slice(2))._) { - console.log(build(fs.readFileSync(arg, {encoding:'utf8'}))); +for (let inFile of parseArgs(process.argv.slice(2))._) { + let outFile = inFile.substring(0, inFile.length - ".in.hledger".length) + ".want"; + let converted = build(fs.readFileSync(inFile, {encoding:'utf8'})); + fs.writeFileSync(outFile, converted, {encoding: 'utf8'}); }
5cc1c7d5121c05ae464f585eadf59212743683d2
src/background-script/quick-and-dirty-migrations.ts
src/background-script/quick-and-dirty-migrations.ts
import { Dexie } from 'src/search/types' export interface Migrations { [storageKey: string]: (db: Dexie) => Promise<void> } export const migrations: Migrations = { /** * If lastEdited is undefined, then set it to createdWhen value. */ 'annots-created-when-to-last-edited': async db => { await db .table('annotations') .toCollection() .filter(annot => annot.lastEdited == null) .modify(annot => { annot.lastEdited = annot.createdWhen }) }, }
import { Dexie } from 'src/search/types' export interface Migrations { [storageKey: string]: (db: Dexie) => Promise<void> } export const migrations: Migrations = { /** * If lastEdited is undefined, then set it to createdWhen value. */ 'annots-created-when-to-last-edited': async db => { await db .table('annotations') .toCollection() .filter( annot => annot.lastEdited == null || (Object.keys(annot.lastEdited).length === 0 && annot.lastEdited.constructor === Object), ) .modify(annot => { annot.lastEdited = annot.createdWhen }) }, }
Fix bug with quick and dirty migration on upgrade
Fix bug with quick and dirty migration on upgrade
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -12,7 +12,12 @@ await db .table('annotations') .toCollection() - .filter(annot => annot.lastEdited == null) + .filter( + annot => + annot.lastEdited == null || + (Object.keys(annot.lastEdited).length === 0 && + annot.lastEdited.constructor === Object), + ) .modify(annot => { annot.lastEdited = annot.createdWhen })
4a8d4677319d3e65a2bf4435d7e15790faed5548
front_end/ui/components/helpers/component-server-setup.ts
front_end/ui/components/helpers/component-server-setup.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 type * as Common from '../../../core/common/common.js'; import * as Root from '../../../core/root/root.js'; import * as ThemeSupport from '../../legacy/theme_support/theme_support.js'; import {CSS_RESOURCES_TO_LOAD_INTO_RUNTIME} from './get-stylesheet.js'; /** * Houses any setup required to run the component docs server. Currently this is * only populating the runtime CSS cache but may be extended in the future. */ export async function setup(): Promise<void> { const setting = { get() { return 'default'; }, } as Common.Settings.Setting<string>; ThemeSupport.ThemeSupport.instance({forceNew: true, setting}); const allPromises = CSS_RESOURCES_TO_LOAD_INTO_RUNTIME.map(resourcePath => { return fetch('/front_end/' + resourcePath).then(response => response.text()).then(cssText => { Root.Runtime.cachedResources.set(resourcePath, cssText); }); }); await Promise.all(allPromises); }
// 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 type * as Common from '../../../core/common/common.js'; import * as Root from '../../../core/root/root.js'; import * as ThemeSupport from '../../legacy/theme_support/theme_support.js'; import {CSS_RESOURCES_TO_LOAD_INTO_RUNTIME} from './get-stylesheet.js'; /** * Houses any setup required to run the component docs server. Currently this is * only populating the runtime CSS cache but may be extended in the future. */ export async function setup(resourcesPrefix = ''): Promise<void> { const setting = { get() { return 'default'; }, } as Common.Settings.Setting<string>; ThemeSupport.ThemeSupport.instance({forceNew: true, setting}); const allPromises = CSS_RESOURCES_TO_LOAD_INTO_RUNTIME.map(resourcePath => { return fetch(resourcesPrefix + '/front_end/' + resourcePath).then(response => response.text()).then(cssText => { Root.Runtime.cachedResources.set(resourcePath, cssText); }); }); await Promise.all(allPromises); }
Allow component server setup to take a url prefix for resources
Allow component server setup to take a url prefix for resources Bug: none Change-Id: I206766a1ff9bb69c3802671aceb8e5c28545c4cf Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3109530 Commit-Queue: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org> Commit-Queue: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Auto-Submit: Jack Franklin <993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org> Reviewed-by: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org>
TypeScript
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
--- +++ @@ -12,7 +12,7 @@ * Houses any setup required to run the component docs server. Currently this is * only populating the runtime CSS cache but may be extended in the future. */ -export async function setup(): Promise<void> { +export async function setup(resourcesPrefix = ''): Promise<void> { const setting = { get() { return 'default'; @@ -21,7 +21,7 @@ ThemeSupport.ThemeSupport.instance({forceNew: true, setting}); const allPromises = CSS_RESOURCES_TO_LOAD_INTO_RUNTIME.map(resourcePath => { - return fetch('/front_end/' + resourcePath).then(response => response.text()).then(cssText => { + return fetch(resourcesPrefix + '/front_end/' + resourcePath).then(response => response.text()).then(cssText => { Root.Runtime.cachedResources.set(resourcePath, cssText); }); });
5a5c3ab58977e0945004dbc7c148a346da4423f8
wegas-app/src/main/webapp/2/src/data/Reducer/reducers.ts
wegas-app/src/main/webapp/2/src/data/Reducer/reducers.ts
import { Immutable } from 'immer'; import games, { GameState } from './game'; import gameModels, { GameModelState } from './gameModel'; import global, { GlobalState } from './globalState'; import pages, { PageState } from './pageState'; import players, { PlayerState } from './player'; import teams, { TeamState } from './teams'; import variableDescriptors, { VariableDescriptorState } from './variableDescriptor'; import variableInstances, { VariableInstanceState } from './variableInstance'; export interface State { gameModels: Immutable<GameModelState>; games: Immutable<GameState>; variableDescriptors: Immutable<VariableDescriptorState>; variableInstances: Immutable<VariableInstanceState>; global: Immutable<GlobalState>; pages: Immutable<PageState>; players: Immutable<PlayerState>; teams: Immutable<TeamState>; } export default { gameModels, variableDescriptors, variableInstances, global, pages, games, players, teams, };
import gameModels, { GameModelState } from './gameModel'; import variableDescriptors, { VariableDescriptorState, } from './variableDescriptor'; import variableInstances, { VariableInstanceState } from './variableInstance'; import global, { GlobalState } from './globalState'; import pages, { PageState } from './pageState'; import games, { GameState } from './game'; import players, { PlayerState } from './player'; import teams, { TeamState } from './teams'; export interface State { gameModels: Readonly<GameModelState>; games: Readonly<GameState>; variableDescriptors: Readonly<VariableDescriptorState>; variableInstances: Readonly<VariableInstanceState>; global: Readonly<GlobalState>; pages: Readonly<PageState>; players: Readonly<PlayerState>; teams: Readonly<TeamState>; } export default { gameModels, variableDescriptors, variableInstances, global, pages, games, players, teams, };
Revert "State Immutable (deep readonly) instead of RO"
Revert "State Immutable (deep readonly) instead of RO" This reverts commit 8bf9bdead9626ef3ce31c82a7e7bc0aec5b3c61a.
TypeScript
mit
Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas
--- +++ @@ -1,22 +1,23 @@ -import { Immutable } from 'immer'; -import games, { GameState } from './game'; import gameModels, { GameModelState } from './gameModel'; +import variableDescriptors, { + VariableDescriptorState, +} from './variableDescriptor'; +import variableInstances, { VariableInstanceState } from './variableInstance'; import global, { GlobalState } from './globalState'; import pages, { PageState } from './pageState'; +import games, { GameState } from './game'; import players, { PlayerState } from './player'; import teams, { TeamState } from './teams'; -import variableDescriptors, { VariableDescriptorState } from './variableDescriptor'; -import variableInstances, { VariableInstanceState } from './variableInstance'; export interface State { - gameModels: Immutable<GameModelState>; - games: Immutable<GameState>; - variableDescriptors: Immutable<VariableDescriptorState>; - variableInstances: Immutable<VariableInstanceState>; - global: Immutable<GlobalState>; - pages: Immutable<PageState>; - players: Immutable<PlayerState>; - teams: Immutable<TeamState>; + gameModels: Readonly<GameModelState>; + games: Readonly<GameState>; + variableDescriptors: Readonly<VariableDescriptorState>; + variableInstances: Readonly<VariableInstanceState>; + global: Readonly<GlobalState>; + pages: Readonly<PageState>; + players: Readonly<PlayerState>; + teams: Readonly<TeamState>; } export default {
c7172a2a6808e65cf26fb67f63f88523f03be901
test/e2e/animations/animations_test.ts
test/e2e/animations/animations_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 {describe, it} from 'mocha'; import {getBrowserAndPages} from '../../shared/helper.js'; import {navigateToSiteWithAnimation, waitForAnimationContent, waitForAnimationsPanelToLoad} from '../helpers/animations-helpers.js'; describe('The Animations Panel', async () => { it('Listens for animation in webpage', async () => { const {target} = getBrowserAndPages(); await waitForAnimationsPanelToLoad(); await navigateToSiteWithAnimation(target); await waitForAnimationContent(); }); });
// 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 {describe, it} from 'mocha'; import {getBrowserAndPages} from '../../shared/helper.js'; import {navigateToSiteWithAnimation, waitForAnimationContent, waitForAnimationsPanelToLoad} from '../helpers/animations-helpers.js'; describe.skip('[crbug.com/1082735] The Animations Panel', async () => { it('Listens for animation in webpage', async () => { const {target} = getBrowserAndPages(); await waitForAnimationsPanelToLoad(); await navigateToSiteWithAnimation(target); await waitForAnimationContent(); }); });
Disable the flaky Animations Panel test
Disable the flaky Animations Panel test The test is turning the tree red. TBR=dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: chromium:1082735 Change-Id: I01454ab9b25a72edf527c1d61b5a46fcda369b79 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/2201639 Reviewed-by: Philip Pfaffe <639a645feae3653b7aaefa0387217d375f2f82ff@chromium.org> Reviewed-by: Tim van der Lippe <dba8716ee7f8d16236046f74d2167cb94410f6ed@chromium.org> Commit-Queue: Philip Pfaffe <639a645feae3653b7aaefa0387217d375f2f82ff@chromium.org>
TypeScript
bsd-3-clause
ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend
--- +++ @@ -7,7 +7,7 @@ import {getBrowserAndPages} from '../../shared/helper.js'; import {navigateToSiteWithAnimation, waitForAnimationContent, waitForAnimationsPanelToLoad} from '../helpers/animations-helpers.js'; -describe('The Animations Panel', async () => { +describe.skip('[crbug.com/1082735] The Animations Panel', async () => { it('Listens for animation in webpage', async () => { const {target} = getBrowserAndPages(); await waitForAnimationsPanelToLoad();
6100fc175410ba512d81e05c3b9993148bf94b1f
src/behaviors/getSourceContentRelativePaths.ts
src/behaviors/getSourceContentRelativePaths.ts
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. import glob = require("glob"); import {Observable} from "rxjs"; import {Environment} from "../Environment"; export function getSourceContentRelativePaths(env: Environment): Observable<string> { let results = glob.sync("**/*", { cwd: env.resolvePath("content"), ignore: [ "**/_*", // Exclude files starting with '_'. "**/_*/**", // Exclude entire directories starting with '_'. "**/*.meta" // Exclude all meta files ], nodir: true }); return Observable.fromArray(results); }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. import glob = require("glob"); import {Observable} from "rxjs"; import {Environment} from "../Environment"; export function getSourceContentRelativePaths(env: Environment): Observable<string> { let results = glob.sync("**/*", { cwd: env.resolvePath("content"), ignore: [ "**/_*", // Exclude files starting with '_'. "**/_*/**", // Exclude entire directories starting with '_'. "**/*.meta" // Exclude all meta files ], nodir: true }); return Observable.from<string>(results); }
Update to workaround function removal in beta 4 of 'rxjs'.
Update to workaround function removal in beta 4 of 'rxjs'.
TypeScript
mit
webreed/webreed-core,webreed/webreed-core
--- +++ @@ -19,5 +19,5 @@ nodir: true }); - return Observable.fromArray(results); + return Observable.from<string>(results); }
0ddbd18710a9228ba3a87a3525166c7bd62a948b
lib/util/class_creator.ts
lib/util/class_creator.ts
var _ = require("lodash"); var CreateClass = function(initFunction, memberMap) { _.forOwn(memberMap, function(value, key) { initFunction.prototype[key] = value; }); return initFunction; } var CreateSubClass = function(baseKlass, initFunction, memberMap) { initFunction.prototype = Object.create(baseKlass.prototype); initFunction.prototype.constructor = initFunction; _.forOwn(memberMap, function(value, key) { initFunction.prototype[key] = value; }); return initFunction; } module.exports = { CreateClass: CreateClass, CreateSubClass: CreateSubClass }
var CreateClass = function(initFunction, memberMap) { for (mem in memberMap) { if (memberMap.hasOwnProperty(mem)) { initFunction.prototype[mem] = memberMap[mem]; } } return initFunction; } var CreateSubClass = function(baseKlass, initFunction, memberMap) { initFunction.prototype = Object.create(baseKlass.prototype); initFunction.prototype.constructor = initFunction; for (mem in memberMap) { if (memberMap.hasOwnProperty(mem)) { initFunction.prototype[mem] = memberMap[mem]; } } return initFunction; } module.exports = { CreateClass: CreateClass, CreateSubClass: CreateSubClass }
Revert "Converted memberMap traversal to use lodash"
Revert "Converted memberMap traversal to use lodash" This reverts commit 0335b3960c8e6b9436973d0e8163d549178a179c.
TypeScript
mit
severn-everett/node_university
--- +++ @@ -1,18 +1,20 @@ -var _ = require("lodash"); - var CreateClass = function(initFunction, memberMap) { - _.forOwn(memberMap, function(value, key) { - initFunction.prototype[key] = value; - }); + for (mem in memberMap) { + if (memberMap.hasOwnProperty(mem)) { + initFunction.prototype[mem] = memberMap[mem]; + } + } return initFunction; } var CreateSubClass = function(baseKlass, initFunction, memberMap) { initFunction.prototype = Object.create(baseKlass.prototype); initFunction.prototype.constructor = initFunction; - _.forOwn(memberMap, function(value, key) { - initFunction.prototype[key] = value; - }); + for (mem in memberMap) { + if (memberMap.hasOwnProperty(mem)) { + initFunction.prototype[mem] = memberMap[mem]; + } + } return initFunction; }
c1a8f5411121ef21039c4fbede7e624b06a560f0
src/xrm-mock-generator/xrm-mock-generator.ts
src/xrm-mock-generator/xrm-mock-generator.ts
import * as XrmMock from "../xrm-mock/index"; import Attribute from "./attribute"; import Context from "./context"; import Control from "./control"; import Form from "./form"; import Ui from "./ui"; import WebApi from "./webapi"; declare var global: any; export class XrmMockGenerator { public static Attribute: Attribute = new Attribute(); public static Context: Context = new Context(); public static Control: Control = new Control(); public static Form: Form = new Form(); public static Ui: Ui = new Ui(); public static WebApi: WebApi = new WebApi(); public static initialise(entityName: string): XrmMock.XrmStaticMock { const context = Context.createContext(); const formContext = new XrmMock.FormContextMock( new XrmMock.DataMock( new XrmMock.EntityMock( "{00000000-0000-0000-0000-000000000000}", entityName, new XrmMock.ItemCollectionMock([]))), Ui.createUi(), ); const xrm = new XrmMock.XrmStaticMock({ page: new XrmMock.PageMock( context, formContext, ), webApi: WebApi.createApi(context.client), }); if (typeof global === "undefined") { window.Xrm = xrm; } else { global.Xrm = xrm; } return xrm; } }
import * as XrmMock from "../xrm-mock/index"; import Attribute from "./attribute"; import Context from "./context"; import Control from "./control"; import Form from "./form"; import Ui from "./ui"; import WebApi from "./webapi"; declare var global: any; export class XrmMockGenerator { public static Attribute: Attribute = new Attribute(); public static Context: Context = new Context(); public static Control: Control = new Control(); public static Form: Form = new Form(); public static Ui: Ui = new Ui(); public static WebApi: WebApi = new WebApi(); public static initialise(entity: IEntity = this.defaultEntity): XrmMock.XrmStaticMock { const context = Context.createContext(); const formContext = new XrmMock.FormContextMock( new XrmMock.DataMock( new XrmMock.EntityMock( entity.id, entity.entityName, new XrmMock.ItemCollectionMock([]))), Ui.createUi(), ); const xrm = new XrmMock.XrmStaticMock({ page: new XrmMock.PageMock( context, formContext, ), webApi: WebApi.createApi(context.client), }); if (typeof global === "undefined") { window.Xrm = xrm; } else { global.Xrm = xrm; } return xrm; } private static defaultEntity: IEntity = { entityName: "contact", id: "{deadbeef-dead-beef-dead-beefdeadbeaf}", }; } export interface IEntity { id?: string; entityName?: string; }
Add interface for optional parameter for initialize method
Add interface for optional parameter for initialize method
TypeScript
mit
camelCaseDave/xrm-mock,camelCaseDave/xrm-mock
--- +++ @@ -16,13 +16,13 @@ public static Ui: Ui = new Ui(); public static WebApi: WebApi = new WebApi(); - public static initialise(entityName: string): XrmMock.XrmStaticMock { + public static initialise(entity: IEntity = this.defaultEntity): XrmMock.XrmStaticMock { const context = Context.createContext(); const formContext = new XrmMock.FormContextMock( new XrmMock.DataMock( new XrmMock.EntityMock( - "{00000000-0000-0000-0000-000000000000}", - entityName, + entity.id, + entity.entityName, new XrmMock.ItemCollectionMock([]))), Ui.createUi(), ); @@ -42,4 +42,14 @@ } return xrm; } + + private static defaultEntity: IEntity = { + entityName: "contact", + id: "{deadbeef-dead-beef-dead-beefdeadbeaf}", + }; } + +export interface IEntity { + id?: string; + entityName?: string; +}
6b27b37569645bcdf5ff2346ca92bea103ba6a8d
src/app/shared/services/data.service.ts
src/app/shared/services/data.service.ts
import { Injectable } from 'angular2/core'; import { Http, Response } from 'angular2/http'; //Grab everything with import 'rxjs/Rx'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class DataService { baseUrl: string = ''; constructor(private http: Http) { } getCustomers() { return this.http.get(this.baseUrl + 'customers.json') .map((res: Response) => res.json()) .catch(this.handleError); } getOrders(){ return this.http.get(this.baseUrl + 'orders.json') .map((res: Response) => res.json()) .catch(this.handleError); } handleError(error: any) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }
import { Injectable } from 'angular2/core'; import { Http, Response } from 'angular2/http'; //Grab everything with import 'rxjs/Rx'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class DataService { baseUrl: string = ''; constructor(private _http: Http) { } getCustomers() { return this._http.get(this.baseUrl + 'customers.json') .map((res: Response) => res.json()) .catch(this.handleError); } getOrders(){ return this._http.get(this.baseUrl + 'orders.json') .map((res: Response) => res.json()) .catch(this.handleError); } handleError(error: any) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } }
Change private http member to _http
Change private http member to _http
TypeScript
mit
m-williams/Angular2-JumpStart,m-williams/Angular2-JumpStart,DanWahlin/Angular-JumpStart,born2net/ng2-minimal,DanWahlin/Angular2-JumpStart,DanWahlin/Angular2-JumpStart,m-williams/Angular2-JumpStart,DanWahlin/Angular2-JumpStart,DanWahlin/Angular-JumpStart,born2net/ng2-minimal,DanWahlin/Angular-JumpStart,born2net/ng2-minimal
--- +++ @@ -12,16 +12,16 @@ baseUrl: string = ''; - constructor(private http: Http) { } + constructor(private _http: Http) { } getCustomers() { - return this.http.get(this.baseUrl + 'customers.json') + return this._http.get(this.baseUrl + 'customers.json') .map((res: Response) => res.json()) .catch(this.handleError); } getOrders(){ - return this.http.get(this.baseUrl + 'orders.json') + return this._http.get(this.baseUrl + 'orders.json') .map((res: Response) => res.json()) .catch(this.handleError); }
d7ddf2018c7f1e1f43f1d65ea89368a6a852aa2f
types/filenamify/filenamify-tests.ts
types/filenamify/filenamify-tests.ts
import * as filenamify from 'filenamify'; filenamify('<foo/bar>'); // => 'foo!bar' filenamify('foo:"bar"', {replacement: '🐴'}); // => 'foo🐴bar' filenamify.path('/some/!path'); // => '/some/path'
import filenamify = require('filenamify'); filenamify('<foo/bar>'); // => 'foo!bar' filenamify('foo:"bar"', {replacement: '🐴'}); // => 'foo🐴bar' filenamify.path('/some/!path'); // => '/some/path'
Update import expression in filenamify-test.ts
Update import expression in filenamify-test.ts See here for the futher information : https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19550#discussion_r137169189
TypeScript
mit
georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,zuzusik/DefinitelyTyped,AgentME/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,one-pieces/DefinitelyTyped,jimthedev/DefinitelyTyped,magny/DefinitelyTyped,aciccarello/DefinitelyTyped,chrootsu/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,magny/DefinitelyTyped,chrootsu/DefinitelyTyped,benliddicott/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,benishouga/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,benishouga/DefinitelyTyped,nycdotnet/DefinitelyTyped,benishouga/DefinitelyTyped,arusakov/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,alexdresko/DefinitelyTyped,borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,rolandzwaga/DefinitelyTyped,nycdotnet/DefinitelyTyped,jimthedev/DefinitelyTyped,arusakov/DefinitelyTyped,jimthedev/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped
--- +++ @@ -1,4 +1,4 @@ -import * as filenamify from 'filenamify'; +import filenamify = require('filenamify'); filenamify('<foo/bar>'); // => 'foo!bar'
a9ce6c5f7e7e916e6197927b8bb0b881c2a610e8
src/v2/components/ChannelFollowers/queries/channelFollowers.ts
src/v2/components/ChannelFollowers/queries/channelFollowers.ts
import gql from 'graphql-tag' import identifiableCellFragment from 'v2/components/Cell/components/Identifiable/fragments/identifiableCell' export const channelFollowersQuery = gql` query ChannelFollowers($id: ID!, $page: Int, $per: Int) { channel(id: $id) { followers(page: $page, per: $per) { __typename ...IdentifiableCell } } } ${identifiableCellFragment} `
import gql from 'graphql-tag' import identifiableCellFragment from 'v2/components/Cell/components/Identifiable/fragments/identifiableCell' export const channelFollowersQuery = gql` query ChannelFollowers($id: ID!, $page: Int, $per: Int) { channel(id: $id) { id __typename followers(page: $page, per: $per) { __typename ...IdentifiableCell } } } ${identifiableCellFragment} `
Add id and typename to channel followers
Add id and typename to channel followers
TypeScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -5,6 +5,8 @@ export const channelFollowersQuery = gql` query ChannelFollowers($id: ID!, $page: Int, $per: Int) { channel(id: $id) { + id + __typename followers(page: $page, per: $per) { __typename ...IdentifiableCell
ce79e2875ddc6a21adcab7f1df3e132d7c56be0e
app/scripts/history/view.tsx
app/scripts/history/view.tsx
import * as React from 'react'; import { Table, TableBody, TableRow, TableRowColumn } from 'material-ui'; import { formatDateFull } from '../dates'; import { Reading } from '../model'; export interface ViewProps { data: Reading; } export default (props: ViewProps) => ( <Table> <TableBody displayRowCheckbox={ false }> <TableRow> <TableRowColumn>Date recorded</TableRowColumn> <TableRowColumn>{ formatDateFull(props.data.recordDate) }</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Electricity (low)</TableRowColumn> <TableRowColumn>{ props.data.electricityLow } kWh</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Electricity (normal)</TableRowColumn> <TableRowColumn>{ props.data.electricityNormal } kWh</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Gas</TableRowColumn> <TableRowColumn>{ props.data.gas } m<sup>3</sup></TableRowColumn> </TableRow> </TableBody> </Table> );
import * as React from 'react'; import { Table, TableBody, TableRow, TableRowColumn } from 'material-ui'; import { formatDateFull } from '../dates'; import { Reading } from '../model'; export interface ViewProps { data: Reading; } export default (props: ViewProps) => ( <Table selectable={ false }> <TableBody displayRowCheckbox={ false }> <TableRow> <TableRowColumn>Date recorded</TableRowColumn> <TableRowColumn>{ formatDateFull(props.data.recordDate) }</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Electricity (low)</TableRowColumn> <TableRowColumn>{ props.data.electricityLow } kWh</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Electricity (normal)</TableRowColumn> <TableRowColumn>{ props.data.electricityNormal } kWh</TableRowColumn> </TableRow> <TableRow> <TableRowColumn>Gas</TableRowColumn> <TableRowColumn>{ props.data.gas } m<sup>3</sup></TableRowColumn> </TableRow> </TableBody> </Table> );
Allow selecting text inside tables
Allow selecting text inside tables
TypeScript
mit
mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web
--- +++ @@ -10,7 +10,7 @@ } export default (props: ViewProps) => ( - <Table> + <Table selectable={ false }> <TableBody displayRowCheckbox={ false }> <TableRow> <TableRowColumn>Date recorded</TableRowColumn>
5e77c43f29c3d90055297610099028e73ede11fc
src/components/controls/intent.ts
src/components/controls/intent.ts
import xs from 'xstream'; export interface Actions { currencyChangeAction$: xs<string>; } export default function intent(domSource): Actions { const currencyChangeAction$: xs<string> = domSource .select('.currency-select') .events('change') .map(inputEv => (inputEv.target as HTMLInputElement).value); return { currencyChangeAction$ }; }
import xs from 'xstream'; import { styles } from './styles'; export interface Actions { currencyChangeAction$: xs<string>; } export default function intent(domSource): Actions { const currencyChangeAction$: xs<string> = domSource .select(`.${styles.currencySelect}`) .events('change') .map(inputEv => (inputEv.target as HTMLInputElement).value); return { currencyChangeAction$ }; }
Fix the broken currency-select selector
Fix the broken currency-select selector
TypeScript
mit
olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator
--- +++ @@ -1,4 +1,5 @@ import xs from 'xstream'; +import { styles } from './styles'; export interface Actions { currencyChangeAction$: xs<string>; @@ -6,7 +7,7 @@ export default function intent(domSource): Actions { const currencyChangeAction$: xs<string> = domSource - .select('.currency-select') + .select(`.${styles.currencySelect}`) .events('change') .map(inputEv => (inputEv.target as HTMLInputElement).value);
72c6db1c08777bafe028b78e9a00cd5370fc6486
test/browser/MongoUtil.ts
test/browser/MongoUtil.ts
import mongoose from "mongoose"; import {isProd} from "../server/util" import { IUser, User, LoginType } from "../server/models/User" import bcrypt from "bcryptjs" export async function clearDatabase() { if (isProd()) { throw new Error("How about you stop calling clearDatabase in production!") } console.log("Clearing database") await mongoose.connection.dropDatabase() for (const modelName of mongoose.modelNames()) { const model = mongoose.model(modelName) await model.init() } } export async function initTestData() { if (isProd()) { throw new Error("How about you stop calling initTestData in production!") } const users: IUser[] = [ { name: "John Smith", email: "john.smith@example.com", logins: [{ loginId: "john.smith@example.com", type: LoginType.Local, password: await bcrypt.hash("johnsmith123", 10), }], }, { name: "John Doe", email: "john.doe@example.com", logins: [{ loginId: "john.doe@example.com", type: LoginType.Local, password: await bcrypt.hash("johndoe123", 10), }], }, ] await User.insertMany(users) }
import mongoose from "mongoose"; import {isProd} from "../../src/server/util" import { IUser, User, LoginType } from "../../src/server/models/User" import bcrypt from "bcryptjs" export async function clearDatabase() { if (isProd()) { throw new Error("How about you stop calling clearDatabase in production!") } console.log("Clearing database") await mongoose.connection.dropDatabase() for (const modelName of mongoose.modelNames()) { const model = mongoose.model(modelName) await model.init() } } export async function initTestData() { if (isProd()) { throw new Error("How about you stop calling initTestData in production!") } const users: IUser[] = [ { name: "John Smith", email: "john.smith@example.com", logins: [{ loginId: "john.smith@example.com", type: LoginType.Local, password: await bcrypt.hash("johnsmith123", 10), }], }, { name: "John Doe", email: "john.doe@example.com", logins: [{ loginId: "john.doe@example.com", type: LoginType.Local, password: await bcrypt.hash("johndoe123", 10), }], }, ] await User.insertMany(users) }
Fix build and give a suspicious look at vscode not giving warning for import paths.
Fix build and give a suspicious look at vscode not giving warning for import paths.
TypeScript
mit
Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki
--- +++ @@ -1,6 +1,6 @@ import mongoose from "mongoose"; -import {isProd} from "../server/util" -import { IUser, User, LoginType } from "../server/models/User" +import {isProd} from "../../src/server/util" +import { IUser, User, LoginType } from "../../src/server/models/User" import bcrypt from "bcryptjs" export async function clearDatabase() {