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
8501fd0b632f68ed23bb60bf893b3ef3393a1673
src/app/app.component.ts
src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: "tpl/app.component.tpl.html" }) export class AppComponent { }
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: "/app/app.component.tpl.html" }) export class AppComponent { }
Use full path of templateUrl
Use full path of templateUrl
TypeScript
mit
ngako/angular2-poc,ngako/angular2-poc,ngako/angular2-poc
--- +++ @@ -2,6 +2,6 @@ @Component({ selector: 'my-app', - templateUrl: "tpl/app.component.tpl.html" + templateUrl: "/app/app.component.tpl.html" }) export class AppComponent { }
0e4dce9c7f07e6d7f02ebad75a81e864e5da2ed9
src/test/java/com/google/javascript/clutz/async_await_with_platform.d.ts
src/test/java/com/google/javascript/clutz/async_await_with_platform.d.ts
declare namespace ಠ_ಠ.clutz { class module$exports$asyncawait { private noStructuralTyping_: any; bar ( ) : any ; foo ( ) : any ; } } declare module 'goog:asyncawait' { import asyncawait = ಠ_ಠ.clutz.module$exports$asyncawait; export default asyncawait; }
declare namespace ಠ_ಠ.clutz { class module$exports$asyncawait { private noStructuralTyping_: any; bar ( ) : Promise < undefined > ; foo ( ) : Promise < undefined > ; } } declare module 'goog:asyncawait' { import asyncawait = ಠ_ಠ.clutz.module$exports$asyncawait; export default asyncawait; }
Fix test of async_await_with_platform for latest Closure Compiler
Fix test of async_await_with_platform for latest Closure Compiler
TypeScript
mit
angular/clutz,angular/clutz,angular/clutz
--- +++ @@ -1,8 +1,8 @@ declare namespace ಠ_ಠ.clutz { class module$exports$asyncawait { private noStructuralTyping_: any; - bar ( ) : any ; - foo ( ) : any ; + bar ( ) : Promise < undefined > ; + foo ( ) : Promise < undefined > ; } } declare module 'goog:asyncawait' {
d0b2386af2ac4f342a8aab1f59e4eb2110e404ff
client/Library/Manager/LibraryManagerRow.tsx
client/Library/Manager/LibraryManagerRow.tsx
import * as React from "react"; import { Listable } from "../../../common/Listable"; import { useSubscription } from "../../Combatant/linkComponentToObservables"; import { Listing } from "../Listing"; import { SelectionContext, Selection } from "./SelectionContext"; export function LibraryManagerRow(props: { listing: Listing<any>; defaultListing: Listable; setEditorTarget: (item: Listable) => void; }) { const listingMeta = useSubscription(props.listing.Meta); const selection = React.useContext<Selection<Listing<any>>>(SelectionContext); const isSelected = selection.selected.includes(props.listing); return ( <div style={{ backgroundColor: isSelected ? "red" : undefined, userSelect: "none", display: "flex", flexFlow: "row", justifyContent: "space-between" }} > <span onClick={mouseEvent => { if (mouseEvent.ctrlKey || mouseEvent.metaKey) { selection.addSelected(props.listing); } else { selection.setSelected(props.listing); } }} > {listingMeta.Name} </span> <span onClick={async () => { const item = await props.listing.GetWithTemplate( props.defaultListing ); props.setEditorTarget(item); }} > edit </span> </div> ); }
import * as React from "react"; import { Listable } from "../../../common/Listable"; import { useSubscription } from "../../Combatant/linkComponentToObservables"; import { Listing } from "../Listing"; import { SelectionContext, Selection } from "./SelectionContext"; export function LibraryManagerRow(props: { listing: Listing<any>; defaultListing: Listable; setEditorTarget: (item: Listable) => void; }) { const listingMeta = useSubscription(props.listing.Meta); const selection = React.useContext<Selection<Listing<any>>>(SelectionContext); const isSelected = selection.selected.includes(props.listing); return ( <div style={{ backgroundColor: isSelected ? "red" : undefined, userSelect: "none", display: "flex", flexFlow: "row", justifyContent: "space-between" }} onClick={mouseEvent => { if (mouseEvent.ctrlKey || mouseEvent.metaKey) { selection.addSelected(props.listing); } else { selection.setSelected(props.listing); } }} > <span>{listingMeta.Name}</span> <span onClick={async e => { e.stopPropagation(); const item = await props.listing.GetWithTemplate( props.defaultListing ); props.setEditorTarget(item); }} > edit </span> </div> ); }
Move click handler to whole row
Move click handler to whole row
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -21,20 +21,18 @@ flexFlow: "row", justifyContent: "space-between" }} + onClick={mouseEvent => { + if (mouseEvent.ctrlKey || mouseEvent.metaKey) { + selection.addSelected(props.listing); + } else { + selection.setSelected(props.listing); + } + }} > + <span>{listingMeta.Name}</span> <span - onClick={mouseEvent => { - if (mouseEvent.ctrlKey || mouseEvent.metaKey) { - selection.addSelected(props.listing); - } else { - selection.setSelected(props.listing); - } - }} - > - {listingMeta.Name} - </span> - <span - onClick={async () => { + onClick={async e => { + e.stopPropagation(); const item = await props.listing.GetWithTemplate( props.defaultListing );
20d953132867d7856c24b417bcddd71a624df3e3
packages/shared/lib/keys/setupAddressKeys.ts
packages/shared/lib/keys/setupAddressKeys.ts
import { getAllAddresses, setupAddress as setupAddressRoute } from '../api/addresses'; import { queryAvailableDomains } from '../api/domains'; import { Address as tsAddress, Api } from '../interfaces'; import { handleSetupKeys } from './setupKeys'; interface SetupAddressArgs { api: Api; username: string; domain: string; } export const handleSetupAddress = async ({ api, username, domain }: SetupAddressArgs) => { if (!domain) { throw new Error('Missing domain'); } const { Address } = await api<{ Address: tsAddress }>( setupAddressRoute({ Domain: domain, DisplayName: username, Signature: '', }) ); return [Address]; }; interface SetupAddressKeysArgs { password: string; api: Api; username: string; hasAddressKeyMigrationGeneration: boolean; } export const handleSetupAddressKeys = async ({ username, password, api, hasAddressKeyMigrationGeneration, }: SetupAddressKeysArgs) => { const [availableAddresses, availableDomains] = await Promise.all([ getAllAddresses(api), api<{ Domains: string[] }>(queryAvailableDomains()).then(({ Domains }) => Domains), ]); const addressesToUse = availableAddresses?.length > 0 ? availableAddresses : await handleSetupAddress({ api, domain: availableDomains[0], username }); return handleSetupKeys({ api, addresses: addressesToUse, password, hasAddressKeyMigrationGeneration }); };
import { getAllAddresses, setupAddress as setupAddressRoute } from '../api/addresses'; import { queryAvailableDomains } from '../api/domains'; import { Address as tsAddress, Api } from '../interfaces'; import { handleSetupKeys } from './setupKeys'; interface SetupAddressArgs { api: Api; username: string; domain: string; } export const handleSetupAddress = async ({ api, username, domain }: SetupAddressArgs) => { if (!domain) { throw new Error('Missing domain'); } const { Address } = await api<{ Address: tsAddress }>( setupAddressRoute({ Domain: domain, DisplayName: username, Signature: '', }) ); return [Address]; }; interface SetupAddressKeysArgs { password: string; api: Api; username: string; hasAddressKeyMigrationGeneration: boolean; } export const handleSetupAddressKeys = async ({ username, password, api, hasAddressKeyMigrationGeneration, }: SetupAddressKeysArgs) => { const [availableAddresses, availableDomains] = await Promise.all([ getAllAddresses(api), api<{ Domains: string[] }>(queryAvailableDomains('signup')).then(({ Domains }) => Domains), ]); const addressesToUse = availableAddresses?.length > 0 ? availableAddresses : await handleSetupAddress({ api, domain: availableDomains[0], username }); return handleSetupKeys({ api, addresses: addressesToUse, password, hasAddressKeyMigrationGeneration }); };
Add signup query parameter when setting up address
Add signup query parameter when setting up address This is to get the right order of the domains to be the same as they are during signup
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -38,7 +38,7 @@ }: SetupAddressKeysArgs) => { const [availableAddresses, availableDomains] = await Promise.all([ getAllAddresses(api), - api<{ Domains: string[] }>(queryAvailableDomains()).then(({ Domains }) => Domains), + api<{ Domains: string[] }>(queryAvailableDomains('signup')).then(({ Domains }) => Domains), ]); const addressesToUse =
2b16f98175489356e8c5fb0e9e7944c753513d89
src/toolchain/linter.ts
src/toolchain/linter.ts
import { linter } from 'eslint' /// Header which might be appended on lint errors. export const LINT_ERROR_HEADER = '[!] These are valid in JavaScript but not in Source' /// Rule indicator for missing semicolon export const MISSING_SEMICOLON_ID = 'semi' export const MISSING_SEMICOLON_MESSAGE = 'Missing Semicolon' /** * Subset of eslint lint result */ export interface ILintResult { ruleId?: string message: string line: number endLine: number column: number endColumn: number } /** * Lint the source code * @param {string} code The source code * @return {ILintResult[]} List of eslint errors/warnings */ export function lint(code: string): ILintResult[] { return linter.verify(code, { rules: { semi: 'warn' } }) }
import { linter } from 'eslint' /// Header which might be appended on lint errors. export const LINT_ERROR_HEADER = '[!] Syntax Error/Warning' /// Rule indicator for missing semicolon export const MISSING_SEMICOLON_ID = 'semi' export const MISSING_SEMICOLON_MESSAGE = 'Error: Missing Semicolon' /** * Subset of eslint lint result */ export interface ILintResult { ruleId?: string message: string line: number endLine: number column: number endColumn: number } /** * Lint the source code * @param {string} code The source code * @return {ILintResult[]} List of eslint errors/warnings */ export function lint(code: string): ILintResult[] { return linter.verify(code, { rules: { semi: 'error' } }) }
Change semicolon message and severity
feat: Change semicolon message and severity
TypeScript
mit
evansb/source-toolchain,evansb/source-toolchain
--- +++ @@ -2,11 +2,11 @@ /// Header which might be appended on lint errors. export const LINT_ERROR_HEADER - = '[!] These are valid in JavaScript but not in Source' + = '[!] Syntax Error/Warning' /// Rule indicator for missing semicolon export const MISSING_SEMICOLON_ID = 'semi' -export const MISSING_SEMICOLON_MESSAGE = 'Missing Semicolon' +export const MISSING_SEMICOLON_MESSAGE = 'Error: Missing Semicolon' /** * Subset of eslint lint result @@ -28,7 +28,7 @@ export function lint(code: string): ILintResult[] { return linter.verify(code, { rules: { - semi: 'warn' + semi: 'error' } }) }
8d1a88177812c65da1347798e33fb8dcd9f69d1e
src/env.ts
src/env.ts
import envPaths from 'env-paths'; import _debug from 'debug'; import { join } from './utils/path'; import getStaging from './utils/get-staging'; import { reporter } from './reporter'; import { Env } from './types'; const paths = envPaths('vba-blocks', { suffix: '' }); const cache = paths.cache; const root = join(__dirname, '../'); const env: Env = { isWindows: process.platform === 'win32', cwd: process.cwd(), values: process.env, ...paths, // data, config, cache, log, temp addins: join(root, 'addins/build'), scripts: join(root, 'run-scripts'), bin: join(root, 'bin'), registry: join(cache, 'registry'), packages: join(cache, 'packages'), sources: join(cache, 'sources'), staging: getStaging(cache), reporter, debug: id => _debug(id), silent: false }; export default env;
import envPaths from 'env-paths'; import _debug from 'debug'; import { join } from './utils/path'; import getStaging from './utils/get-staging'; import { reporter } from './reporter'; import { Env } from './types'; const paths = envPaths('vba-blocks', { suffix: '' }); const cache = paths.cache; const root = join(__dirname, '../'); const env: Env = { isWindows: process.platform === 'win32', cwd: process.cwd(), values: process.env, ...paths, // data, config, cache, log, temp addins: join(root, 'addins/build'), scripts: join(root, 'run-scripts'), bin: join(root, 'bin'), registry: join(cache, 'registry'), packages: join(cache, 'packages'), sources: join(cache, 'sources'), staging: getStaging(paths.temp), reporter, debug: id => _debug(id), silent: false }; export default env;
Move staging to temp directory
Move staging to temp directory
TypeScript
mit
vba-blocks/vba-blocks,vba-blocks/vba-blocks,vba-blocks/vba-blocks
--- +++ @@ -23,7 +23,7 @@ registry: join(cache, 'registry'), packages: join(cache, 'packages'), sources: join(cache, 'sources'), - staging: getStaging(cache), + staging: getStaging(paths.temp), reporter, debug: id => _debug(id),
dd2031cef5ccc6f06035d59b409c1cee127b705e
src/app.ts
src/app.ts
import xs, { Stream } from 'xstream'; import { VNode, div, span, img, a, h1, button } from '@cycle/dom'; import { Sources, Sinks } from './interfaces'; import Header from './components/header'; import Price from './components/price'; import PriceInputs from './components/priceInputs'; import Footer from './components/footer'; export function App(sources : Sources) : Sinks { const headerVDom$ : Stream<VNode> = Header(sources); const priceInputsSinks : Sinks = PriceInputs(sources); const priceInputsVDom$ : Stream<VNode> = priceInputsSinks.DOM; const priceInputs$ : xs<number> = priceInputsSinks.PRICE; // @TODO: is this ok? sources.PRICE = priceInputs$; const priceVDom$ : Stream<VNode> = Price(sources); const footerVDom$ : Stream<VNode> = Footer(sources); const vdom$ : Stream<VNode> = xs .combine(headerVDom$, priceVDom$, priceInputsVDom$, footerVDom$) .map(([headerVDom, priceVDom, priceInputVDom, footerVDom]) => div('.App-flex-container', [ headerVDom, priceVDom, priceInputVDom, footerVDom, ]) ); const sinks : Sinks = { DOM : vdom$, PRICE: priceInputs$ }; return sinks; }
import xs, { Stream } from 'xstream'; import { VNode, div, span, img, a, h1, button } from '@cycle/dom'; import { Sources, Sinks } from './interfaces'; import Header from './components/header'; import Price from './components/price'; import PriceInputs from './components/priceInputs'; import Footer from './components/footer'; export function App(sources : Sources) : Sinks { const headerVDom$ : Stream<VNode> = Header(sources); const priceInputsProxy$ : xs<{}> = xs.create(); const priceInputsSinks : Sinks = PriceInputs(sources); const priceInputsVDom$ : Stream<VNode> = priceInputsSinks.DOM; const priceInputs$ : xs<number> = priceInputsSinks.PRICE; const priceVDom$ : Stream<VNode> = Price({...sources, PRICE: priceInputsProxy$ as xs<number>}); priceInputsProxy$.imitate(priceInputs$); const footerVDom$ : Stream<VNode> = Footer(sources); const vdom$ : Stream<VNode> = xs .combine(headerVDom$, priceVDom$, priceInputsVDom$, footerVDom$) .map((VDomArray) => div('.App-flex-container', VDomArray) ); const sinks : Sinks = { DOM : vdom$, PRICE: priceInputs$ }; return sinks; }
Use imitate() to solve the circular dependency issue
Use imitate() to solve the circular dependency issue Also do not destructure the array because it's not necessary
TypeScript
mit
olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator
--- +++ @@ -10,25 +10,20 @@ export function App(sources : Sources) : Sinks { const headerVDom$ : Stream<VNode> = Header(sources); + const priceInputsProxy$ : xs<{}> = xs.create(); const priceInputsSinks : Sinks = PriceInputs(sources); const priceInputsVDom$ : Stream<VNode> = priceInputsSinks.DOM; const priceInputs$ : xs<number> = priceInputsSinks.PRICE; - // @TODO: is this ok? - sources.PRICE = priceInputs$; + const priceVDom$ : Stream<VNode> = Price({...sources, PRICE: priceInputsProxy$ as xs<number>}); + priceInputsProxy$.imitate(priceInputs$); - const priceVDom$ : Stream<VNode> = Price(sources); const footerVDom$ : Stream<VNode> = Footer(sources); const vdom$ : Stream<VNode> = xs .combine(headerVDom$, priceVDom$, priceInputsVDom$, footerVDom$) - .map(([headerVDom, priceVDom, priceInputVDom, footerVDom]) => - div('.App-flex-container', [ - headerVDom, - priceVDom, - priceInputVDom, - footerVDom, - ]) + .map((VDomArray) => + div('.App-flex-container', VDomArray) ); const sinks : Sinks = {
464de5919623b540ec86a8a1007387976db04541
src/autosize.directive.ts
src/autosize.directive.ts
import { ElementRef, HostListener, Directive} from 'angular2/core'; @Directive({ selector: 'textarea[autosize]' }) export class Autosize { @HostListener('input',['$event.target']) onInput(textArea) { this.adjust(); } constructor(public element: ElementRef){ } ngOnInit(){ this.adjust(); } adjust(){ this.element.nativeElement.style.height = 'auto'; this.element.nativeElement.style.height = this.element.nativeElement.scrollHeight + "px"; } }
import { ElementRef, HostListener, Directive} from 'angular2/core'; @Directive({ selector: 'textarea[autosize]' }) export class Autosize { @HostListener('input',['$event.target']) onInput(textArea) { this.adjust(); } constructor(public element: ElementRef){ } ngOnInit(){ this.adjust(); } adjust(){ this.element.nativeElement.style.overflow = 'hidden'; this.element.nativeElement.style.height = 'auto'; this.element.nativeElement.style.height = this.element.nativeElement.scrollHeight + "px"; } }
Add overflow hidden to create cleaner height
Add overflow hidden to create cleaner height
TypeScript
mit
stevepapa/angular2-autosize
--- +++ @@ -15,7 +15,8 @@ this.adjust(); } adjust(){ - this.element.nativeElement.style.height = 'auto'; + this.element.nativeElement.style.overflow = 'hidden'; + this.element.nativeElement.style.height = 'auto'; this.element.nativeElement.style.height = this.element.nativeElement.scrollHeight + "px"; } }
70c77a11f8d8fafb81668ecbbe108d6c83b98229
src/app/shared/storage.service.ts
src/app/shared/storage.service.ts
import { Injectable } from '@angular/core'; import { Subject, BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class StorageService { storageKey: string = 'marvel-readin-stats'; currentStorage: Subject<any> = new BehaviorSubject<any>(null); constructor() { } initStorage(): any { this.updateStorage({}); } getStorage(): any { let storage = JSON.parse(localStorage.getItem(this.storageKey)); if (!storage) { this.initStorage(); } else { this.currentStorage.next(storage); } } updateStorage(newStorage: any): void { localStorage.setItem( this.storageKey, JSON.stringify(newStorage) ); this.currentStorage.next(newStorage); } deleteStorage(): void { localStorage.removeItem(this.storageKey); this.currentStorage.next(null); } }
import { Injectable } from '@angular/core'; import { Subject, BehaviorSubject, Observable } from 'rxjs'; @Injectable() export class StorageService { storageKey: string = 'marvel-reading-stats'; currentStorage: Subject<any> = new BehaviorSubject<any>(null); constructor() { } initStorage(): any { this.updateStorage({}); } getStorage(): any { let storage = JSON.parse(localStorage.getItem(this.storageKey)); if (!storage) { this.initStorage(); } else { this.currentStorage.next(storage); } } updateStorage(newStorage: any): void { localStorage.setItem( this.storageKey, JSON.stringify(newStorage) ); this.currentStorage.next(newStorage); } deleteStorage(): void { localStorage.removeItem(this.storageKey); this.currentStorage.next(null); } }
Fix typo in local storage key
Fix typo in local storage key
TypeScript
mit
SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend,SBats/marvel-reading-stats-frontend
--- +++ @@ -3,7 +3,7 @@ @Injectable() export class StorageService { - storageKey: string = 'marvel-readin-stats'; + storageKey: string = 'marvel-reading-stats'; currentStorage: Subject<any> = new BehaviorSubject<any>(null); constructor() {
c43c196c0ce4c4599510f686d29f9eb017d05090
src/Namespace.ts
src/Namespace.ts
export class Namespace { /** @param uri Unique identifier for the namespace, should be a valid URI. * @param defaultPrefix Default xmlns prefix for serializing to XML. */ constructor(public defaultPrefix: string, public uri: string, id?: number) { this.id = id || Namespace.idLast++; } addElement(name: string) { this.elementNameList.push(name); } addAttribute(name: string) { this.attributeNameList.push(name); } elementNameList: string[] = []; attributeNameList: string[] = []; id: number; static idLast = 0; static unknown = new Namespace('', ''); }
export class Namespace { /** @param uri Unique identifier for the namespace, should be a valid URI. * @param defaultPrefix Default xmlns prefix for serializing to XML. */ constructor(public defaultPrefix: string, public uri: string, id?: number) { this.id = id || Namespace.idLast++; } addElement(name: string) { this.elementNameList.push(name); } addAttribute(name: string) { this.attributeNameList.push(name); } addLocation(url: string) { this.schemaLocationList.push(url); } elementNameList: string[] = []; attributeNameList: string[] = []; schemaLocationList: string[] = []; id: number; static idLast = 0; static unknown = new Namespace('', ''); }
Allow storing schema locations with namespaces.
Allow storing schema locations with namespaces.
TypeScript
mit
charto/cxml,charto/cxml,charto/cxml
--- +++ @@ -8,9 +8,11 @@ addElement(name: string) { this.elementNameList.push(name); } addAttribute(name: string) { this.attributeNameList.push(name); } + addLocation(url: string) { this.schemaLocationList.push(url); } elementNameList: string[] = []; attributeNameList: string[] = []; + schemaLocationList: string[] = []; id: number;
24006c946b8a6634a4116422acf912a820c7f238
src/middlewares/logger.ts
src/middlewares/logger.ts
import { Store, Dispatch, Action } from "redux"; const crashReporter = (store: Store) => (next: Dispatch) => ( action: Action ) => { const { getState } = store; const beforeActionState = getState(); const result = next(action); const afterActionState = getState(); console.info( "action", action, "beforeState", beforeActionState, "afterState", afterActionState ); return result; }; export default crashReporter;
import { Store, Dispatch, Action } from "redux"; const logger = (store: Store) => (next: Dispatch) => (action: Action) => { const { getState } = store; const beforeActionState = getState(); const result = next(action); const afterActionState = getState(); console.info( "action", action, "beforeState", beforeActionState, "afterState", afterActionState ); return result; }; export default logger;
Change name to match middlware behavior
Change name to match middlware behavior
TypeScript
bsd-3-clause
wakatime/desktop,wakatime/wakatime-desktop,wakatime/wakatime-desktop,wakatime/desktop,wakatime/desktop
--- +++ @@ -1,8 +1,6 @@ import { Store, Dispatch, Action } from "redux"; -const crashReporter = (store: Store) => (next: Dispatch) => ( - action: Action -) => { +const logger = (store: Store) => (next: Dispatch) => (action: Action) => { const { getState } = store; const beforeActionState = getState(); const result = next(action); @@ -17,4 +15,4 @@ ); return result; }; -export default crashReporter; +export default logger;
1511585939a7433702201f646fb32730e18ce98a
src/reactors/search/index.ts
src/reactors/search/index.ts
import { Watcher } from "../watcher"; import rootLogger from "../../logger"; const logger = rootLogger.child({ name: "fetch-search" }); import { actions } from "../../actions"; export default function(watcher: Watcher) { watcher.on(actions.search, async (store, action) => { logger.error("TODO: re-implement search with buse"); }); }
import { Watcher } from "../watcher"; import { actions } from "../../actions"; import { call, messages } from "../../buse/index"; import { ISearchResults } from "../../types/index"; import { mergeGames, mergeUsers } from "./search-helpers"; export default function(watcher: Watcher) { watcher.on(actions.search, async (store, action) => { const profileId = store.getState().profile.credentials.me.id; const { query } = action.payload; if (query.length < 3) { return; } let results: ISearchResults = {}; let dispatch = () => { store.dispatch(actions.searchFetched({ query, results })); }; let promises = []; promises.push( call(messages.SearchGames, { profileId, query }, client => { // TODO: give params directly to request handlers client.onNotification(messages.SearchGamesYield, ({ params }) => { results = mergeGames(results, params.games); dispatch(); }); }) ); promises.push(messages.SearchUsers, { profileId, query }, client => { client.onNotification(messages.SearchUsers, ({ params }) => { results = mergeUsers(results, params.users); dispatch(); }); }); await Promise.all(promises); }); }
Reimplement search on top of buse
Reimplement search on top of buse
TypeScript
mit
itchio/itch,itchio/itch,leafo/itchio-app,itchio/itch,itchio/itchio-app,leafo/itchio-app,itchio/itch,leafo/itchio-app,itchio/itchio-app,itchio/itchio-app,itchio/itch,itchio/itch
--- +++ @@ -1,12 +1,41 @@ import { Watcher } from "../watcher"; -import rootLogger from "../../logger"; -const logger = rootLogger.child({ name: "fetch-search" }); - import { actions } from "../../actions"; +import { call, messages } from "../../buse/index"; +import { ISearchResults } from "../../types/index"; +import { mergeGames, mergeUsers } from "./search-helpers"; export default function(watcher: Watcher) { watcher.on(actions.search, async (store, action) => { - logger.error("TODO: re-implement search with buse"); + const profileId = store.getState().profile.credentials.me.id; + const { query } = action.payload; + if (query.length < 3) { + return; + } + + let results: ISearchResults = {}; + + let dispatch = () => { + store.dispatch(actions.searchFetched({ query, results })); + }; + + let promises = []; + promises.push( + call(messages.SearchGames, { profileId, query }, client => { + // TODO: give params directly to request handlers + client.onNotification(messages.SearchGamesYield, ({ params }) => { + results = mergeGames(results, params.games); + dispatch(); + }); + }) + ); + promises.push(messages.SearchUsers, { profileId, query }, client => { + client.onNotification(messages.SearchUsers, ({ params }) => { + results = mergeUsers(results, params.users); + dispatch(); + }); + }); + + await Promise.all(promises); }); }
5a4abcf993fac75b7add47aa4ad3e901cf00752e
db/migration/1551312762103-ChartsIsIndexable.ts
db/migration/1551312762103-ChartsIsIndexable.ts
import {MigrationInterface, QueryRunner} from "typeorm"; export class ChartsIsIndexable1551312762103 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { queryRunner.query("alter table charts ADD is_indexable BOOLEAN NOT NULL DEFAULT FALSE") } public async down(queryRunner: QueryRunner): Promise<any> { } }
import {MigrationInterface, QueryRunner} from "typeorm"; import _ = require('lodash') import { PUBLIC_TAG_PARENT_IDS } from "settings"; export class ChartsIsIndexable1551312762103 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { await queryRunner.query("alter table charts ADD is_indexable BOOLEAN NOT NULL DEFAULT FALSE") const chartTags = await queryRunner.query("select ct.chartId, t.parentId from chart_tags ct join tags t on ct.tagId = t.id") as { chartId: number, parentId: number }[] for (const ct of chartTags) { if (PUBLIC_TAG_PARENT_IDS.includes(ct.parentId)) { await queryRunner.query("update charts set is_indexable = ? where id = ?", [true, ct.chartId]) } } } public async down(queryRunner: QueryRunner): Promise<any> { } }
Set is_indexable as part of migration
Set is_indexable as part of migration
TypeScript
mit
OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/owid-grapher
--- +++ @@ -1,9 +1,18 @@ import {MigrationInterface, QueryRunner} from "typeorm"; +import _ = require('lodash') +import { PUBLIC_TAG_PARENT_IDS } from "settings"; export class ChartsIsIndexable1551312762103 implements MigrationInterface { + public async up(queryRunner: QueryRunner): Promise<any> { + await queryRunner.query("alter table charts ADD is_indexable BOOLEAN NOT NULL DEFAULT FALSE") - public async up(queryRunner: QueryRunner): Promise<any> { - queryRunner.query("alter table charts ADD is_indexable BOOLEAN NOT NULL DEFAULT FALSE") + const chartTags = await queryRunner.query("select ct.chartId, t.parentId from chart_tags ct join tags t on ct.tagId = t.id") as { chartId: number, parentId: number }[] + + for (const ct of chartTags) { + if (PUBLIC_TAG_PARENT_IDS.includes(ct.parentId)) { + await queryRunner.query("update charts set is_indexable = ? where id = ?", [true, ct.chartId]) + } + } } public async down(queryRunner: QueryRunner): Promise<any> {
a9c050cf8318e0f477071c71023cd6cf38a73aca
src/evaluation.ts
src/evaluation.ts
import { Grid } from './definitions'; export function evaluate(grid: Grid): number { return evaluateRows(grid) + evaluateColumns(grid) + evaluateDiagonals(grid); } function evaluateRows(grid: Grid): number { return 0; } function evaluateColumns(grid: Grid): number { return 0; } function evaluateDiagonals(grid: Grid): number { return 0; }
import { Grid, Row, Column, Diagonal } from './definitions'; import { getRows, getColumns, getDiagonals } from './utils'; export function evaluate(grid: Grid): number { return evaluateRows(grid) + evaluateColumns(grid) + evaluateDiagonals(grid); } function evaluateRows(grid: Grid): number { return getRows(grid) .map(evaluateCells) .reduce((x, y) => x + y, 0); } function evaluateColumns(grid: Grid): number { return getColumns(grid) .map(evaluateCells) .reduce((x, y) => x + y, 0); } function evaluateDiagonals(grid: Grid): number { return getDiagonals(grid) .map(evaluateCells) .reduce((x, y) => x + y, 0); } function evaluateCells(cells: boolean[]): number { return 0; }
Implement evaluateRows, evaluateColumns and evaluateDiagonals
Implement evaluateRows, evaluateColumns and evaluateDiagonals
TypeScript
mit
artfuldev/tictactoe-ai,artfuldev/tictactoe-ai
--- +++ @@ -1,17 +1,28 @@ -import { Grid } from './definitions'; +import { Grid, Row, Column, Diagonal } from './definitions'; +import { getRows, getColumns, getDiagonals } from './utils'; export function evaluate(grid: Grid): number { return evaluateRows(grid) + evaluateColumns(grid) + evaluateDiagonals(grid); } function evaluateRows(grid: Grid): number { - return 0; + return getRows(grid) + .map(evaluateCells) + .reduce((x, y) => x + y, 0); } function evaluateColumns(grid: Grid): number { - return 0; + return getColumns(grid) + .map(evaluateCells) + .reduce((x, y) => x + y, 0); } function evaluateDiagonals(grid: Grid): number { + return getDiagonals(grid) + .map(evaluateCells) + .reduce((x, y) => x + y, 0); +} + +function evaluateCells(cells: boolean[]): number { return 0; }
3f2440063956259b4fb7b6de6fab0452890b61dc
types/prismic-dom/index.d.ts
types/prismic-dom/index.d.ts
// Type definitions for prismic-dom 2.0 // Project: https://github.com/prismicio/prismic-dom#readme // Definitions by: Nick Whyte <https://github.com/nickw444> // Siggy Bilstein <https://github.com/sbilstein> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface RichText { asHtml(richText: any, linkResolver?: (doc: any) => string): string; asText(richText: any, linkResolver?: (doc: any) => string): string; } export const RichText: RichText; declare const _default: { RichText: RichText }; export default _default;
// Type definitions for prismic-dom 2.0 // Project: https://github.com/prismicio/prismic-dom#readme // Definitions by: Nick Whyte <https://github.com/nickw444> // Siggy Bilstein <https://github.com/sbilstein> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface RichText { asHtml(richText: any, linkResolver?: (doc: any) => string): string; asText(richText: any, joinString?: string): string; } export const RichText: RichText; declare const _default: { RichText: RichText }; export default _default;
Fix type to actually match the implementation
Fix type to actually match the implementation
TypeScript
mit
georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,AgentME/DefinitelyTyped
--- +++ @@ -6,7 +6,7 @@ interface RichText { asHtml(richText: any, linkResolver?: (doc: any) => string): string; - asText(richText: any, linkResolver?: (doc: any) => string): string; + asText(richText: any, joinString?: string): string; } export const RichText: RichText;
7b82e5a2c67375470fcd93d943b2b83432b37456
src/ts/Mission.ts
src/ts/Mission.ts
import Parser = require('./Parser'); import Ast = require('./Ast'); function updateItemsField(node: Parser.Node, itemCount: number): void { var itemsField: Parser.Node[] = Ast.select(node, 'items'); if (itemsField.length === 0) { Ast.addLiteralNode(node, 'items', itemCount, Parser.NodeType.NUMBER_FIELD); } else { itemsField[0].value = itemCount; } } function updateItemClassNames(allItems: Parser.Node[]): void { for (var i = 0, len = allItems.length; i < len; i++) { allItems[i].fieldName = 'Item' + i; } } export function mergeItems(node: Parser.Node, newItems: Parser.Node[]): void { node.fields = node.fields.concat(newItems); var allItems: Parser.Node[] = Ast.select(node, 'Item*'); updateItemsField(node, allItems.length); updateItemClassNames(allItems); }
import Parser = require('./Parser'); import Ast = require('./Ast'); function updateItemsField(node: Parser.Node, itemCount: number): void { var itemsField: Parser.Node[] = Ast.select(node, 'items'); if (itemsField.length === 0) { Ast.addLiteralNode(node, 'items', itemCount, Parser.NodeType.NUMBER_FIELD); } else { itemsField[0].value = itemCount; } } function updateItemClassNames(allItems: Parser.Node[]): void { for (var i = 0, len = allItems.length; i < len; i++) { allItems[i].fieldName = 'Item' + i; } } function updateIds(node: Parser.Node): number { var items = Ast.select(node, 'Item*'); var count = 0; for (var i = 0, len = items.length; i < len; i++) { if (Ast.select(items[i], 'dataType')[0].value = 'Group') { var groupItems = Ast.select(items[i], 'Entities.Item*'); for (var j = 0, groupLen = groupItems.length; j < groupLen; j++) { Ast.select(groupItems[j], 'id')[0].value = count + 1; count++; } } Ast.select(items[i], 'id')[0].value = count + 1; count++; } return count; } export function mergeItems(node: Parser.Node, newItems: Parser.Node[]): number { node.fields = node.fields.concat(newItems); var allItems: Parser.Node[] = Ast.select(node, 'Item*'); updateItemsField(node, allItems.length); updateItemClassNames(allItems); return updateIds(node); }
Support for ids in new mission sqm format.
Support for ids in new mission sqm format.
TypeScript
mit
kami-/config-parser
--- +++ @@ -16,9 +16,27 @@ } } -export function mergeItems(node: Parser.Node, newItems: Parser.Node[]): void { +function updateIds(node: Parser.Node): number { + var items = Ast.select(node, 'Item*'); + var count = 0; + for (var i = 0, len = items.length; i < len; i++) { + if (Ast.select(items[i], 'dataType')[0].value = 'Group') { + var groupItems = Ast.select(items[i], 'Entities.Item*'); + for (var j = 0, groupLen = groupItems.length; j < groupLen; j++) { + Ast.select(groupItems[j], 'id')[0].value = count + 1; + count++; + } + } + Ast.select(items[i], 'id')[0].value = count + 1; + count++; + } + return count; +} + +export function mergeItems(node: Parser.Node, newItems: Parser.Node[]): number { node.fields = node.fields.concat(newItems); var allItems: Parser.Node[] = Ast.select(node, 'Item*'); updateItemsField(node, allItems.length); updateItemClassNames(allItems); + return updateIds(node); }
44264635b7ad0eac22207f6f157231157d620d77
sources/resource.android.ts
sources/resource.android.ts
import { replace } from "./resource.common"; const Hashes = require("jshashes"); const SHA1 = new Hashes.SHA1; export function encodeKey(key: string): string { return "_" + SHA1.hex(key); } export function encodeValue(value: string): string { return '"' + replace(['"', "\\"], ['\\"', "\\\\"], value) + '"'; }
import { replace } from "./resource.common"; const Hashes = require("jshashes"); const SHA1 = new Hashes.SHA1; export function encodeKey(key: string): string { return "_" + SHA1.hex(key); } export function encodeValue(value: string): string { return replace(["'", '"', "\\", "<", "&"], ["\\'", '\\"', "\\\\", "&lt;", "&amp;"], value); }
Fix a bug with special XML characters in value
Fix a bug with special XML characters in value
TypeScript
mit
lfabreges/nativescript-localize,lfabreges/nativescript-localize,lfabreges/nativescript-localize,lfabreges/nativescript-localize
--- +++ @@ -8,5 +8,5 @@ } export function encodeValue(value: string): string { - return '"' + replace(['"', "\\"], ['\\"', "\\\\"], value) + '"'; + return replace(["'", '"', "\\", "<", "&"], ["\\'", '\\"', "\\\\", "&lt;", "&amp;"], value); }
90ba781ac5dd33f6ef7a979fbc9ded311eee5f89
e2e/common/common.ts
e2e/common/common.ts
const data = require('../data/users.json').users; import { ElementFinder } from 'protractor'; export class User { alias: string; description: string; username: string; password: string; constructor(alias: string, description: string) { this.alias = alias; this.description = description; this.username = data[alias].username; this.password = data[alias].password; } toString(): string { return `User{alias=${this.alias}, login=${this.username}}`; } } /** * Represents ui component that has it's angular selector. */ export interface IPaaSComponent { rootElement(): ElementFinder; }
const data = require('../data/users.json').users; import { ElementFinder } from 'protractor'; export class User { alias: string; description: string; username: string; password: string; constructor(alias: string, description: string) { this.alias = alias; this.description = description; const envUsername = process.env[`IPAAS_${alias.toUpperCase()}_USERNAME`] || null; const envPassword = process.env[`IPAAS_${alias.toUpperCase()}_PASSWORD`] || null; if (envUsername === null || envPassword === null) { this.username = data[alias].username; this.password = data[alias].password; } else { this.username = envUsername; this.password = envPassword; } } toString(): string { return `User{alias=${this.alias}, login=${this.username}}`; } } /** * Represents ui component that has it's angular selector. */ export interface IPaaSComponent { rootElement(): ElementFinder; }
Load e2e test creadentials from env vars
Load e2e test creadentials from env vars
TypeScript
apache-2.0
kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client
--- +++ @@ -12,8 +12,16 @@ this.alias = alias; this.description = description; - this.username = data[alias].username; - this.password = data[alias].password; + const envUsername = process.env[`IPAAS_${alias.toUpperCase()}_USERNAME`] || null; + const envPassword = process.env[`IPAAS_${alias.toUpperCase()}_PASSWORD`] || null; + + if (envUsername === null || envPassword === null) { + this.username = data[alias].username; + this.password = data[alias].password; + } else { + this.username = envUsername; + this.password = envPassword; + } }
49c667ad4ec59bb3225db2edafdc6a34824d793c
whisper/pages/new.tsx
whisper/pages/new.tsx
import {GetServerSidePropsContext, GetServerSidePropsResult} from "next" import {useApolloClient} from "@apollo/client" import {useRouter} from "next/router" import {Fragment, FC} from "react" import layout from "lib/hoc/layout" import withError from "lib/error/withError" import getApollo from "lib/graphql/client/getApollo" import getViewer from "api/query/viewer.gql" import add from "api/mutation/post/add.gql" import EditorLayout from "layout/Editor" import Title from "component/Title" import Editor from "component/Post/Editor" import withLogin from "component/Login/withLogin" export const getServerSideProps = withError( async ({req}: GetServerSidePropsContext) => { const client = getApollo(undefined, req) const props = await client.query({query: getViewer}) return { props } } ) const NewPost: FC = () => { const router = useRouter() const client = useApolloClient() const submit = (post: any) => client .mutate({mutation: add, variables: {post}}) .then(({data}) => router.push(data.postAdd.slug)) .catch(console.error) return ( <Fragment> <Title titleTemplate="%s - New post" /> <Editor onSubmit={submit} /> </Fragment> ) } export default layout(EditorLayout)(withLogin(NewPost))
import {GetServerSidePropsContext, GetServerSidePropsResult} from "next" import {useApolloClient} from "@apollo/client" import {useRouter} from "next/router" import {Fragment, FC} from "react" import layout from "lib/hoc/layout" import withError from "lib/error/withError" import getApollo from "lib/graphql/client/getApollo" import getViewer from "api/query/viewer.gql" import add from "api/mutation/post/add.gql" import EditorLayout from "layout/Editor" import Title from "component/Title" import Editor from "component/Post/Editor" import withLogin from "component/Login/withLogin" export const getServerSideProps = withError( async ({req}: GetServerSidePropsContext) => { const client = getApollo(undefined, req) const props = await client.query({query: getViewer}) return { props } } ) const NewPost: FC = () => { const router = useRouter() const client = useApolloClient() const submit = (post: any) => client .mutate({mutation: add, variables: {post}}) .then(({data}) => { if (data.postAdd.isDraft === false) { router.push(data.postAdd.slug) } }) .catch(console.error) return ( <Fragment> <Title titleTemplate="%s - New post" /> <Editor onSubmit={submit} /> </Fragment> ) } export default layout(EditorLayout)(withLogin(NewPost))
Remove redirection for drafted posts
whisper: Remove redirection for drafted posts
TypeScript
mit
octet-stream/eri,octet-stream/eri
--- +++ @@ -34,7 +34,11 @@ const submit = (post: any) => client .mutate({mutation: add, variables: {post}}) - .then(({data}) => router.push(data.postAdd.slug)) + .then(({data}) => { + if (data.postAdd.isDraft === false) { + router.push(data.postAdd.slug) + } + }) .catch(console.error) return (
a243b48c80fe221238137f7921e2b961a40396fa
src/providers/File.ts
src/providers/File.ts
import i = require('../Interfaces'); import _ = require('lodash'); import Utils = require('../Utils'); import Path = require('path'); var filter: any = require('fuzzaldrin').filter; class File implements i.AutocompletionProvider { getSuggestions(currentDirectory: string, input: i.Parsable) { return new Promise((resolve) => { if (input.getLexemes().length < 2) { return resolve([]); } var enteredDirectoriesPath = Utils.normalizeDir(Path.dirname(input.getLastLexeme())); var searchDirectory = Utils.normalizeDir(Path.join(currentDirectory, enteredDirectoriesPath)); Utils.stats(searchDirectory).then((fileInfos) => { var all = _.map(fileInfos, (fileInfo: i.FileInfo) => { let name = fileInfo.name; if (fileInfo.stat.isDirectory()) { name = Utils.normalizeDir(name); } var suggestion: i.Suggestion = { value: name, score: 0, synopsis: '', description: '', type: 'file', partial: fileInfo.stat.isDirectory(), }; if (searchDirectory != currentDirectory) { suggestion.prefix = enteredDirectoriesPath; } return suggestion; }); resolve(filter(all, Path.basename(input.getLastLexeme()), {key: 'value', maxResults: 30})); }); }); } } export = File;
import i = require('../Interfaces'); import _ = require('lodash'); import Utils = require('../Utils'); import Path = require('path'); var filter: any = require('fuzzaldrin').filter; class File implements i.AutocompletionProvider { getSuggestions(currentDirectory: string, input: i.Parsable) { return new Promise((resolve) => { if (input.getLexemes().length < 2) { return resolve([]); } var enteredDirectoriesPath = Utils.normalizeDir(Path.dirname(input.getLastLexeme())); if (Path.isAbsolute(enteredDirectoriesPath)) { var searchDirectory = enteredDirectoriesPath; } else { searchDirectory = Utils.normalizeDir(Path.join(currentDirectory, enteredDirectoriesPath)); } Utils.stats(searchDirectory).then((fileInfos) => { var all = _.map(fileInfos, (fileInfo: i.FileInfo) => { let name = fileInfo.name; if (fileInfo.stat.isDirectory()) { name = Utils.normalizeDir(name); } var suggestion: i.Suggestion = { value: name, score: 0, synopsis: '', description: '', type: 'file', partial: fileInfo.stat.isDirectory(), }; if (searchDirectory != currentDirectory) { suggestion.prefix = enteredDirectoriesPath; } return suggestion; }); resolve(filter(all, Path.basename(input.getLastLexeme()), {key: 'value', maxResults: 30})); }); }); } } export = File;
Allow to glob absolute paths.
Allow to glob absolute paths.
TypeScript
mit
Cavitt/black-screen,Ribeiro/black-screen,Thundabrow/black-screen,Dangku/black-screen,smaty1/black-screen,Ribeiro/black-screen,Dangku/black-screen,w9jds/black-screen,Dangku/black-screen,geksilla/black-screen,drew-gross/black-screen,smaty1/black-screen,Young55555/black-screen,jacobmarshall/black-screen,noikiy/black-screen,black-screen/black-screen,JimLiu/black-screen,rakesh-mohanta/black-screen,vshatskyi/black-screen,smaty1/black-screen,Suninus/black-screen,over300laughs/black-screen,drew-gross/black-screen,gabrielbellamy/black-screen,black-screen/black-screen,N00D13/black-screen,kingland/black-screen,vshatskyi/black-screen,kustomzone/black-screen,alice-gh/black-screen-1,gabrielbellamy/black-screen,jbhannah/black-screen,stefohnee/black-screen,railsware/upterm,gabrielbellamy/black-screen,Thundabrow/black-screen,habibmasuro/black-screen,jassyboy/black-screen,Serg09/black-screen,geksilla/black-screen,bodiam/black-screen,black-screen/black-screen,j-allard/black-screen,stefohnee/black-screen,over300laughs/black-screen,rocky-jaiswal/black-screen,taraszerebecki/black-screen,shockone/black-screen,gastrodia/black-screen,JimLiu/black-screen,mzgnr/black-screen,alessandrostone/black-screen,stefohnee/black-screen,kingland/black-screen,toxic88/black-screen,mzgnr/black-screen,bestwpw/black-screen,adamliesko/black-screen,Cavitt/black-screen,alice-gh/black-screen-1,genecyber/black-screen,littlecodeshop/black-screen,jassyboy/black-screen,jonadev95/black-screen,jbhannah/black-screen,williara/black-screen,drew-gross/black-screen,AnalogRez/black-screen,w9jds/black-screen,genecyber/black-screen,habibmasuro/black-screen,jqk6/black-screen,skomski/black-screen,adamliesko/black-screen,ammaroff/black-screen,rocky-jaiswal/black-screen,rob3ns/black-screen,shockone/black-screen,kaze13/black-screen,habibmasuro/black-screen,geksilla/black-screen,taraszerebecki/black-screen,over300laughs/black-screen,kaze13/black-screen,Suninus/black-screen,JimLiu/black-screen,Thundabrow/black-screen,ammaroff/black-screen,kustomzone/black-screen,Cavitt/black-screen,toxic88/black-screen,gastrodia/black-screen,jassyboy/black-screen,rakesh-mohanta/black-screen,genecyber/black-screen,rakesh-mohanta/black-screen,adamliesko/black-screen,jqk6/black-screen,bodiam/black-screen,rob3ns/black-screen,RyanTech/black-screen,jacobmarshall/black-screen,Young55555/black-screen,Serg09/black-screen,gastrodia/black-screen,noikiy/black-screen,RyanTech/black-screen,littlecodeshop/black-screen,kaze13/black-screen,kingland/black-screen,jqk6/black-screen,jonadev95/black-screen,cyrixhero/black-screen,toxic88/black-screen,railsware/upterm,N00D13/black-screen,alessandrostone/black-screen,w9jds/black-screen,williara/black-screen,noikiy/black-screen,AnalogRez/black-screen,bestwpw/black-screen,mzgnr/black-screen,Serg09/black-screen,williara/black-screen,AnalogRez/black-screen,bodiam/black-screen,ammaroff/black-screen,bestwpw/black-screen,Young55555/black-screen,RyanTech/black-screen,rocky-jaiswal/black-screen,taraszerebecki/black-screen,j-allard/black-screen,vshatskyi/black-screen,littlecodeshop/black-screen,alessandrostone/black-screen,jbhannah/black-screen,Suninus/black-screen,jacobmarshall/black-screen,jonadev95/black-screen,cyrixhero/black-screen,Ribeiro/black-screen,cyrixhero/black-screen,kustomzone/black-screen,rob3ns/black-screen,N00D13/black-screen,skomski/black-screen,j-allard/black-screen,drew-gross/black-screen,alice-gh/black-screen-1,vshatskyi/black-screen,skomski/black-screen
--- +++ @@ -12,7 +12,12 @@ } var enteredDirectoriesPath = Utils.normalizeDir(Path.dirname(input.getLastLexeme())); - var searchDirectory = Utils.normalizeDir(Path.join(currentDirectory, enteredDirectoriesPath)); + + if (Path.isAbsolute(enteredDirectoriesPath)) { + var searchDirectory = enteredDirectoriesPath; + } else { + searchDirectory = Utils.normalizeDir(Path.join(currentDirectory, enteredDirectoriesPath)); + } Utils.stats(searchDirectory).then((fileInfos) => { var all = _.map(fileInfos, (fileInfo: i.FileInfo) => {
b73e6853f471974c5c009e874adb2fa24738394e
web-ng/src/app/shared/models/project.model.ts
web-ng/src/app/shared/models/project.model.ts
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { StringDictionary } from "./string-dictionary.model"; export class Project { constructor( readonly title: StringDictionary, readonly description?: string ) {} }
/** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { StringDictionary } from "./string-dictionary.model"; export class Project { constructor( readonly title: StringDictionary, readonly description: StringDictionary ) {} }
Use string dict for project description
Use string dict for project description
TypeScript
apache-2.0
google/ground-platform,google/ground-platform,google/ground-platform,google/ground-platform
--- +++ @@ -19,6 +19,6 @@ export class Project { constructor( readonly title: StringDictionary, - readonly description?: string + readonly description: StringDictionary ) {} }
39a1184178bcbc16bd7dba5c6a678c333d82ee14
src/app/app.component.ts
src/app/app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <span fxShow="false" fxShow.xs> XS </span> <span fxShow="false" fxShow.sm> SM </span> <span fxShow="false" fxShow.md> MD </span> <span fxShow="false" fxShow.lg> LG </span> <span fxShow="false" fxShow.xl> XL </span> <router-outlet></router-outlet>`, }) export class AppComponent { constructor() { } }
import { Component } from '@angular/core'; import { environment } from 'environments/environment'; @Component({ selector: 'app-root', template: ` <div *ngIf="sizeHelp"> <span fxShow="false" fxShow.xs> XS </span> <span fxShow="false" fxShow.sm> SM </span> <span fxShow="false" fxShow.md> MD </span> <span fxShow="false" fxShow.lg> LG </span> <span fxShow="false" fxShow.xl> XL </span> </div> <router-outlet></router-outlet>`, }) export class AppComponent { constructor() { } get sizeHelp(): boolean { return environment.production === false; } }
Hide size help in production mode
Hide size help in production mode
TypeScript
mit
knowledgeplazza/knowledgeplazza,knowledgeplazza/knowledgeplazza,knowledgeplazza/knowledgeplazza
--- +++ @@ -1,15 +1,22 @@ import { Component } from '@angular/core'; +import { environment } from 'environments/environment'; @Component({ selector: 'app-root', template: ` - <span fxShow="false" fxShow.xs> XS </span> - <span fxShow="false" fxShow.sm> SM </span> - <span fxShow="false" fxShow.md> MD </span> - <span fxShow="false" fxShow.lg> LG </span> - <span fxShow="false" fxShow.xl> XL </span> + <div *ngIf="sizeHelp"> + <span fxShow="false" fxShow.xs> XS </span> + <span fxShow="false" fxShow.sm> SM </span> + <span fxShow="false" fxShow.md> MD </span> + <span fxShow="false" fxShow.lg> LG </span> + <span fxShow="false" fxShow.xl> XL </span> + </div> <router-outlet></router-outlet>`, }) export class AppComponent { constructor() { } + + get sizeHelp(): boolean { + return environment.production === false; + } }
40e7d012cf0f2e5df82595ec9b6d856ec81a2532
web/components/Header/index.tsx
web/components/Header/index.tsx
import { AppBar, IconButton, Toolbar, Typography } from "@material-ui/core"; import { createStyles, makeStyles } from "@material-ui/core/styles"; import { GitHub } from "@material-ui/icons"; import { useRouter } from "next/router"; import { useTranslation } from "../../hooks/useTranslation"; import LangMenu from "./LangMenu"; const useStyles = makeStyles(() => createStyles({ root: { flexGrow: 1, }, title: { flexGrow: 1, cursor: "pointer", }, }) ); const Header: React.FC = () => { const router = useRouter(); const classes = useStyles(); const { t } = useTranslation(); const onClickTitle = () => router.push("/", "/"); return ( <header> <AppBar position="fixed"> <Toolbar> <Typography variant="h6" className={classes.title} onClick={onClickTitle} > {t.title} </Typography> <nav> <LangMenu /> <IconButton aria-label="github" color="inherit" href="https://github.com/nownabe/cloud-demos" target="_blank" rel="noopener noreferrer" > <GitHub /> </IconButton> </nav> </Toolbar> </AppBar> </header> ); }; export default Header;
import { AppBar, IconButton, Toolbar, Typography } from "@material-ui/core"; import { createStyles, makeStyles } from "@material-ui/core/styles"; import { GitHub } from "@material-ui/icons"; import { useRouter } from "next/router"; import { useTranslation } from "../../hooks/useTranslation"; import LangMenu from "./LangMenu"; const useStyles = makeStyles(() => createStyles({ root: { flexGrow: 1, }, title: { flexGrow: 1, cursor: "pointer", }, }) ); const Header: React.FC = () => { const router = useRouter(); const classes = useStyles(); const { t } = useTranslation(); const onClickTitle = () => router.push("/", "/"); return ( <header> <AppBar position="fixed"> <Toolbar> <Typography variant="h6" className={classes.title} onClick={onClickTitle} > {t.title} </Typography> <nav> <LangMenu /> {/* <IconButton aria-label="github" color="inherit" href="https://github.com/nownabe/cloud-demos" target="_blank" rel="noopener noreferrer" > <GitHub /> </IconButton> */} </nav> </Toolbar> </AppBar> </header> ); }; export default Header;
Hide link to GitHub temporarily
Hide link to GitHub temporarily
TypeScript
apache-2.0
GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal,GoogleCloudPlatform/appengine-cloud-demo-portal
--- +++ @@ -38,6 +38,7 @@ </Typography> <nav> <LangMenu /> + {/* <IconButton aria-label="github" color="inherit" @@ -47,6 +48,7 @@ > <GitHub /> </IconButton> + */} </nav> </Toolbar> </AppBar>
a25363bc700f5c9148344f28c44b7cb125fe15d2
packages/components/containers/payments/subscription/SubscriptionUpgrade.tsx
packages/components/containers/payments/subscription/SubscriptionUpgrade.tsx
import { c } from 'ttag'; import { CircleLoader } from '../../../components'; const SubscriptionUpgrade = () => { return ( <> <CircleLoader size="large" className="center flex color-primary" /> <h1 className="text-xl text-bold mb0">{c('Title').t`Processing`}</h1> <p className="text-center mt0-5">{c('Info') .t`Your account is being upgraded, this may take up to 30 seconds.`}</p> <p className="text-center color-weak pb2 mb2">{c('Info').t`Thank you for supporting our mission.`}</p> </> ); }; export default SubscriptionUpgrade;
import { c } from 'ttag'; import { CircleLoader } from '../../../components'; const SubscriptionUpgrade = () => { return ( <> <CircleLoader size="large" className="center flex color-primary mb0-5" /> <h1 className="text-xl text-bold mb0">{c('Title').t`Processing`}</h1> <p className="text-center mt0-5">{c('Info') .t`Your account is being upgraded, this may take up to 30 seconds.`}</p> <p className="text-center color-weak pb2 mb2">{c('Info').t`Thank you for supporting our mission.`}</p> </> ); }; export default SubscriptionUpgrade;
Add spacing between loader and text
Add spacing between loader and text
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -4,7 +4,7 @@ const SubscriptionUpgrade = () => { return ( <> - <CircleLoader size="large" className="center flex color-primary" /> + <CircleLoader size="large" className="center flex color-primary mb0-5" /> <h1 className="text-xl text-bold mb0">{c('Title').t`Processing`}</h1> <p className="text-center mt0-5">{c('Info') .t`Your account is being upgraded, this may take up to 30 seconds.`}</p>
551e94fcbd39a9155e39fb6f1cef898456dd6ba7
packages/skin-database/api/graphql/defaultQuery.ts
packages/skin-database/api/graphql/defaultQuery.ts
const DEFAULT_QUERY = `# Winamp Skins GraphQL API # # https://skins.webamp.org # # This is a GraphQL API for the Winamp Skin Museum's database. # It's mostly intended for exploring the data set. Please feel # free to have a look around and see what you can find! # # The GraphiQL environment has many helpful features to help # you discover what fields exist and what they mean, so be bold! # # If you have any questions or feedback, please get in touch: # - Twitter: @captbaritone # - Email: [email protected] # - Discord: https://webamp.org/chat # An example query to get you started... query MyQuery { # Get info about a @winampskins tweet # (spoiler, it's Luigihann's ZeldaAmp) fetch_tweet_by_url(url: "https://twitter.com/winampskins/status/1056605906597629953") { skin { # The filename of the skin that the tweet is about filename download_url screenshot_url museum_url # All the tweets that shared this skin tweets { likes retweets url } # Information about the files contained within the skin archive_files { filename # For image files, try hovering the # returned url ---> url # Date the file was created according to the zip file date } } } }`; export default DEFAULT_QUERY;
const DEFAULT_QUERY = `# Winamp Skins GraphQL API # # https://skins.webamp.org # # This is a GraphQL API for the Winamp Skin Museum's database. # It's mostly intended for exploring the data set. Please feel # free to have a look around and see what you can find! # # The GraphiQL environment has many helpful features to help # you discover what fields exist and what they mean, so be bold! # # If you have any questions or feedback, please get in touch: # - Twitter: @captbaritone # - Email: [email protected] # - Discord: https://webamp.org/chat # An example query to get you started... query MyQuery { # Search for a skin made by LuigiHann search_skins(query: "luigihann zelda", first: 1) { # The filename of the skin filename download_url museum_url # Try hovering the returned url # for a preview of the skin --> screenshot_url # All the tweets that shared this skin tweets { likes retweets url } # Information about the files contained within the skin archive_files { filename # For image files, try hovering the # returned url ---> url # Date the file was created according to the zip file date } } }`; export default DEFAULT_QUERY;
Use seach in the example query
Use seach in the example query
TypeScript
mit
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
--- +++ @@ -17,33 +17,33 @@ # An example query to get you started... query MyQuery { - # Get info about a @winampskins tweet - # (spoiler, it's Luigihann's ZeldaAmp) - fetch_tweet_by_url(url: "https://twitter.com/winampskins/status/1056605906597629953") { - skin { - # The filename of the skin that the tweet is about + # Search for a skin made by LuigiHann + search_skins(query: "luigihann zelda", first: 1) { + # The filename of the skin + filename + download_url + museum_url + + # Try hovering the returned url + # for a preview of the skin --> + screenshot_url + + # All the tweets that shared this skin + tweets { + likes + retweets + url + } + + # Information about the files contained within the skin + archive_files { filename - download_url - screenshot_url - museum_url - - # All the tweets that shared this skin - tweets { - likes - retweets - url - } - - # Information about the files contained within the skin - archive_files { - filename - # For image files, try hovering the - # returned url ---> - url - # Date the file was created according to the zip file - date - } + # For image files, try hovering the + # returned url ---> + url + # Date the file was created according to the zip file + date } } }`;
c996381b75d054cf569161924c12f6d26638a493
src/statusBar/controller.ts
src/statusBar/controller.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Alessandro Fragnani. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, window, workspace } from "vscode"; import { FileAccess } from "./../constants"; import { Container } from "./../container"; import { StatusBar } from "./statusBar"; export class Controller { private statusBar: StatusBar; private disposable: Disposable; constructor() { this.statusBar = new StatusBar(); this.statusBar.update(); Container.context.subscriptions.push(this.statusBar); window.onDidChangeActiveTextEditor(editor => { if (editor) { this.statusBar.update(); } }, null, Container.context.subscriptions); workspace.onDidChangeConfiguration(cfg => { if (cfg.affectsConfiguration("fileAccess.position")) { this.statusBar.dispose(); this.statusBar = undefined; this.statusBar = new StatusBar(); } if (cfg.affectsConfiguration("fileAccess")) { this.updateStatusBar(); } }, null, Container.context.subscriptions); } public dispose() { this.disposable.dispose(); } public updateStatusBar(fileAccess?: FileAccess) { this.statusBar.update(fileAccess); } }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Alessandro Fragnani. All rights reserved. * Licensed under the MIT License. See License.md in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, window, workspace } from "vscode"; import { FileAccess } from "./../constants"; import { Container } from "./../container"; import { StatusBar } from "./statusBar"; export class Controller { private statusBar: StatusBar; private disposable: Disposable; constructor() { this.statusBar = new StatusBar(); this.statusBar.update(); Container.context.subscriptions.push(this.statusBar); window.onDidChangeActiveTextEditor(_editor => { this.statusBar.update(); }, null, Container.context.subscriptions); workspace.onDidChangeConfiguration(cfg => { if (cfg.affectsConfiguration("fileAccess.position")) { this.statusBar.dispose(); this.statusBar = undefined; this.statusBar = new StatusBar(); } if (cfg.affectsConfiguration("fileAccess")) { this.updateStatusBar(); } }, null, Container.context.subscriptions); } public dispose() { this.disposable.dispose(); } public updateStatusBar(fileAccess?: FileAccess) { this.statusBar.update(fileAccess); } }
Fix bug where the status bar indicator didn't get hidden when switching to a non-editor window.
Fix bug where the status bar indicator didn't get hidden when switching to a non-editor window.
TypeScript
mit
alefragnani/vscode-read-only-indicator,alefragnani/vscode-read-only-indicator
--- +++ @@ -18,10 +18,8 @@ Container.context.subscriptions.push(this.statusBar); - window.onDidChangeActiveTextEditor(editor => { - if (editor) { - this.statusBar.update(); - } + window.onDidChangeActiveTextEditor(_editor => { + this.statusBar.update(); }, null, Container.context.subscriptions); workspace.onDidChangeConfiguration(cfg => {
9706d48b326b8365643fa32fbfb1c98c81b19166
src/extension.ts
src/extension.ts
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import { languages, ExtensionContext } from 'vscode'; import { CssCompletionItemProvider } from './cssCompletionItemProvider'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: ExtensionContext) { let disposable = languages.registerCompletionItemProvider('html', new CssCompletionItemProvider()); context.subscriptions.push(disposable); } // this method is called when your extension is deactivated export function deactivate() { }
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import { languages, ExtensionContext, workspace } from 'vscode'; import { CssCompletionItemProvider } from './cssCompletionItemProvider'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: ExtensionContext) { let provider = new CssCompletionItemProvider(); let disposable = languages.registerCompletionItemProvider('html', provider); let saveEventDisposable = workspace.onDidSaveTextDocument((e) => { if(e.languageId === 'css') { provider.refreshCompletionItems(); } }) context.subscriptions.push(disposable, saveEventDisposable); } // this method is called when your extension is deactivated export function deactivate() { }
Refresh css classes on changes.
Refresh css classes on changes. This change adds an event listener on the save event of the workspace that refreshes the list of css classes when a css file has been changed. Fixes issue #4.
TypeScript
mit
andersea/HTMLClassSuggestionsVSCode
--- +++ @@ -1,16 +1,24 @@ 'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below -import { languages, ExtensionContext } from 'vscode'; +import { languages, ExtensionContext, workspace } from 'vscode'; import { CssCompletionItemProvider } from './cssCompletionItemProvider'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: ExtensionContext) { - let disposable = languages.registerCompletionItemProvider('html', new CssCompletionItemProvider()); + let provider = new CssCompletionItemProvider(); - context.subscriptions.push(disposable); + let disposable = languages.registerCompletionItemProvider('html', provider); + + let saveEventDisposable = workspace.onDidSaveTextDocument((e) => { + if(e.languageId === 'css') { + provider.refreshCompletionItems(); + } + }) + + context.subscriptions.push(disposable, saveEventDisposable); } // this method is called when your extension is deactivated
c78149215b57c65ab1493cdd2e079d9d0b8d67c1
tests/cases/fourslash/jsxSpreadReference.ts
tests/cases/fourslash/jsxSpreadReference.ts
/// <reference path='fourslash.ts' /> //@Filename: file.tsx //// declare module JSX { //// interface Element { } //// interface IntrinsicElements { //// } //// interface ElementAttributesProperty { props } //// } //// class MyClass { //// props: { //// name?: string; //// size?: number; //// } //// } //// //// var [|/*dst*/nn|]: {name?: string; size?: number}; //// var x = <MyClass {...[|n/*src*/n|]}></MyClass>; goTo.marker('src'); goTo.definition(); verify.caretAtMarker('dst'); goTo.marker('src'); verify.renameLocations(false, false);
/// <reference path='fourslash.ts' /> //@Filename: file.tsx //// declare module JSX { //// interface Element { } //// interface IntrinsicElements { //// } //// interface ElementAttributesProperty { props } //// } //// class MyClass { //// props: { //// name?: string; //// size?: number; //// } //// } //// //// var [|/*dst*/nn|]: {name?: string; size?: number}; //// var x = <MyClass {...[|n/*src*/n|]}></MyClass>; goTo.marker('src'); goTo.definition(); verify.caretAtMarker('dst'); goTo.marker('src'); verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false);
Add comments to bool params
Add comments to bool params
TypeScript
apache-2.0
AbubakerB/TypeScript,jwbay/TypeScript,thr0w/Thr0wScript,vilic/TypeScript,Microsoft/TypeScript,plantain-00/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,microsoft/TypeScript,ziacik/TypeScript,Eyas/TypeScript,ionux/TypeScript,jeremyepling/TypeScript,thr0w/Thr0wScript,basarat/TypeScript,AbubakerB/TypeScript,erikmcc/TypeScript,fabioparra/TypeScript,synaptek/TypeScript,chuckjaz/TypeScript,nycdotnet/TypeScript,minestarks/TypeScript,blakeembrey/TypeScript,Eyas/TypeScript,synaptek/TypeScript,ziacik/TypeScript,jeremyepling/TypeScript,weswigham/TypeScript,mmoskal/TypeScript,yortus/TypeScript,mmoskal/TypeScript,plantain-00/TypeScript,alexeagle/TypeScript,minestarks/TypeScript,mihailik/TypeScript,ziacik/TypeScript,evgrud/TypeScript,vilic/TypeScript,DLehenbauer/TypeScript,kitsonk/TypeScript,blakeembrey/TypeScript,evgrud/TypeScript,fabioparra/TypeScript,basarat/TypeScript,mihailik/TypeScript,plantain-00/TypeScript,kpreisser/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,yortus/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,plantain-00/TypeScript,yortus/TypeScript,thr0w/Thr0wScript,ziacik/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,samuelhorwitz/typescript,blakeembrey/TypeScript,minestarks/TypeScript,mmoskal/TypeScript,samuelhorwitz/typescript,donaldpipowitch/TypeScript,basarat/TypeScript,kimamula/TypeScript,ionux/TypeScript,kpreisser/TypeScript,thr0w/Thr0wScript,mihailik/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,evgrud/TypeScript,jeremyepling/TypeScript,jwbay/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,Eyas/TypeScript,chuckjaz/TypeScript,kitsonk/TypeScript,chuckjaz/TypeScript,TukekeSoft/TypeScript,yortus/TypeScript,alexeagle/TypeScript,kpreisser/TypeScript,TukekeSoft/TypeScript,jwbay/TypeScript,synaptek/TypeScript,synaptek/TypeScript,kimamula/TypeScript,samuelhorwitz/typescript,vilic/TypeScript,blakeembrey/TypeScript,mmoskal/TypeScript,weswigham/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,Eyas/TypeScript,erikmcc/TypeScript,microsoft/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,ionux/TypeScript,Microsoft/TypeScript,nycdotnet/TypeScript,samuelhorwitz/typescript,chuckjaz/TypeScript,nycdotnet/TypeScript,evgrud/TypeScript,jwbay/TypeScript,nycdotnet/TypeScript,SaschaNaz/TypeScript,kimamula/TypeScript,ionux/TypeScript,kimamula/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,AbubakerB/TypeScript,mihailik/TypeScript,kitsonk/TypeScript,fabioparra/TypeScript,AbubakerB/TypeScript,DLehenbauer/TypeScript,fabioparra/TypeScript,DLehenbauer/TypeScript,erikmcc/TypeScript,RyanCavanaugh/TypeScript
--- +++ @@ -22,4 +22,4 @@ verify.caretAtMarker('dst'); goTo.marker('src'); -verify.renameLocations(false, false); +verify.renameLocations(/*findInStrings*/ false, /*findInComments*/ false);
b8d6beb9ceb2a9e1bad0d08dd8715a4d57ad0379
client/sharedClasses/user.ts
client/sharedClasses/user.ts
export class User { id: number; first_name: string; last_name: string; email: string; email_verified: boolean; district: string; nic: string; phone: string; phone_no_verified: boolean; type_id: number; type: string; password: string; } export class UserType { id: number; type_name: string; }
export class User { id: number; first_name: string; last_name: string; email: string; email_verified: boolean; district: string; nic: string; phone: string; phone_no_verified: boolean; type_id: number; type: string; password: string; veri_code: number; } export class UserType { id: number; type_name: string; }
Modify model to have verfication code
Modify model to have verfication code
TypeScript
mit
shavindraSN/examen,shavindraSN/examen,shavindraSN/examen
--- +++ @@ -11,6 +11,7 @@ type_id: number; type: string; password: string; + veri_code: number; } export class UserType { id: number;
4203d0aebdcfecdd789b23338c5005c89db23aa5
semver-diff/index.d.ts
semver-diff/index.d.ts
// Type definitions for semver-diff v2.1.0 // Project: https://github.com/sindresorhus/semver-diff // Definitions by: Chris Barr <https://github.com/chrismbarr> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/semver-diff declare namespace SemverDiff { type SemverDiffReturn = 'major' | 'minor' | 'patch' | 'prerelease' | 'build' | null; export default function(versionA: string, versionB: string): SemverDiffReturn; } declare module 'semver-diff' { export = SemverDiff.default; }
// Type definitions for semver-diff 2.1 // Project: https://github.com/sindresorhus/semver-diff // Definitions by: Chris Barr <https://github.com/chrismbarr> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/semver-diff declare namespace SemverDiff { type SemverDiffReturn = 'major' | 'minor' | 'patch' | 'prerelease' | 'build' | null; export default function(versionA: string, versionB: string): SemverDiffReturn; } declare module 'semver-diff' { export = SemverDiff.default; }
Fix version number linting violation
Fix version number linting violation
TypeScript
mit
markogresak/DefinitelyTyped,smrq/DefinitelyTyped,jimthedev/DefinitelyTyped,pocesar/DefinitelyTyped,chrootsu/DefinitelyTyped,minodisk/DefinitelyTyped,alvarorahul/DefinitelyTyped,magny/DefinitelyTyped,arusakov/DefinitelyTyped,one-pieces/DefinitelyTyped,benishouga/DefinitelyTyped,YousefED/DefinitelyTyped,rolandzwaga/DefinitelyTyped,QuatroCode/DefinitelyTyped,martinduparc/DefinitelyTyped,sledorze/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,sledorze/DefinitelyTyped,use-strict/DefinitelyTyped,AgentME/DefinitelyTyped,mcrawshaw/DefinitelyTyped,QuatroCode/DefinitelyTyped,johan-gorter/DefinitelyTyped,scriby/DefinitelyTyped,smrq/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,martinduparc/DefinitelyTyped,jimthedev/DefinitelyTyped,dsebastien/DefinitelyTyped,ashwinr/DefinitelyTyped,pocesar/DefinitelyTyped,chrismbarr/DefinitelyTyped,georgemarshall/DefinitelyTyped,benishouga/DefinitelyTyped,psnider/DefinitelyTyped,magny/DefinitelyTyped,shlomiassaf/DefinitelyTyped,minodisk/DefinitelyTyped,hellopao/DefinitelyTyped,aciccarello/DefinitelyTyped,shlomiassaf/DefinitelyTyped,subash-a/DefinitelyTyped,arusakov/DefinitelyTyped,arusakov/DefinitelyTyped,benliddicott/DefinitelyTyped,nycdotnet/DefinitelyTyped,pocesar/DefinitelyTyped,zuzusik/DefinitelyTyped,dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,abbasmhd/DefinitelyTyped,isman-usoh/DefinitelyTyped,alvarorahul/DefinitelyTyped,isman-usoh/DefinitelyTyped,martinduparc/DefinitelyTyped,chrootsu/DefinitelyTyped,hellopao/DefinitelyTyped,nycdotnet/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,psnider/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,benishouga/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,abbasmhd/DefinitelyTyped,progre/DefinitelyTyped,amir-arad/DefinitelyTyped,mcliment/DefinitelyTyped,progre/DefinitelyTyped,alexdresko/DefinitelyTyped,johan-gorter/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,use-strict/DefinitelyTyped,scriby/DefinitelyTyped,psnider/DefinitelyTyped,jimthedev/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,georgemarshall/DefinitelyTyped,YousefED/DefinitelyTyped,AgentME/DefinitelyTyped,micurs/DefinitelyTyped,georgemarshall/DefinitelyTyped,aciccarello/DefinitelyTyped,chrismbarr/DefinitelyTyped,mcrawshaw/DefinitelyTyped,georgemarshall/DefinitelyTyped,hellopao/DefinitelyTyped,borisyankov/DefinitelyTyped,ashwinr/DefinitelyTyped,subash-a/DefinitelyTyped
--- +++ @@ -1,4 +1,4 @@ -// Type definitions for semver-diff v2.1.0 +// Type definitions for semver-diff 2.1 // Project: https://github.com/sindresorhus/semver-diff // Definitions by: Chris Barr <https://github.com/chrismbarr> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/semver-diff
3fcd9a4e44e2f8851a54d47558d814c512d76c19
app/CakeInput.tsx
app/CakeInput.tsx
import * as React from "react"; class CakeInput extends React.Component<any, void> { constructor(props: React.Props<any>) { super(props); // Required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); } refs: { [string: string]: any; cakeName: any; } onSubmit(e: Event) { e.preventDefault(); const newCake = { name: this.refs.cakeName.value, description: "", date: new Date() }; // Propagate to external handler this.props.onSubmit(newCake); } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> <input ref="cakeName" type="text" defaultValue="" placeholder="Cake name" /> <button type="submit">Add</button> </form> ); } } export default CakeInput;
import * as React from "react"; interface CakeInputState { value: string; } class CakeInput extends React.Component<any, CakeInputState> { constructor(props: React.Props<any>) { super(props); // Required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); this.state = { value: "" }; } refs: { [string: string]: any; cakeName: any; } onSubmit(e: Event) { e.preventDefault(); const newCake = { name: this.refs.cakeName.value, description: "", date: new Date() }; // Propagate to external handler this.props.onSubmit(newCake); // State didn't for some reason propagate correctly to the input's default value, // so clearing the input field directly for now this.refs.cakeName.value = ""; } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> <input ref="cakeName" type="text" placeholder="Cake name" /> <button type="submit">Add</button> </form> ); } } export default CakeInput;
Clear text field on input
Clear text field on input
TypeScript
mit
mieky/we-love-cake,mieky/we-love-cake
--- +++ @@ -1,12 +1,17 @@ import * as React from "react"; -class CakeInput extends React.Component<any, void> { +interface CakeInputState { + value: string; +} + +class CakeInput extends React.Component<any, CakeInputState> { constructor(props: React.Props<any>) { super(props); // Required because of the ES6 class syntax decifiency this.onSubmit = this.onSubmit.bind(this); - } + this.state = { value: "" }; + } refs: { [string: string]: any; @@ -24,13 +29,17 @@ // Propagate to external handler this.props.onSubmit(newCake); + + // State didn't for some reason propagate correctly to the input's default value, + // so clearing the input field directly for now + this.refs.cakeName.value = ""; } render() { return ( <form onSubmit={this.onSubmit}> <h3>New cake</h3> - <input ref="cakeName" type="text" defaultValue="" placeholder="Cake name" /> + <input ref="cakeName" type="text" placeholder="Cake name" /> <button type="submit">Add</button> </form> );
ad3439929a19b1c41978d4de6f74fb442313fb07
src/mockDOMSource.ts
src/mockDOMSource.ts
import {Observable} from 'rx'; export interface DOMSelection { observable: Observable<any>; events: (eventType: string) => Observable<any>; } export class MockedDOMSelection { public observable: Observable<any>; constructor(private mockConfigEventTypes: Object, mockConfigObservable?: Observable<any>) { if (mockConfigObservable) { this.observable = mockConfigObservable; } else { this.observable = Observable.empty(); } } public events(eventType: string) { const mockConfigEventTypes = this.mockConfigEventTypes; const keys = Object.keys(mockConfigEventTypes); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === eventType) { return mockConfigEventTypes[key]; } } return Observable.empty(); } } export class MockedDOMSource { constructor(private mockConfig: Object) { } public select(selector: string): DOMSelection { const mockConfig = this.mockConfig; const keys = Object.keys(mockConfig); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === selector) { return new MockedDOMSelection(mockConfig[key], mockConfig['observable']); } } return new MockedDOMSelection({}, mockConfig['observable']); } } export function mockDOMSource(mockConfig: Object): MockedDOMSource { return new MockedDOMSource(mockConfig); }
import {Observable} from 'rx'; export interface DOMSelection { observable: Observable<any>; events: (eventType: string) => Observable<any>; } export class MockedDOMSource { public observable: Observable<any>; constructor(private _mockConfig: Object) { if (_mockConfig['observable']) { this.observable = _mockConfig['observable']; } else { this.observable = Observable.empty(); } } public events(eventType: string) { const mockConfig = this._mockConfig; const keys = Object.keys(mockConfig); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === eventType) { return mockConfig[key]; } } return Observable.empty(); } public select(selector: string): DOMSelection { const mockConfig = this._mockConfig; const keys = Object.keys(mockConfig); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === selector) { return new MockedDOMSource(mockConfig[key]); } } return new MockedDOMSource({}); } } export function mockDOMSource(mockConfig: Object): MockedDOMSource { return new MockedDOMSource(mockConfig); }
Fix some tests/issues with mocDOMSource
Fix some tests/issues with mocDOMSource
TypeScript
mit
cyclejs/cycle-dom,cyclejs/cycle-web,cyclejs/cycle-web,cyclejs/cycle-dom
--- +++ @@ -5,47 +5,41 @@ events: (eventType: string) => Observable<any>; } -export class MockedDOMSelection { +export class MockedDOMSource { public observable: Observable<any>; - constructor(private mockConfigEventTypes: Object, - mockConfigObservable?: Observable<any>) { - if (mockConfigObservable) { - this.observable = mockConfigObservable; + constructor(private _mockConfig: Object) { + if (_mockConfig['observable']) { + this.observable = _mockConfig['observable']; } else { this.observable = Observable.empty(); } } public events(eventType: string) { - const mockConfigEventTypes = this.mockConfigEventTypes; - const keys = Object.keys(mockConfigEventTypes); + const mockConfig = this._mockConfig; + const keys = Object.keys(mockConfig); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === eventType) { - return mockConfigEventTypes[key]; + return mockConfig[key]; } } return Observable.empty(); } -} - -export class MockedDOMSource { - constructor(private mockConfig: Object) { - } public select(selector: string): DOMSelection { - const mockConfig = this.mockConfig; + const mockConfig = this._mockConfig; const keys = Object.keys(mockConfig); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; if (key === selector) { - return new MockedDOMSelection(mockConfig[key], mockConfig['observable']); + return new MockedDOMSource(mockConfig[key]); } } - return new MockedDOMSelection({}, mockConfig['observable']); + return new MockedDOMSource({}); } }
a6c566bd39644ceef66d2e638de62e656cf310db
integration/src/index.tsx
integration/src/index.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Accordion, AccordionItem, AccordionItemHeading, AccordionItemPanel, } from '../../src'; ReactDOM.render( <div id="classic-accordion"> <Accordion> <AccordionItem> <AccordionItemHeading>Heading One</AccordionItemHeading> <AccordionItemPanel> Sunt in reprehenderit cillum ex proident qui culpa fugiat pariatur aliqua nostrud consequat consequat enim quis sit consectetur ad aute ea ex eiusmod id esse culpa et pariatur ad amet pariatur pariatur dolor quis. </AccordionItemPanel> </AccordionItem> <AccordionItem> <AccordionItemHeading>Heading Two</AccordionItemHeading> <AccordionItemPanel> Velit tempor dolore commodo voluptate id do nulla do ut proident cillum ad cillum voluptate deserunt fugiat ut sed cupidatat ut consectetur consequat incididunt sed in culpa do labore ea incididunt ea in eiusmod. </AccordionItemPanel> </AccordionItem> <AccordionItem> <AccordionItemHeading>Heading Three</AccordionItemHeading> <AccordionItemPanel> Lorem ipsum esse occaecat voluptate duis incididunt amet eiusmod sunt commodo sunt enim anim ea culpa ut tempor dolore fugiat exercitation aliquip commodo dolore elit esse est ullamco velit et deserunt. </AccordionItemPanel> </AccordionItem> </Accordion> </div>, document.body.appendChild(document.createElement('div')), );
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Accordion, AccordionItem, AccordionItemHeading, AccordionItemPanel, } from '../../src'; // tslint:disable-next-line no-import-side-effect import '../../src/css/minimal-example.css'; ReactDOM.render( <div id="classic-accordion"> <Accordion> <AccordionItem> <AccordionItemHeading>Heading One</AccordionItemHeading> <AccordionItemPanel> Sunt in reprehenderit cillum ex proident qui culpa fugiat pariatur aliqua nostrud consequat consequat enim quis sit consectetur ad aute ea ex eiusmod id esse culpa et pariatur ad amet pariatur pariatur dolor quis. </AccordionItemPanel> </AccordionItem> <AccordionItem> <AccordionItemHeading>Heading Two</AccordionItemHeading> <AccordionItemPanel> Velit tempor dolore commodo voluptate id do nulla do ut proident cillum ad cillum voluptate deserunt fugiat ut sed cupidatat ut consectetur consequat incididunt sed in culpa do labore ea incididunt ea in eiusmod. </AccordionItemPanel> </AccordionItem> <AccordionItem> <AccordionItemHeading>Heading Three</AccordionItemHeading> <AccordionItemPanel> Lorem ipsum esse occaecat voluptate duis incididunt amet eiusmod sunt commodo sunt enim anim ea culpa ut tempor dolore fugiat exercitation aliquip commodo dolore elit esse est ullamco velit et deserunt. </AccordionItemPanel> </AccordionItem> </Accordion> </div>, document.body.appendChild(document.createElement('div')), );
Add minimal styles to integration tests
Add minimal styles to integration tests
TypeScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
--- +++ @@ -6,6 +6,9 @@ AccordionItemHeading, AccordionItemPanel, } from '../../src'; + +// tslint:disable-next-line no-import-side-effect +import '../../src/css/minimal-example.css'; ReactDOM.render( <div id="classic-accordion">
40a3c1fcd50dd37e97dea316dbc68702858f40b4
src/vs/base/common/numbers.ts
src/vs/base/common/numbers.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 types = require('vs/base/common/types'); export type NumberCallback = (index: number) => void; export function count(to: number, callback: NumberCallback): void; export function count(from: number, to: number, callback: NumberCallback): void; export function count(fromOrTo: number, toOrCallback?: NumberCallback | number, callback?: NumberCallback): any { let from: number; let to: number; if (types.isNumber(toOrCallback)) { from = fromOrTo; to = <number>toOrCallback; } else { from = 0; to = fromOrTo; callback = <NumberCallback>toOrCallback; } const op = from <= to ? (i: number) => i + 1 : (i: number) => i - 1; const cmp = from <= to ? (a: number, b: number) => a < b : (a: number, b: number) => a > b; for (let i = from; cmp(i, to); i = op(i)) { callback(i); } } export function countToArray(to: number): number[]; export function countToArray(from: number, to: number): number[]; export function countToArray(fromOrTo: number, to?: number): number[] { const result: number[] = []; const fn = (i: number) => result.push(i); if (types.isUndefined(to)) { count(fromOrTo, fn); } else { count(fromOrTo, to, fn); } return result; } export function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } export function rot(index: number, modulo: number): number { return (modulo + (index % modulo)) % modulo; }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; export function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } export function rot(index: number, modulo: number): number { return (modulo + (index % modulo)) % modulo; }
Remove unused count and countToArray functions
Remove unused count and countToArray functions
TypeScript
mit
mjbvz/vscode,DustinCampbell/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,microlv/vscode,stringham/vscode,mjbvz/vscode,the-ress/vscode,mjbvz/vscode,0xmohit/vscode,microsoft/vscode,eamodio/vscode,0xmohit/vscode,eamodio/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,joaomoreno/vscode,Zalastax/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,DustinCampbell/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,veeramarni/vscode,eamodio/vscode,DustinCampbell/vscode,cleidigh/vscode,Zalastax/vscode,Zalastax/vscode,microlv/vscode,Microsoft/vscode,cleidigh/vscode,mjbvz/vscode,Microsoft/vscode,landonepps/vscode,Microsoft/vscode,eamodio/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,the-ress/vscode,Zalastax/vscode,Zalastax/vscode,landonepps/vscode,veeramarni/vscode,hoovercj/vscode,veeramarni/vscode,stringham/vscode,microlv/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,landonepps/vscode,joaomoreno/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,Microsoft/vscode,rishii7/vscode,stringham/vscode,Zalastax/vscode,the-ress/vscode,veeramarni/vscode,veeramarni/vscode,microlv/vscode,stringham/vscode,joaomoreno/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,cleidigh/vscode,microlv/vscode,veeramarni/vscode,mjbvz/vscode,microlv/vscode,mjbvz/vscode,rishii7/vscode,0xmohit/vscode,mjbvz/vscode,cleidigh/vscode,cleidigh/vscode,joaomoreno/vscode,Microsoft/vscode,DustinCampbell/vscode,stringham/vscode,rishii7/vscode,eamodio/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,rishii7/vscode,microlv/vscode,0xmohit/vscode,DustinCampbell/vscode,stringham/vscode,the-ress/vscode,microsoft/vscode,0xmohit/vscode,stringham/vscode,eamodio/vscode,mjbvz/vscode,Microsoft/vscode,the-ress/vscode,mjbvz/vscode,hoovercj/vscode,hoovercj/vscode,microsoft/vscode,joaomoreno/vscode,Zalastax/vscode,Zalastax/vscode,veeramarni/vscode,DustinCampbell/vscode,microlv/vscode,Zalastax/vscode,mjbvz/vscode,microsoft/vscode,microsoft/vscode,landonepps/vscode,stringham/vscode,stringham/vscode,mjbvz/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,DustinCampbell/vscode,cleidigh/vscode,joaomoreno/vscode,eamodio/vscode,veeramarni/vscode,hoovercj/vscode,joaomoreno/vscode,rishii7/vscode,Microsoft/vscode,rishii7/vscode,stringham/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,hoovercj/vscode,the-ress/vscode,DustinCampbell/vscode,veeramarni/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,0xmohit/vscode,rishii7/vscode,landonepps/vscode,cleidigh/vscode,eamodio/vscode,joaomoreno/vscode,landonepps/vscode,mjbvz/vscode,cleidigh/vscode,DustinCampbell/vscode,the-ress/vscode,landonepps/vscode,cleidigh/vscode,0xmohit/vscode,stringham/vscode,mjbvz/vscode,Microsoft/vscode,Zalastax/vscode,DustinCampbell/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,veeramarni/vscode,0xmohit/vscode,veeramarni/vscode,eamodio/vscode,microsoft/vscode,the-ress/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,Microsoft/vscode,DustinCampbell/vscode,rishii7/vscode,microlv/vscode,Zalastax/vscode,DustinCampbell/vscode,hoovercj/vscode,hoovercj/vscode,joaomoreno/vscode,hoovercj/vscode,0xmohit/vscode,rishii7/vscode,Microsoft/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,veeramarni/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,Zalastax/vscode,veeramarni/vscode,veeramarni/vscode,microlv/vscode,cleidigh/vscode,microsoft/vscode,stringham/vscode,DustinCampbell/vscode,mjbvz/vscode,DustinCampbell/vscode,landonepps/vscode,veeramarni/vscode,the-ress/vscode,0xmohit/vscode,the-ress/vscode,0xmohit/vscode,stringham/vscode,Zalastax/vscode,rishii7/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,the-ress/vscode,eamodio/vscode,microlv/vscode,DustinCampbell/vscode,joaomoreno/vscode,microsoft/vscode,landonepps/vscode,joaomoreno/vscode,hoovercj/vscode,rishii7/vscode,cra0zy/VSCode,cleidigh/vscode,hoovercj/vscode,cleidigh/vscode,veeramarni/vscode,landonepps/vscode,the-ress/vscode,mjbvz/vscode,DustinCampbell/vscode,0xmohit/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,eamodio/vscode,the-ress/vscode,joaomoreno/vscode,Zalastax/vscode,microlv/vscode,veeramarni/vscode,stringham/vscode,stringham/vscode,microlv/vscode,rishii7/vscode,landonepps/vscode,Zalastax/vscode,joaomoreno/vscode,microsoft/vscode,cleidigh/vscode,microsoft/vscode,joaomoreno/vscode,microlv/vscode,microsoft/vscode,landonepps/vscode,DustinCampbell/vscode,stringham/vscode,mjbvz/vscode,0xmohit/vscode,Zalastax/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,the-ress/vscode,the-ress/vscode,eamodio/vscode,cleidigh/vscode,Zalastax/vscode
--- +++ @@ -4,49 +4,6 @@ *--------------------------------------------------------------------------------------------*/ 'use strict'; - -import types = require('vs/base/common/types'); - -export type NumberCallback = (index: number) => void; - -export function count(to: number, callback: NumberCallback): void; -export function count(from: number, to: number, callback: NumberCallback): void; -export function count(fromOrTo: number, toOrCallback?: NumberCallback | number, callback?: NumberCallback): any { - let from: number; - let to: number; - - if (types.isNumber(toOrCallback)) { - from = fromOrTo; - to = <number>toOrCallback; - } else { - from = 0; - to = fromOrTo; - callback = <NumberCallback>toOrCallback; - } - - const op = from <= to ? (i: number) => i + 1 : (i: number) => i - 1; - const cmp = from <= to ? (a: number, b: number) => a < b : (a: number, b: number) => a > b; - - for (let i = from; cmp(i, to); i = op(i)) { - callback(i); - } -} - -export function countToArray(to: number): number[]; -export function countToArray(from: number, to: number): number[]; -export function countToArray(fromOrTo: number, to?: number): number[] { - const result: number[] = []; - const fn = (i: number) => result.push(i); - - if (types.isUndefined(to)) { - count(fromOrTo, fn); - } else { - count(fromOrTo, to, fn); - } - - return result; -} - export function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max);
95eda9688d8b8600311db1f2439710d710973657
demo/src/app/app.component.ts
demo/src/app/app.component.ts
import {Component, ElementRef, Inject} from '@angular/core'; import {PageScrollService, PageScrollInstance} from 'ng2-page-scroll'; import {DOCUMENT} from "@angular/platform-browser"; import {Router, NavigationEnd} from "@angular/router"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private router: Router) { router.events.subscribe((event) => { // see also if (event instanceof NavigationEnd) { this.links.forEach((link, index) => { if (link.route[0] === event.url) { this.currentTabIndex = index; } }); } }); } public currentTabIndex: number = 0; public links = [ { route: ['/'], name: 'Home' }, { route: ['/simple'], name: 'Simple Scrolling' }, { route: ['/nested'], name: 'Nested Scrolling' }, { route: ['/horizontal'], name: 'Horizontal Scrolling' }, { route: ['/translated'], name: 'Transformed Target Scrolling' }]; public tabChange(event: any) { // Select the correct route for that tab let routeObj = this.links[event.index]; if (routeObj && routeObj.route) { this.router.navigate(routeObj.route); } } }
import {Component, ElementRef, Inject} from '@angular/core'; import {PageScrollService, PageScrollInstance} from 'ng2-page-scroll'; import {DOCUMENT} from "@angular/platform-browser"; import {Router, NavigationEnd} from "@angular/router"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private router: Router) { router.events.subscribe((event) => { // see also if (event instanceof NavigationEnd) { this.links.forEach((link, index) => { if (router.isActive(router.createUrlTree(link.route), false)) { this.currentTabIndex = index; } }); } }); } public currentTabIndex: number = 0; public links = [ { route: ['/'], name: 'Home' }, { route: ['/simple'], name: 'Simple Scrolling' }, { route: ['/nested'], name: 'Nested Scrolling' }, { route: ['/horizontal'], name: 'Horizontal Scrolling' }, { route: ['/translated'], name: 'Transformed Target Scrolling' }]; public tabChange(event: any) { // Select the correct route for that tab let routeObj = this.links[event.index]; if (routeObj && routeObj.route) { this.router.navigate(routeObj.route); } } }
Fix route detection for tab group
Fix route detection for tab group
TypeScript
mit
Nolanus/ng2-page-scroll,Nolanus/ng2-page-scroll,Nolanus/ng2-page-scroll
--- +++ @@ -15,7 +15,7 @@ // see also if (event instanceof NavigationEnd) { this.links.forEach((link, index) => { - if (link.route[0] === event.url) { + if (router.isActive(router.createUrlTree(link.route), false)) { this.currentTabIndex = index; } });
218d124d7bac09d9b1c8bc2b88c91c79763b3ab7
src/components/common/Header.tsx
src/components/common/Header.tsx
import * as React from 'react'; import {NavLink} from 'react-router-dom' export const Header = () => ( <nav> <NavLink to="/" activeClassName="active">Home</NavLink> {" | "} <NavLink to="about" activeClassName="active">About</NavLink> </nav> );
import * as React from 'react'; import {NavLink} from 'react-router-dom' export const Header = () => ( <nav> <NavLink exact to="/" activeClassName="active">Home</NavLink> {" | "} <NavLink to="/about" activeClassName="active">About</NavLink> </nav> );
Update path to match the routes
Update path to match the routes
TypeScript
mit
chunliu/typescript-react-hot-reload,chunliu/typescript-react-hot-reload,chunliu/typescript-react-hot-reload
--- +++ @@ -3,8 +3,8 @@ export const Header = () => ( <nav> - <NavLink to="/" activeClassName="active">Home</NavLink> + <NavLink exact to="/" activeClassName="active">Home</NavLink> {" | "} - <NavLink to="about" activeClassName="active">About</NavLink> + <NavLink to="/about" activeClassName="active">About</NavLink> </nav> );
31f5757421fba3e93d01fe101bb11a15ba355f91
src/site/app/lib/components/pioneer-tree-node/pioneer-tree-node.component.ts
src/site/app/lib/components/pioneer-tree-node/pioneer-tree-node.component.ts
import { Component, Input, TemplateRef } from '@angular/core'; import { PioneerTreeComponent } from '../pioneer-tree/pioneer-tree.component' import { IPioneerTreeExpandedNode } from "../../models/pioneer-tree-expanded-node.model" import { PioneerTreeService } from "../../services/pioneer-tree.service" @Component({ selector: '[pioneer-tree-node],[pt-node]', template: ` <div class="pioneer-tree-node" (click)="onClicked()" [ngClass]="{ 'pt-node-selected': this.treeService.currentSlectedNodeId === this.node.pioneerTreeNode.getId() }"> <ng-container [ngTemplateOutlet]="nodeTemplate" [ngOutletContext]="{ $implicit: node }"> </ng-container> <div class="pioneer-tree-repeater"> <ng-container [ngTemplateOutlet]="repeaterTemplate" [ngOutletContext]="{ $implicit: node }"> </ng-container> </div> </div> ` }) export class PioneerTreeNodeComponent { @Input() node: IPioneerTreeExpandedNode; @Input() nodeTemplate: TemplateRef<any>; @Input() repeaterTemplate: TemplateRef<any>; constructor(private treeService: PioneerTreeService) { } onClicked() { this.treeService.currentSlectedNodeId = this.node.pioneerTreeNode.getId(); } }
import { Component, Input, TemplateRef } from '@angular/core'; import { PioneerTreeComponent } from '../pioneer-tree/pioneer-tree.component' import { IPioneerTreeExpandedNode } from "../../models/pioneer-tree-expanded-node.model" import { PioneerTreeService } from "../../services/pioneer-tree.service" @Component({ selector: '[pioneer-tree-node],[pt-node]', template: ` <div class="pioneer-tree-node" (click)="onClicked()"> <div class="pioneer-tree-node-content" [ngClass]="{ 'pt-node-selected': this.treeService.currentSlectedNodeId === this.node.pioneerTreeNode.getId() }"> <ng-container [ngTemplateOutlet]="nodeTemplate" [ngOutletContext]="{ $implicit: node }"> </ng-container> </div> <div class="pioneer-tree-repeater"> <ng-container [ngTemplateOutlet]="repeaterTemplate" [ngOutletContext]="{ $implicit: node }"> </ng-container> </div> </div> ` }) export class PioneerTreeNodeComponent { @Input() node: IPioneerTreeExpandedNode; @Input() nodeTemplate: TemplateRef<any>; @Input() repeaterTemplate: TemplateRef<any>; constructor(private treeService: PioneerTreeService) { } onClicked() { this.treeService.currentSlectedNodeId = this.node.pioneerTreeNode.getId(); } }
Add parent container to template in node
Add parent container to template in node
TypeScript
mit
PioneerCode/pioneer-tree,PioneerCode/pioneer-tree,PioneerCode/pioneer-tree
--- +++ @@ -8,12 +8,14 @@ selector: '[pioneer-tree-node],[pt-node]', template: ` <div class="pioneer-tree-node" - (click)="onClicked()" - [ngClass]="{ - 'pt-node-selected': this.treeService.currentSlectedNodeId === this.node.pioneerTreeNode.getId() - }"> - <ng-container [ngTemplateOutlet]="nodeTemplate" [ngOutletContext]="{ $implicit: node }"> - </ng-container> + (click)="onClicked()"> + <div class="pioneer-tree-node-content" + [ngClass]="{ + 'pt-node-selected': this.treeService.currentSlectedNodeId === this.node.pioneerTreeNode.getId() + }"> + <ng-container [ngTemplateOutlet]="nodeTemplate" [ngOutletContext]="{ $implicit: node }"> + </ng-container> + </div> <div class="pioneer-tree-repeater"> <ng-container [ngTemplateOutlet]="repeaterTemplate" [ngOutletContext]="{ $implicit: node }"> </ng-container>
52a2c41c3f2efbedd99f384d419db7f2de01d199
src/DailySoccerSolution/DailySoccerMobile/Scripts/tickets/starter.ticket.services.ts
src/DailySoccerSolution/DailySoccerMobile/Scripts/tickets/starter.ticket.services.ts
module starter.ticket { 'use strict'; export class TicketServices implements ITicketService { static $inject = ['starter.shared.QueryRemoteDataService']; constructor(private queryRemoteSvc: starter.shared.QueryRemoteDataService) { } public BuyTicket(req: BuyTicketRequest): ng.IPromise<BuyTicketRespond> { var requestUrl = "BuyTicket/BuyTicket?userId=" + req.UserId + "&amount=" + req.Amount; return this.queryRemoteSvc.RemoteQuery<BuyTicketRespond>(requestUrl); }; } angular .module('starter.ticket') .service('starter.ticket.TicketServices', TicketServices); }
module starter.ticket { 'use strict'; export class TicketServices implements ITicketService { static $inject = ['starter.shared.QueryRemoteDataService']; constructor(private queryRemoteSvc: starter.shared.QueryRemoteDataService) { } public BuyTicket(req: BuyTicketRequest): ng.IPromise<BuyTicketRespond> { var requestUrl = "BuyTicket/BuyTicket?userId=" + req.UserId + "&amount=" + req.Amount; return this.queryRemoteSvc.RemoteQuery<BuyTicketRespond>(requestUrl); }; } export class BuyTicketManagerService { } angular .module('starter.ticket') .service('starter.ticket.TicketServices', TicketServices) .service('starter.ticket.BuyTicketManagerService', BuyTicketManagerService); }
Add BuyTicketManagerService for validate buy ticket.
Add BuyTicketManagerService for validate buy ticket. Signed-off-by: Sakul Jaruthanaset <[email protected]>
TypeScript
mit
tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer,tlaothong/xdailysoccer
--- +++ @@ -13,7 +13,12 @@ }; } + export class BuyTicketManagerService { + + } + angular .module('starter.ticket') - .service('starter.ticket.TicketServices', TicketServices); + .service('starter.ticket.TicketServices', TicketServices) + .service('starter.ticket.BuyTicketManagerService', BuyTicketManagerService); }
7365c96f0479658d9c66d0877df9622f1838dc28
helpers/object.ts
helpers/object.ts
export default class HelperObject { public static clone<T extends any>(obj: T): T { if (obj === undefined || typeof (obj) !== "object") { return obj; // any non-objects are passed by value, not reference } if (obj instanceof Date) { return <any>new Date(obj.getTime()); } const temp: any = new obj.constructor(); Object.keys(obj).forEach(key => { temp[key] = HelperObject.clone(obj[key]); }); return temp; } public static merge<T>(from: T, to: T, reverseArrays = false): T { for (const i in from) { if (from[i] instanceof Array && to[i] instanceof Array) { to[i] = reverseArrays ? (<any>from[i]).concat(to[i]) : (<any>to[i]).concat(from[i]); } else { to[i] = from[i]; } } return to; } }
export default class HelperObject { public static clone<T extends any>(obj: T): T { // We need to check strict null // tslint:disable-next-line if (obj === undefined || obj === null || typeof (obj) !== "object") { return obj; // any non-objects are passed by value, not reference } if (obj instanceof Date) { return <any>new Date(obj.getTime()); } const temp: any = new obj.constructor(); Object.keys(obj).forEach(key => { temp[key] = HelperObject.clone(obj[key]); }); return temp; } public static merge<T>(from: T, to: T, reverseArrays = false): T { for (const i in from) { if (from[i] instanceof Array && to[i] instanceof Array) { to[i] = reverseArrays ? (<any>from[i]).concat(to[i]) : (<any>to[i]).concat(from[i]); } else { to[i] = from[i]; } } return to; } public static extend<T extends any>(obj: T, template: any): T { Object.keys(template).filter(k => obj[k] === undefined).forEach(k => { obj[k] = this.clone(template[k]); }); return obj; } }
Implement HelperObject.extend() and fix a bug in .clone()
Implement HelperObject.extend() and fix a bug in .clone()
TypeScript
mit
crossroads-education/eta,crossroads-education/eta
--- +++ @@ -1,6 +1,8 @@ export default class HelperObject { public static clone<T extends any>(obj: T): T { - if (obj === undefined || typeof (obj) !== "object") { + // We need to check strict null + // tslint:disable-next-line + if (obj === undefined || obj === null || typeof (obj) !== "object") { return obj; // any non-objects are passed by value, not reference } if (obj instanceof Date) { @@ -23,4 +25,11 @@ } return to; } + + public static extend<T extends any>(obj: T, template: any): T { + Object.keys(template).filter(k => obj[k] === undefined).forEach(k => { + obj[k] = this.clone(template[k]); + }); + return obj; + } }
a465e6423c198f3bf84996e6f76a3b01ca18c454
angular/examples/Code/Router/Nested_Routes/src/app/products/product.component.ts
angular/examples/Code/Router/Nested_Routes/src/app/products/product.component.ts
import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {Subscription} from 'rxjs'; import {ProductsService} from './products.service'; @Component({ template: ` <h1>{{product.name}}</h1> ` }) export class ProductComponent implements OnInit, OnDestroy { product = {}; subscription: Subscription; constructor( private productsService: ProductsService, private route: ActivatedRoute ) {} ngOnInit() { console.log('init'); this.subscription = this.route.params.subscribe((params) => { this.product = this.productsService.getProduct(Number(params['id'])); }); } ngOnDestroy() { console.log('destroy'); this.subscription.unsubscribe(); } }
import {Component, OnInit, OnDestroy} from '@angular/core'; import {ActivatedRoute, ParamMap} from '@angular/router'; import {Subscription} from 'rxjs'; import {ProductsService} from './products.service'; @Component({ template: ` <h1>{{product.name}}</h1> ` }) export class ProductComponent implements OnInit, OnDestroy { product = {}; subscription: Subscription; constructor( private productsService: ProductsService, private route: ActivatedRoute ) {} ngOnInit() { console.log('init'); // unsubscribe is not strictly needed with ActivatedRoute this.subscription = this.route.paramMap .subscribe((params: ParamMap) => { this.product = this.productsService.getProduct(Number(params.get('id'))); }); } ngOnDestroy() { console.log('destroy'); this.subscription.unsubscribe(); } }
Use paramMap of ActivatedRoute instead of params
Use paramMap of ActivatedRoute instead of params
TypeScript
mit
jsperts/workshop_unterlagen,jsperts/workshop_unterlagen,jsperts/workshop_unterlagen
--- +++ @@ -1,5 +1,5 @@ import {Component, OnInit, OnDestroy} from '@angular/core'; -import {ActivatedRoute} from '@angular/router'; +import {ActivatedRoute, ParamMap} from '@angular/router'; import {Subscription} from 'rxjs'; import {ProductsService} from './products.service'; @@ -20,9 +20,11 @@ ngOnInit() { console.log('init'); - this.subscription = this.route.params.subscribe((params) => { - this.product = this.productsService.getProduct(Number(params['id'])); - }); + // unsubscribe is not strictly needed with ActivatedRoute + this.subscription = this.route.paramMap + .subscribe((params: ParamMap) => { + this.product = this.productsService.getProduct(Number(params.get('id'))); + }); } ngOnDestroy() {
904f6728ea44e62fe04c1871a98cb3b8ac9ad7fa
src/queue.ts
src/queue.ts
class Queue { private _running = false; private _queue: Function[] = []; public push(f: Function) { this._queue.push(f); if (!this._running) { // if nothing is running, then start the engines! this._next(); } return this; // for chaining fun! } private _next() { this._running = false; // get the first element off the queue let action = this._queue.shift(); if (action) { this._running = true; new Promise((resolve, reject) => action(resolve)).then(this._next.bind(this)); } } } export default Queue;
class Queue { private _running = false; private _queue: Function[] = []; public push(f: Function) { this._queue.push(f); if (!this._running) { // if nothing is running, then start the engines! this._next(); } return this; // for chaining fun! } private _next() { this._running = false; // get the first element off the queue let action = this._queue.shift(); if (action) { this._running = true; action(this._next.bind(this)); } } } export default Queue;
Use old style callback instead of Promise to a avoid timeout error
Use old style callback instead of Promise to a avoid timeout error
TypeScript
apache-2.0
KamiKillertO/vscode-colorize,KamiKillertO/vscode-colorize
--- +++ @@ -20,7 +20,7 @@ let action = this._queue.shift(); if (action) { this._running = true; - new Promise((resolve, reject) => action(resolve)).then(this._next.bind(this)); + action(this._next.bind(this)); } } }
54499c121604ce0fbf39f72a6ff3c5a688e5ae28
web-server/src/main.ts
web-server/src/main.ts
/// <reference path="../typings/node/node.d.ts"/> /// <reference path="../typings/express/express.d.ts"/> var express = require('express'); var app = express(); var router = express.Router(); var bodyParser = require('body-parser'); router.get('/hello', function(req, res, next) { if (!req.name) { res.json({ status: "error", msg: "Need name field in request body" }); return; } res.json({ status: "ok", msg: "Hello " + req.name + "." }); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(router); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
/// <reference path="../typings/node/node.d.ts"/> /// <reference path="../typings/express/express.d.ts"/> var express = require('express'); var app = express(); var router = express.Router(); var bodyParser = require('body-parser'); router.get('/hello', function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); if (!req.name) { res.json({ status: "error", msg: "Need name field in request body" }); return; } res.json({ status: "ok", msg: "Hello " + req.name + "." }); }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(router); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
Allow requests from other servers.
Allow requests from other servers. (Access-Control-Allow-Origin)
TypeScript
mit
2DKot/AI_Contester,2DKot/AI_Contester,2DKot/AI_Contester,2DKot/AI_Contester
--- +++ @@ -7,6 +7,8 @@ var bodyParser = require('body-parser'); router.get('/hello', function(req, res, next) { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Headers', 'origin, content-type, accept'); if (!req.name) { res.json({ status: "error",
5b4b02c25e2f9e4f4ce8c3bcc9dbd2ff32cceb0c
app/src/ui/popuppy.tsx
app/src/ui/popuppy.tsx
import * as React from 'react' /** * A terrible, horrible, no good, very bad component for presenting modal * popups. */ export default class Popuppy extends React.Component<any, any> { public render() { const style: React.CSSProperties = { display: 'block', zIndex: 99, width: '50%', height: '50%', margin: 'auto', backgroundColor: 'rgb(255, 210, 210)', position: 'absolute' } return ( <div style={style}> <div><strong><em>🔥 This is fine 🔥</em></strong></div> <div>&nbsp;</div> {this.props.children} </div> ) } }
import * as React from 'react' /** * A terrible, horrible, no good, very bad component for presenting modal * popups. */ export default class Popuppy extends React.Component<any, any> { public render() { const style: React.CSSProperties = { display: 'flex', flexDirection: 'column', zIndex: 99, width: '50%', height: '50%', margin: 'auto', backgroundColor: 'rgb(255, 210, 210)', position: 'absolute' } return ( <div style={style}> <div><strong><em>🔥 This is fine 🔥</em></strong></div> <div>&nbsp;</div> {this.props.children} </div> ) } }
Fix flexbox layouts in the popup
Fix flexbox layouts in the popup
TypeScript
mit
say25/desktop,shiftkey/desktop,say25/desktop,hjobrien/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,shiftkey/desktop,BugTesterTest/desktops,j-f1/forked-desktop,say25/desktop,desktop/desktop,hjobrien/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,hjobrien/desktop,j-f1/forked-desktop,BugTesterTest/desktops,kactus-io/kactus,artivilla/desktop,gengjiawen/desktop,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,gengjiawen/desktop,say25/desktop,BugTesterTest/desktops,desktop/desktop,desktop/desktop,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,artivilla/desktop
--- +++ @@ -7,7 +7,8 @@ export default class Popuppy extends React.Component<any, any> { public render() { const style: React.CSSProperties = { - display: 'block', + display: 'flex', + flexDirection: 'column', zIndex: 99, width: '50%', height: '50%',
ef22e10e7a705b1595b838b6171be6b105f9a135
app/src/ui/discard-changes/index.tsx
app/src/ui/discard-changes/index.tsx
import * as React from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { WorkingDirectoryFileChange } from '../../models/status' import { Form } from '../lib/form' import { Button } from '../lib/button' interface IDiscardChangesProps { readonly repository: Repository readonly dispatcher: Dispatcher readonly files: ReadonlyArray<WorkingDirectoryFileChange> } /** A component to confirm and then discard changes. */ export class DiscardChanges extends React.Component<IDiscardChangesProps, void> { public render() { const paths = this.props.files.map(f => f.path).join(', ') return ( <Form onSubmit={this.cancel}> <div>Confirm Discard Changes</div> <div>Are you sure you want to discard all changes to {paths}?</div> <Button type='submit'>Cancel</Button> <Button onClick={this.discard}>Discard Changes</Button> </Form> ) } private cancel = () => { this.props.dispatcher.closePopup() } private discard = () => { this.props.dispatcher.discardChanges(this.props.repository, this.props.files) this.props.dispatcher.closePopup() } }
import * as React from 'react' import { Repository } from '../../models/repository' import { Dispatcher } from '../../lib/dispatcher' import { WorkingDirectoryFileChange } from '../../models/status' import { Form } from '../lib/form' import { Button } from '../lib/button' interface IDiscardChangesProps { readonly repository: Repository readonly dispatcher: Dispatcher readonly files: ReadonlyArray<WorkingDirectoryFileChange> } /** A component to confirm and then discard changes. */ export class DiscardChanges extends React.Component<IDiscardChangesProps, void> { public render() { const paths = this.props.files.map(f => f.path).join(', ') return ( <Form onSubmit={this.cancel}> <div>{ __DARWIN__ ? 'Confirm Discard Changes' : 'Confirm discard changes'}</div> <div>Are you sure you want to discard all changes to {paths}?</div> <Button type='submit'>Cancel</Button> <Button onClick={this.discard}>{__DARWIN__ ? 'Discard Changes' : 'Discard changes'}</Button> </Form> ) } private cancel = () => { this.props.dispatcher.closePopup() } private discard = () => { this.props.dispatcher.discardChanges(this.props.repository, this.props.files) this.props.dispatcher.closePopup() } }
Fix sentence casing for non darwin platforms in discard popup
Fix sentence casing for non darwin platforms in discard popup
TypeScript
mit
j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,hjobrien/desktop,hjobrien/desktop,shiftkey/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,BugTesterTest/desktops,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,desktop/desktop,BugTesterTest/desktops,gengjiawen/desktop,BugTesterTest/desktops,hjobrien/desktop,BugTesterTest/desktops,hjobrien/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,desktop/desktop,gengjiawen/desktop,shiftkey/desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,say25/desktop,kactus-io/kactus,gengjiawen/desktop,artivilla/desktop,gengjiawen/desktop,kactus-io/kactus,say25/desktop
--- +++ @@ -18,11 +18,11 @@ const paths = this.props.files.map(f => f.path).join(', ') return ( <Form onSubmit={this.cancel}> - <div>Confirm Discard Changes</div> + <div>{ __DARWIN__ ? 'Confirm Discard Changes' : 'Confirm discard changes'}</div> <div>Are you sure you want to discard all changes to {paths}?</div> <Button type='submit'>Cancel</Button> - <Button onClick={this.discard}>Discard Changes</Button> + <Button onClick={this.discard}>{__DARWIN__ ? 'Discard Changes' : 'Discard changes'}</Button> </Form> ) }
ebc92c2125041b0020992b3a00ef76a69536d4f1
packages/angular/cli/commands/new-impl.ts
packages/angular/cli/commands/new-impl.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // tslint:disable:no-global-tslint-disable no-any import { Arguments } from '../models/interface'; import { SchematicCommand } from '../models/schematic-command'; import { Schema as NewCommandSchema } from './new'; export class NewCommand extends SchematicCommand<NewCommandSchema> { public readonly allowMissingWorkspace = true; schematicName = 'ng-new'; async initialize(options: NewCommandSchema & Arguments) { if (options.collection) { this.collectionName = options.collection; } else { this.collectionName = await this.parseCollectionName(options); } return super.initialize(options); } public async run(options: NewCommandSchema & Arguments) { // Register the version of the CLI in the registry. const packageJson = require('../package.json'); const version = packageJson.version; this._workflow.registry.addSmartDefaultProvider('ng-cli-version', () => version); return this.runSchematic({ collectionName: this.collectionName, schematicName: this.schematicName, schematicOptions: options['--'] || [], debug: !!options.debug, dryRun: !!options.dryRun, force: !!options.force, }); } private async parseCollectionName(options: any): Promise<string> { return options.collection || this.getDefaultSchematicCollection(); } }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // tslint:disable:no-global-tslint-disable no-any import { Arguments } from '../models/interface'; import { SchematicCommand } from '../models/schematic-command'; import { Schema as NewCommandSchema } from './new'; export class NewCommand extends SchematicCommand<NewCommandSchema> { public readonly allowMissingWorkspace = true; schematicName = 'ng-new'; async initialize(options: NewCommandSchema & Arguments) { this.collectionName = options.collection || await this.getDefaultSchematicCollection(); return super.initialize(options); } public async run(options: NewCommandSchema & Arguments) { // Register the version of the CLI in the registry. const packageJson = require('../package.json'); const version = packageJson.version; this._workflow.registry.addSmartDefaultProvider('ng-cli-version', () => version); return this.runSchematic({ collectionName: this.collectionName, schematicName: this.schematicName, schematicOptions: options['--'] || [], debug: !!options.debug, dryRun: !!options.dryRun, force: !!options.force, }); } }
Simplify retrival of collection name
refactor(@angular/cli): Simplify retrival of collection name
TypeScript
mit
filipesilva/angular-cli,ocombe/angular-cli,filipesilva/angular-cli,ocombe/angular-cli,hansl/angular-cli,catull/angular-cli,catull/angular-cli,angular/angular-cli,angular/angular-cli,catull/angular-cli,DevIntent/angular-cli,ocombe/angular-cli,manekinekko/angular-cli,DevIntent/angular-cli,DevIntent/angular-cli,beeman/angular-cli,geofffilippi/angular-cli,beeman/angular-cli,DevIntent/angular-cli,clydin/angular-cli,angular/angular-cli,clydin/angular-cli,Brocco/angular-cli,catull/angular-cli,geofffilippi/angular-cli,beeman/angular-cli,clydin/angular-cli,DevIntent/angular-cli,hansl/angular-cli,Brocco/angular-cli,Brocco/angular-cli,geofffilippi/angular-cli,hansl/angular-cli,manekinekko/angular-cli,beeman/angular-cli,manekinekko/angular-cli,geofffilippi/angular-cli,hansl/angular-cli,ocombe/angular-cli,angular/angular-cli,Brocco/angular-cli,clydin/angular-cli,filipesilva/angular-cli,ocombe/angular-cli,Brocco/angular-cli,filipesilva/angular-cli
--- +++ @@ -17,11 +17,7 @@ schematicName = 'ng-new'; async initialize(options: NewCommandSchema & Arguments) { - if (options.collection) { - this.collectionName = options.collection; - } else { - this.collectionName = await this.parseCollectionName(options); - } + this.collectionName = options.collection || await this.getDefaultSchematicCollection(); return super.initialize(options); } @@ -43,7 +39,4 @@ }); } - private async parseCollectionName(options: any): Promise<string> { - return options.collection || this.getDefaultSchematicCollection(); - } }
55f3cf131146034154a964da8ad561e87e1519b0
packages/puppeteer/src/index.ts
packages/puppeteer/src/index.ts
import { Webdriver, ElementNotFoundError, ElementNotVisibleError, } from 'mugshot'; import { Page } from 'puppeteer'; /** * Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer) * to be used with [[WebdriverScreenshotter]]. * * @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md */ export default class PuppeteerAdapter implements Webdriver { constructor(private readonly page: Page) {} getElementRect = async (selector: string) => { const elements = await this.page.$$(selector); if (!elements.length) { throw new ElementNotFoundError(selector); } const rects = await Promise.all( elements.map(async (element) => { const rect = await element.boundingBox(); if (!rect) { throw new ElementNotVisibleError(selector); } return rect; }) ); return rects.length === 1 ? rects[0] : rects; }; setViewportSize = (width: number, height: number) => this.page.setViewport({ width, height, }); takeScreenshot = () => this.page.screenshot(); execute = <R, A extends any[]>(func: (...args: A) => R, ...args: A) => this.page.evaluate( // @ts-expect-error the puppeteer type expects at least 1 argument func, ...args ); }
import { Webdriver } from 'mugshot'; import { Page } from 'puppeteer'; /** * Webdriver adapter over [Puppeteer](https://github.com/puppeteer/puppeteer) * to be used with [[WebdriverScreenshotter]]. * * @see https://github.com/puppeteer/puppeteer/blob/v2.0.0/docs/api.md */ export default class PuppeteerAdapter implements Webdriver { constructor(private readonly page: Page) {} getElementRect = async (selector: string) => { const elements = await this.page.$$(selector); if (!elements.length) { return null; } const rects = await Promise.all( elements.map(async (element) => { const rect = await element.boundingBox(); if (!rect) { return { x: 0, y: 0, width: 0, height: 0 }; } return rect; }) ); return rects.length === 1 ? rects[0] : rects; }; setViewportSize = (width: number, height: number) => this.page.setViewport({ width, height, }); takeScreenshot = () => this.page.screenshot(); execute = <R, A extends any[]>(func: (...args: A) => R, ...args: A) => this.page.evaluate( // @ts-expect-error the puppeteer type expects at least 1 argument func, ...args ); }
Implement the new `Webdriver` interface
feat(puppeteer): Implement the new `Webdriver` interface BREAKING CHANGE: this will bump the min required version of Mugshot.
TypeScript
mit
uberVU/mugshot,uberVU/mugshot
--- +++ @@ -1,8 +1,4 @@ -import { - Webdriver, - ElementNotFoundError, - ElementNotVisibleError, -} from 'mugshot'; +import { Webdriver } from 'mugshot'; import { Page } from 'puppeteer'; /** @@ -18,7 +14,7 @@ const elements = await this.page.$$(selector); if (!elements.length) { - throw new ElementNotFoundError(selector); + return null; } const rects = await Promise.all( @@ -26,7 +22,7 @@ const rect = await element.boundingBox(); if (!rect) { - throw new ElementNotVisibleError(selector); + return { x: 0, y: 0, width: 0, height: 0 }; } return rect;
8fea7f2a5cc43b93d59e06ec2aba5b8ce1c226ae
src/app/budget/budget-item.ts
src/app/budget/budget-item.ts
/* * Interface representing a budget item. It has the sum — some amount spent * or gained, and a description that explains the purpose or source of money */ export interface BudgetItem { sum: number; description: string; }
/* * Interface representing a budget item. It has the sum — some amount spent * or gained, and a description that explains the purpose or source of money */ export class BudgetItem { constructor( public sum: number, public description: string ) { } }
Make BudgetItem a class instead of interface
Make BudgetItem a class instead of interface
TypeScript
mit
bluebirrrrd/ng2-budget,bluebirrrrd/ng2-budget,bluebirrrrd/ng2-budget
--- +++ @@ -2,7 +2,9 @@ * Interface representing a budget item. It has the sum — some amount spent * or gained, and a description that explains the purpose or source of money */ -export interface BudgetItem { - sum: number; - description: string; +export class BudgetItem { + constructor( + public sum: number, + public description: string + ) { } }
f3993f4f8a109e3c6f45bf1257fd8062ae236945
src/index.ts
src/index.ts
import { middleware, Middleware as GenericMiddleware } from './utils/middleware' export { help } from './middlewares/helper' export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any export type CLIParams = string[] export type CommandsModule = ICommandsDictionary | CommandFunction export type Middleware = GenericMiddleware<IMiddlewareArguments> export interface ICLIOptions { [key: string]: number | string | boolean } export interface ICommandsDictionary { [namespace: string]: CommandsModule } export interface IMiddlewareArguments { options: ICLIOptions params: CLIParams definition: CommandsModule namespace: string command: CommandFunction } export interface IInterpreterArguments extends IMiddlewareArguments { middlewares?: Middleware[] } export class CLIError extends Error {} export function cli(definition: CommandsModule) { middleware<IMiddlewareArguments>([])({ command: () => null, definition, namespace: '', options: {}, params: [] }) }
import { middleware, Middleware as GenericMiddleware } from './utils/middleware' export { help } from './middlewares/helper' export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any export type CLIParams = string[] export type CommandsModule = ICommandsDictionary | CommandFunction export type Middleware = GenericMiddleware<IMiddlewareArguments> export interface ICLIOptions { [key: string]: number | string | boolean } export interface ICommandsDictionary { [namespace: string]: CommandsModule } export interface IMiddlewareArguments { options: ICLIOptions params: CLIParams definition: CommandsModule namespace: string command: CommandFunction } export class CLIError extends Error {} export function cli( definition: CommandsModule, middlewares: Middleware[] = [] ) { middleware<IMiddlewareArguments>(middlewares)({ command: () => null, definition, namespace: '', options: {}, params: [] }) }
Add middlewares argument to cli function
Add middlewares argument to cli function
TypeScript
mit
pawelgalazka/microcli,pawelgalazka/microcli
--- +++ @@ -23,14 +23,13 @@ command: CommandFunction } -export interface IInterpreterArguments extends IMiddlewareArguments { - middlewares?: Middleware[] -} - export class CLIError extends Error {} -export function cli(definition: CommandsModule) { - middleware<IMiddlewareArguments>([])({ +export function cli( + definition: CommandsModule, + middlewares: Middleware[] = [] +) { + middleware<IMiddlewareArguments>(middlewares)({ command: () => null, definition, namespace: '',
662939b38abf0d0ad905c6efe84064402297a479
src/plugins/postcss/compile.ts
src/plugins/postcss/compile.ts
import * as emitter from "../../emitter"; import { IFile } from "../../io/file"; import * as autoprefixer from "autoprefixer"; import * as path from "path"; import * as postcss from "postcss"; interface ICustomPostCssOptions { browsers: string[]; } interface IPostCssOptions { map: boolean | { inline: boolean; prev: boolean | string; }; to: string; } export function compile(options: ICustomPostCssOptions) { const prefixer = autoprefixer({ browsers: options.browsers, }); return (files: IFile[]) => { return Promise.all( files.map((file: IFile) => { let cssOptions: IPostCssOptions = { map: false, to: path.basename(file.location), }; if (file.map !== null) { cssOptions.map = { inline: false, prev: file.map, }; } return postcss([prefixer]) .process(file.content, cssOptions) .then(res => { res.warnings().forEach(warn => emitter.warning(warn)); file.content = res.css; if (res.map) { file.map = res.map.toString(); } return file; }).catch((err: Error) => { emitter.error(err); }); }) ); }; }
import * as emitter from "../../emitter"; import { IFile } from "../../io/file"; import * as autoprefixer from "autoprefixer"; import * as path from "path"; import * as postcss from "postcss"; interface ICustomPostCssOptions { browsers: string[]; addVendorPrefixes?: boolean; } interface IPostCssOptions { map: boolean | { inline: boolean; prev: boolean | string; }; to: string; } export function compile(options: ICustomPostCssOptions) { const prefixer = autoprefixer({ browsers: options.browsers, }); return (files: IFile[]) => { return Promise.all( files.map((file: IFile) => { let cssOptions: IPostCssOptions = { map: false, to: path.basename(file.location), }; if (file.map !== null) { cssOptions.map = { inline: false, prev: file.map, }; } let plugins: any[] = []; if (typeof options.addVendorPrefixes === "undefined" || options.addVendorPrefixes) { plugins.push(prefixer); } return postcss(plugins) .process(file.content, cssOptions) .then(res => { res.warnings().forEach(warn => emitter.warning(warn)); file.content = res.css; if (res.map) { file.map = res.map.toString(); } return file; }).catch((err: Error) => { emitter.error(err); }); }) ); }; }
Add new user config to enable/disable prefixes
Add new user config to enable/disable prefixes
TypeScript
mit
marvinhagemeister/kiki,marvinhagemeister/kiki
--- +++ @@ -6,6 +6,7 @@ interface ICustomPostCssOptions { browsers: string[]; + addVendorPrefixes?: boolean; } interface IPostCssOptions { @@ -36,7 +37,14 @@ }; } - return postcss([prefixer]) + let plugins: any[] = []; + + if (typeof options.addVendorPrefixes === "undefined" + || options.addVendorPrefixes) { + plugins.push(prefixer); + } + + return postcss(plugins) .process(file.content, cssOptions) .then(res => { res.warnings().forEach(warn => emitter.warning(warn));
5d9fb91f1f575a70727f1f4623254ff79ea768b7
test/lib/states.ts
test/lib/states.ts
'use strict'; import assert = require('assert'); import GitLabStateHelper from '../../src/lib/states'; const projectId = process.env.GITLAB_TEST_PROJECT; describe('States', function () { describe('constructor()', function () { it('should throw an error with invalid url', function() { assert.throws(() => { new GitLabStateHelper('ftp://foo.bar', '****'); }, /Invalid url!/); }); it('should throw an error without token', function() { assert.throws(() => { new GitLabStateHelper('http://localhost', '****'); }, /Invalid token!/); }); }); describe('getState()', function() { this.timeout(5000); it('should work', projectId ? async function() { const states = await new GitLabStateHelper(); const result1 = await states.getState(projectId, 'develop'); assert.strictEqual(typeof result1.status, 'string'); assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined); const result2 = await states.getState(projectId, 'develop'); assert.strictEqual(result2.status, result1.status); assert.strictEqual(result2.coverage, result1.coverage); } : () => Promise.resolve()); }); });
'use strict'; import assert from 'assert'; import GitLabStateHelper from '../../src/lib/states'; const projectId = process.env.GITLAB_TEST_PROJECT; describe('States', function () { describe('constructor()', function () { it('should throw an error with invalid url', function() { assert.throws(() => { new GitLabStateHelper('ftp://foo.bar', '****'); }, /Invalid url!/); }); it('should throw an error without token', function() { assert.throws(() => { new GitLabStateHelper('http://localhost', '****'); }, /Invalid token!/); }); }); describe('getState()', function() { this.timeout(5000); it('should work', projectId ? async function() { const states = await new GitLabStateHelper(); const result1 = await states.getState(projectId, 'develop'); assert.strictEqual(typeof result1.status, 'string'); assert.ok(typeof result1.coverage === 'string' || result1.coverage === undefined); const result2 = await states.getState(projectId, 'develop'); assert.strictEqual(result2.status, result1.status); assert.strictEqual(result2.coverage, result1.coverage); } : () => Promise.resolve()); }); });
Remove crazy `import require` line
chore(tests): Remove crazy `import require` line
TypeScript
mit
sebbo2002/gitlab-badges,sebbo2002/gitlab-badges
--- +++ @@ -1,6 +1,6 @@ 'use strict'; -import assert = require('assert'); +import assert from 'assert'; import GitLabStateHelper from '../../src/lib/states'; const projectId = process.env.GITLAB_TEST_PROJECT;
6e79159d85663381b5390ebceda9e24c75e1b8c0
src/System/Drawing/Slugifier.ts
src/System/Drawing/Slugifier.ts
import * as Transliteration from "transliteration"; /** * Provides the functionality to generate slugs. */ export class Slugifier { /** * The already generated slugs. */ private slugs: string[] = []; /** * Initializes a new instance of the `Slugifier` class. */ public constructor() { } /** * Gets or sets the already generated slugs. */ protected get Slugs(): string[] { return this.slugs; } protected set Slugs(value: string[]) { this.slugs = value; } /** * Slugifies a text. * * @param text * The text that is to be slugified. */ public CreateSlug(text: string): string { let baseName = this.Slugify(text); let counter = 0; let slug = baseName; while (this.Slugs.includes(slug)) { slug = `${baseName}-${++counter}`; } this.Slugs.push(slug); return slug; } /** * Slugifies a text. * * @param text * The text that is to be slugified. */ protected Slugify(text: string): string { return Transliteration.slugify( text, { lowercase: true, separator: "-", ignore: [] }); } }
import * as Transliteration from "transliteration"; /** * Provides the functionality to generate slugs. */ export class Slugifier { /** * The already generated slugs. */ private slugs: string[] = []; /** * Initializes a new instance of the `Slugifier` class. */ public constructor() { } /** * Gets or sets the already generated slugs. */ protected get Slugs(): string[] { return this.slugs; } protected set Slugs(value: string[]) { this.slugs = value; } /** * Slugifies a text. * * @param text * The text that is to be slugified. */ public CreateSlug(text: string): string { let baseName = this.Slugify(text); let counter = 1; let slug = baseName; while (this.Slugs.includes(slug)) { slug = `${baseName}-${++counter}`; } this.Slugs.push(slug); return slug; } /** * Slugifies a text. * * @param text * The text that is to be slugified. */ protected Slugify(text: string): string { return Transliteration.slugify( text, { lowercase: true, separator: "-", ignore: [] }); } }
Normalize the counter of the slugifier
Normalize the counter of the slugifier
TypeScript
mit
manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter
--- +++ @@ -39,7 +39,7 @@ { let baseName = this.Slugify(text); - let counter = 0; + let counter = 1; let slug = baseName; while (this.Slugs.includes(slug))
9d882dd84f49d5aa8d653bd2392d7067664c717c
server/src/analysis/index.ts
server/src/analysis/index.ts
export { Analysis } from './analysis'; export { ScopedNode } from './Node'; export { Scope } from './scope';
export { Analysis } from './analysis'; export { ScopedNode } from './node'; export { Scope } from './scope';
Fix case sensitivity of 'node' import
Fix case sensitivity of 'node' import
TypeScript
mit
trixnz/vscode-lua,trixnz/vscode-lua
--- +++ @@ -1,3 +1,3 @@ export { Analysis } from './analysis'; -export { ScopedNode } from './Node'; +export { ScopedNode } from './node'; export { Scope } from './scope';
b23fa8418b29bf461fd51f3b925fe872e3e682ba
src/event/eventdispatcher/BaseEventDispatcher.ts
src/event/eventdispatcher/BaseEventDispatcher.ts
import {IEventDispatcher} from "../eventlistenerhelper/IEventDispatcher"; import {IEventListenerCallback} from "../eventlistenerhelper/IEventListenerCallback"; // Type definition for the eventemitter3 declare type EventEmitter = { addListener(type:string, listener:Function, context?:any); removeListener(type:string, listener:Function, context?:any); removeAllListeners(type?:string); emit(type:string, ...args); }; export class BaseEventDispatcher implements IEventDispatcher<string> { private eventEmitter:EventEmitter; public constructor() { this.eventEmitter = new EventEmitter(); } addEventListener(type:string, listener:IEventListenerCallback<string>):void { this.eventEmitter.addListener(type, listener as Function); } removeAllEventListeners(type?:string):void { this.eventEmitter.removeAllListeners(type); } removeEventListener(type:string, listener:any):void { this.eventEmitter.removeListener(type, listener as Function); } dispatchEvent(event:string, data?:any):void { this.eventEmitter.emit(event, data); } }
import {IEventDispatcher} from "../eventlistenerhelper/IEventDispatcher"; import {IEventListenerCallback} from "../eventlistenerhelper/IEventListenerCallback"; import * as EventEmitter from "eventemitter3"; // Type definition for the eventemitter3 declare type EventEmitter = { addListener(type:string, listener:Function, context?:any); removeListener(type:string, listener:Function, context?:any); removeAllListeners(type?:string); emit(type:string, ...args); }; export class BaseEventDispatcher implements IEventDispatcher<string> { private eventEmitter:EventEmitter; public constructor() { this.eventEmitter = new EventEmitter(); } addEventListener(type:string, listener:IEventListenerCallback<string>):void { this.eventEmitter.addListener(type, listener as Function); } removeAllEventListeners(type?:string):void { this.eventEmitter.removeAllListeners(type); } removeEventListener(type:string, listener:any):void { this.eventEmitter.removeListener(type, listener as Function); } dispatchEvent(event:string, data?:any):void { this.eventEmitter.emit(event, data); } }
Fix of the eventemitter3 import.
Fix of the eventemitter3 import.
TypeScript
mit
flashist/fcore,flashist/fcore,flashist/fcore
--- +++ @@ -1,5 +1,7 @@ import {IEventDispatcher} from "../eventlistenerhelper/IEventDispatcher"; import {IEventListenerCallback} from "../eventlistenerhelper/IEventListenerCallback"; + +import * as EventEmitter from "eventemitter3"; // Type definition for the eventemitter3 declare type EventEmitter = {
e4a10e51b3614cc45e30ea9fcd33797390624e11
packages/@orbit/integration-tests/test/support/jsonapi.ts
packages/@orbit/integration-tests/test/support/jsonapi.ts
import Orbit from '@orbit/core'; export function jsonapiResponse(_options: any, body?: any, timeout?: number): Promise<Response> { let options: any; let response: Response; if (typeof _options === 'number') { options = { status: _options }; } else { options = _options || {}; } options.statusText = options.statusText || statusText(options.status); options.headers = options.headers || {}; if (body) { options.headers['Content-Type'] = 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { response = new Orbit.globals.Response(options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type')); if (timeout) { return new Promise((resolve: (response: Response) => void) => { let timer = Orbit.globals.setTimeout(() => { Orbit.globals.clearTimeout(timer); resolve(response); }, timeout); }); } else { return Promise.resolve(response); } } function statusText(code: number): string { switch (code) { case 200: return 'OK'; case 201: return 'Created'; case 204: return 'No Content'; case 422: return 'Unprocessable Entity'; } }
import Orbit from '@orbit/core'; export function jsonapiResponse(_options: any, body?: any, timeout?: number): Promise<Response> { let options: any; let response: Response; if (typeof _options === 'number') { options = { status: _options }; } else { options = _options || {}; } options.statusText = options.statusText || statusText(options.status); options.headers = options.headers || {}; if (body) { options.headers['Content-Type'] = 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { response = new Orbit.globals.Response(null, options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type')); if (timeout) { return new Promise((resolve: (response: Response) => void) => { let timer = Orbit.globals.setTimeout(() => { Orbit.globals.clearTimeout(timer); resolve(response); }, timeout); }); } else { return Promise.resolve(response); } } function statusText(code: number): string { switch (code) { case 200: return 'OK'; case 201: return 'Created'; case 204: return 'No Content'; case 422: return 'Unprocessable Entity'; } }
Fix usage of Response in integration tests
Fix usage of Response in integration tests
TypeScript
mit
orbitjs/orbit.js,orbitjs/orbit.js,orbitjs/orbit-core
--- +++ @@ -16,7 +16,7 @@ options.headers['Content-Type'] = 'application/vnd.api+json'; response = new Orbit.globals.Response(JSON.stringify(body), options); } else { - response = new Orbit.globals.Response(options); + response = new Orbit.globals.Response(null, options); } // console.log('jsonapiResponse', body, options, response.headers.get('Content-Type'));
bec2f7b794e722bbaf66735adc94d9b15ada8ba2
tools/env/base.ts
tools/env/base.ts
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.11.0', RELEASEVERSION: '0.11.0' }; export = BaseConfig;
import { EnvConfig } from './env-config.interface'; const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.12.0', RELEASEVERSION: '0.12.0' }; export = BaseConfig;
Update release version to 0.12.0.
Update release version to 0.12.0.
TypeScript
mit
nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website,nie-ine/raeber-website
--- +++ @@ -3,8 +3,8 @@ const BaseConfig: EnvConfig = { // Sample API url API: 'https://demo.com', - RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.11.0', - RELEASEVERSION: '0.11.0' + RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.12.0', + RELEASEVERSION: '0.12.0' }; export = BaseConfig;
6fd8aedc4e16f0503303df5c0e8ca85a49c9ace2
src/js/View/Ui/AppLoading.tsx
src/js/View/Ui/AppLoading.tsx
import * as React from 'react'; import { Loader, CenteredBox } from 'View/Ui/Index'; interface IAppLoadingProps { show: boolean; }; const AppLoading: React.SFC<IAppLoadingProps> = ({ show }) => ( <div className={'app__loading' + (show ? ' app__loading--show' : '')}> <CenteredBox> <Loader size="medium" default /> </CenteredBox> </div> ); export default AppLoading;
import * as React from 'react'; import { Loader, CenteredBox } from 'View/Ui/Index'; interface IAppLoadingProps { show: boolean; }; const AppLoading: React.SFC<IAppLoadingProps> = ({ show }) => ( <div className={'app__loading app-drag' + (show ? ' app__loading--show' : '')}> <CenteredBox> <Loader size="medium" default /> </CenteredBox> </div> ); export default AppLoading;
Allow dragging on the loading screen
Allow dragging on the loading screen
TypeScript
mit
harksys/HawkEye,harksys/HawkEye,harksys/HawkEye
--- +++ @@ -12,7 +12,7 @@ const AppLoading: React.SFC<IAppLoadingProps> = ({ show }) => ( - <div className={'app__loading' + <div className={'app__loading app-drag' + (show ? ' app__loading--show' : '')}>
db11b0b9e55d7a4cea578428c0f243175ec5cdcf
src/index.ts
src/index.ts
import 'babel-polyfill'; //This will be replaced based on your babel-env config import { run } from '@cycle/run'; import { makeDOMDriver } from '@cycle/dom'; import { timeDriver } from '@cycle/time'; import onionify from 'cycle-onionify'; import storageify from 'cycle-storageify'; import storageDriver from '@cycle/storage'; import { Component } from './interfaces'; import App from './components/app'; const main: Component = App; const wrappedMain = onionify( storageify(main, { key: 'meeting-price-calculator' }) ); const drivers: any = { DOM: makeDOMDriver('#app'), Time: timeDriver, storage: storageDriver }; run(wrappedMain, drivers);
import 'babel-polyfill'; //This will be replaced based on your babel-env config import { run } from '@cycle/run'; import { makeDOMDriver } from '@cycle/dom'; import { timeDriver } from '@cycle/time'; import onionify from 'cycle-onionify'; import storageify from 'cycle-storageify'; import storageDriver from '@cycle/storage'; import { Component } from './interfaces'; import App from './components/app'; const main: Component = App; const wrappedMain = onionify(storageify(main, { key: 'mpc-state' })); const drivers: any = { DOM: makeDOMDriver('#app'), Time: timeDriver, storage: storageDriver }; run(wrappedMain, drivers);
Change the local storage key in order to not break for recurring users
Change the local storage key in order to not break for recurring users
TypeScript
mit
olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator,olpeh/meeting-price-calculator
--- +++ @@ -12,9 +12,7 @@ const main: Component = App; -const wrappedMain = onionify( - storageify(main, { key: 'meeting-price-calculator' }) -); +const wrappedMain = onionify(storageify(main, { key: 'mpc-state' })); const drivers: any = { DOM: makeDOMDriver('#app'),
776f278cfae3d7c2c0c8a3eaf4a0248ab0778adf
src/data/Data.ts
src/data/Data.ts
import Query from '../query/Query' import { NormalizedData } from './Contract' import Normalizer from './Normalizer' import Attacher from './Attacher' import Builder from './Builder' import Incrementer from './Incrementer' export default class Data { /** * Normalize the data. */ static normalize (data: any, Query: Query): NormalizedData { const normalizedData = Normalizer.normalize(data, Query) const attachedData = Attacher.attach(normalizedData, Query) return Incrementer.increment(attachedData, Query) } /** * Fill missing records with default value based on model schema. */ static fillAll (data: NormalizedData, Query: Query): NormalizedData { return Builder.build(data, Query) } }
import Query from '../query/Query' import { NormalizedData } from './Contract' import Normalizer from './Normalizer' import Attacher from './Attacher' import Builder from './Builder' import Incrementer from './Incrementer' export default class Data { /** * Normalize the data. */ static normalize (data: any, query: Query): NormalizedData { const normalizedData = Normalizer.normalize(data, query) const attachedData = Attacher.attach(normalizedData, query) return Incrementer.increment(attachedData, query) } /** * Fill missing records with default value based on model schema. */ static fillAll (data: NormalizedData, query: Query): NormalizedData { return Builder.build(data, query) } }
Fix some styling in the data class
Fix some styling in the data class
TypeScript
mit
revolver-app/vuex-orm,revolver-app/vuex-orm
--- +++ @@ -9,18 +9,18 @@ /** * Normalize the data. */ - static normalize (data: any, Query: Query): NormalizedData { - const normalizedData = Normalizer.normalize(data, Query) + static normalize (data: any, query: Query): NormalizedData { + const normalizedData = Normalizer.normalize(data, query) - const attachedData = Attacher.attach(normalizedData, Query) + const attachedData = Attacher.attach(normalizedData, query) - return Incrementer.increment(attachedData, Query) + return Incrementer.increment(attachedData, query) } /** * Fill missing records with default value based on model schema. */ - static fillAll (data: NormalizedData, Query: Query): NormalizedData { - return Builder.build(data, Query) + static fillAll (data: NormalizedData, query: Query): NormalizedData { + return Builder.build(data, query) } }
770b1b3dbe52ae8cf5593487621e1ca8662efd9d
src/rimu/main.ts
src/rimu/main.ts
/* This is the main module, it exports the 'render' API. The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm) formatted libraries. */ import * as Api from './api' import * as Options from './options' /* The single public API which translates Rimu Markup to HTML: render(source [, options]) */ export function render(source: string, opts: Options.RenderOptions = {}): string { if (typeof source !== 'string') { throw new TypeError('render(): source argument is not a string') } if (opts !== undefined && typeof opts !== 'object') { throw new TypeError('render(): options argument is not an object') } Options.updateOptions(opts) return Api.render(source) } // Load-time initialization. Api.init()
/* This is the main module, it exports the 'render' API. The compiled modules are bundled by Webpack into 'var' (script tag) and 'commonjs' (npm) formatted libraries. */ import * as Api from './api' import * as Options from './options' /* The single public API which translates Rimu Markup to HTML: render(source [, options]) */ export function render(source: string, opts: Options.RenderOptions = {}): string { Options.updateOptions(opts) return Api.render(source) } // Load-time initialization. Api.init()
Drop API argument checks: redundant if the caller is TypeScript; if not then it's the caller's responsibility.
feature: Drop API argument checks: redundant if the caller is TypeScript; if not then it's the caller's responsibility.
TypeScript
mit
srackham/rimu
--- +++ @@ -14,12 +14,6 @@ render(source [, options]) */ export function render(source: string, opts: Options.RenderOptions = {}): string { - if (typeof source !== 'string') { - throw new TypeError('render(): source argument is not a string') - } - if (opts !== undefined && typeof opts !== 'object') { - throw new TypeError('render(): options argument is not an object') - } Options.updateOptions(opts) return Api.render(source) }
855486dbcfcb013f0d72071a0e1712e032a0bcc4
src/popup/bookmark-button/actions.ts
src/popup/bookmark-button/actions.ts
import { createAction } from 'redux-act' import { remoteFunction } from '../../util/webextensionRPC' import { Thunk } from '../types' import * as selectors from './selectors' import * as popup from '../selectors' const createBookmarkRPC = remoteFunction('addBookmark') const deleteBookmarkRPC = remoteFunction('delBookmark') export const setIsBookmarked = createAction<boolean>('bookmark/setIsBookmarked') export const toggleBookmark: () => Thunk = () => async (dispatch, getState) => { const state = getState() const url = popup.url(state) const tabId = popup.tabId(state) const isBookmarked = selectors.isBookmarked(state) if (!isBookmarked) { await createBookmarkRPC({ url, tabId }) } else { await deleteBookmarkRPC({ url }) } dispatch(setIsBookmarked(!isBookmarked)) }
import { createAction } from 'redux-act' import { remoteFunction } from '../../util/webextensionRPC' import { Thunk } from '../types' import * as selectors from './selectors' import * as popup from '../selectors' const createBookmarkRPC = remoteFunction('addBookmark') const deleteBookmarkRPC = remoteFunction('delBookmark') export const setIsBookmarked = createAction<boolean>('bookmark/setIsBookmarked') export const toggleBookmark: () => Thunk = () => async (dispatch, getState) => { const state = getState() const url = popup.url(state) const tabId = popup.tabId(state) const isBookmarked = selectors.isBookmarked(state) dispatch(setIsBookmarked(!isBookmarked)) try { if (!isBookmarked) { await createBookmarkRPC({ url, tabId }) } else { await deleteBookmarkRPC({ url }) } } catch (err) { dispatch(setIsBookmarked(isBookmarked)) } }
Make bookmarking UI state change optimistic
Make bookmarking UI state change optimistic - no need to wait for the DB here; change it back if error
TypeScript
mit
WorldBrain/WebMemex,WorldBrain/WebMemex
--- +++ @@ -15,12 +15,15 @@ const url = popup.url(state) const tabId = popup.tabId(state) const isBookmarked = selectors.isBookmarked(state) + dispatch(setIsBookmarked(!isBookmarked)) - if (!isBookmarked) { - await createBookmarkRPC({ url, tabId }) - } else { - await deleteBookmarkRPC({ url }) + try { + if (!isBookmarked) { + await createBookmarkRPC({ url, tabId }) + } else { + await deleteBookmarkRPC({ url }) + } + } catch (err) { + dispatch(setIsBookmarked(isBookmarked)) } - - dispatch(setIsBookmarked(!isBookmarked)) }
e0a9a68ab9937c28a4b406a7989b5b0400d1a5ea
src/Proxy.ts
src/Proxy.ts
import * as Proxy from "harmony-proxy"; export function createProxy ( state, previousState, multiplier ): any { return new Proxy( state, createHandler( previousState, multiplier ) ); } function createHandler ( previousState, multiplier ) { return { get ( state, property ) { let currentValue = state[ property ] let previousValue = previousState[ property ] if ( typeof( currentValue ) === "undefined" ) { currentValue = previousValue } if ( typeof( previousValue ) === "undefined" ) { previousValue = currentValue } if ( typeof( currentValue ) === "number" && typeof( previousValue ) === "number" ) { let result = currentValue + ( previousValue - currentValue ) * multiplier return isNaN( result ) ? null : result } else if ( currentValue === null ) { return null } else if ( typeof( currentValue ) === "object" ) { return createProxy( currentValue, previousValue, multiplier ) } else { return currentValue } } }; }
import * as Proxy from "harmony-proxy"; export function createProxy ( state, previousState, multiplier ): any { return new Proxy( state, createHandler( previousState, multiplier ) ); } function createHandler ( previousState, multiplier ) { return { get ( state, property ) { let currentValue = state[ property ] let previousValue = previousState[ property ] if ( currentValue === undefined ) { currentValue = previousValue } if ( previousValue === undefined ) { previousValue = currentValue } if ( typeof( currentValue ) === "number" && typeof( previousValue ) === "number" ) { let result = currentValue + ( previousValue - currentValue ) * multiplier return isNaN( result ) ? null : result } else if ( currentValue === null ) { return null } else if ( typeof( currentValue ) === "object" ) { return createProxy( currentValue, previousValue, multiplier ) } else { return currentValue } } }; }
Remove typeof in favor of strict check.
Remove typeof in favor of strict check. They are equivalent, there is no reason to use typeof when you can just check with an ===
TypeScript
mit
gamestdio/timeframe,gamestdio/timeframe
--- +++ @@ -10,11 +10,11 @@ let currentValue = state[ property ] let previousValue = previousState[ property ] - if ( typeof( currentValue ) === "undefined" ) { + if ( currentValue === undefined ) { currentValue = previousValue } - if ( typeof( previousValue ) === "undefined" ) { + if ( previousValue === undefined ) { previousValue = currentValue } @@ -30,7 +30,6 @@ } else { return currentValue - } } };
3df73e61835dc85b6c50c6828ce498da9eddd5fa
server/app.ts
server/app.ts
import * as dotenv from 'dotenv'; import * as express from 'express'; import * as morgan from 'morgan'; import * as mongoose from 'mongoose'; import * as path from 'path'; import setRoutes from './routes'; const app = express(); dotenv.config(); app.set('port', (process.env.PORT || 3000)); app.use('/', express.static(path.join(__dirname, '../public'))); app.use(express.json()); app.use(express.urlencoded({ extended: false })); let mongodbURI; if (process.env.NODE_ENV === 'test') { mongodbURI = process.env.MONGODB_TEST_URI; } else { mongodbURI = process.env.MONGODB_URI; app.use(morgan('dev')); } mongoose.Promise = global.Promise; mongoose.set('useCreateIndex', true); mongoose.set('useNewUrlParser', true); mongoose.set('useUnifiedTopology', true); mongoose.connect(mongodbURI) .then(db => { console.log('Connected to MongoDB'); setRoutes(app); app.get('/*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')); }); if (!module.parent) { app.listen(app.get('port'), () => console.log(`Angular Full Stack listening on port ${app.get('port')}`)); } }) .catch(err => console.error(err)); export { app };
import * as dotenv from 'dotenv'; import * as express from 'express'; import * as morgan from 'morgan'; import * as mongoose from 'mongoose'; import * as path from 'path'; import setRoutes from './routes'; const app = express(); dotenv.config(); app.set('port', (process.env.PORT || 3000)); app.use('/', express.static(path.join(__dirname, '../public'))); app.use(express.json()); app.use(express.urlencoded({ extended: false })); let mongodbURI; if (process.env.NODE_ENV === 'test') { mongodbURI = process.env.MONGODB_TEST_URI; } else { mongodbURI = process.env.MONGODB_URI; app.use(morgan('dev')); } mongoose.Promise = global.Promise; mongoose.set('useCreateIndex', true); mongoose.set('useNewUrlParser', true); mongoose.set('useFindAndModify', false); mongoose.set('useUnifiedTopology', true); mongoose.connect(mongodbURI) .then(db => { console.log('Connected to MongoDB'); setRoutes(app); app.get('/*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')); }); if (!module.parent) { app.listen(app.get('port'), () => console.log(`Angular Full Stack listening on port ${app.get('port')}`)); } }) .catch(err => console.error(err)); export { app };
Set flag for depreaction update on mongodb
Set flag for depreaction update on mongodb
TypeScript
mit
DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular2-Express-Mongoose
--- +++ @@ -25,6 +25,7 @@ mongoose.Promise = global.Promise; mongoose.set('useCreateIndex', true); mongoose.set('useNewUrlParser', true); +mongoose.set('useFindAndModify', false); mongoose.set('useUnifiedTopology', true); mongoose.connect(mongodbURI) .then(db => {
ca2c4f31a62f33be8f4d9d06814153fa434e31ce
src/types/game-unit.ts
src/types/game-unit.ts
import { chain, kebabCase } from 'lodash'; import { IGameUnit, IGameUnitConfig, IUnitParameter } from '../interfaces'; import { UnitParameter } from './unit-parameter'; export abstract class GameUnit implements IGameUnit { private readonly name: string; private readonly description?: string; private readonly id?: string; private readonly parameters: IUnitParameter[]; constructor(settings: IGameUnitConfig) { this.id = settings.id || kebabCase(settings.name); this.name = settings.name; this.description = settings.description; this.parameters = settings.parameters || []; } public getName(): string { return this.name; } public getDescription(): string { return this.description; } public getId(): string { return this.id; } public getParameterValue(id: string): string { return this.getParameterById(id).getValue(); } public setParameterValue(id: string, value: string): void { this.getParameterById(id).setValue(value); } public getParameters(): IUnitParameter[] { return this.parameters; } public abstract calculateScore(): Promise<number>; private getParameterById(id: string): IUnitParameter { return chain(this.parameters) .uniqBy(UnitParameter.byId) .find((parameter: any) => parameter.getId() === id) .value() as IUnitParameter; } }
import { chain, kebabCase } from 'lodash'; import { IGameUnit, IGameUnitConfig, IUnitParameter } from '../interfaces'; import { UnitParameter } from './unit-parameter'; export abstract class GameUnit implements IGameUnit { private readonly name: string; private readonly description?: string; private readonly id?: string; private readonly parameters: IUnitParameter[]; constructor(settings: IGameUnitConfig) { this.id = settings.id || kebabCase(settings.name); this.name = settings.name; this.description = settings.description; this.parameters = settings.parameters || []; } public getName(): string { return this.name; } public getDescription(): string { return this.description; } public getId(): string { return this.id; } public getParameterValue(id: string): any { return this.getParameterById(id).getValue(); } public setParameterValue(id: string, value: any): void { this.getParameterById(id).setValue(value); } public getParameters(): IUnitParameter[] { return this.parameters; } public abstract calculateScore(): Promise<number>; private getParameterById(id: string): IUnitParameter { return chain(this.parameters) .uniqBy(UnitParameter.byId) .find((parameter: any) => parameter.getId() === id) .value() as IUnitParameter; } }
Update getParameterValue and setParameterValue signatures
Update getParameterValue and setParameterValue signatures
TypeScript
mpl-2.0
Gamegains/gamegains-kit,Gamegains/gamegains-kit,Gamegains/gamegains-kit
--- +++ @@ -28,11 +28,11 @@ return this.id; } - public getParameterValue(id: string): string { + public getParameterValue(id: string): any { return this.getParameterById(id).getValue(); } - public setParameterValue(id: string, value: string): void { + public setParameterValue(id: string, value: any): void { this.getParameterById(id).setValue(value); }
5b49ddb801ea73840237fbf4173362b12c14333c
components/backdrop/backdrop.service.ts
components/backdrop/backdrop.service.ts
import { AppBackdrop } from './backdrop'; export interface BackdropOptions { context?: HTMLElement; className?: string; } export class Backdrop { private static backdrops: AppBackdrop[] = []; static push(options: BackdropOptions = {}) { const el = document.createElement('div'); if (!options.context) { document.body.appendChild(el); } else { options.context.appendChild(el); } const backdrop = new AppBackdrop({ propsData: { className: options.className, }, }); backdrop.$mount(el); this.backdrops.push(backdrop); document.body.classList.add('backdrop-active'); return backdrop; } static checkBackdrops() { const active = this.backdrops.filter(i => i.active); if (active.length === 0) { document.body.classList.remove('backdrop-active'); } } static remove(backdrop: AppBackdrop) { backdrop.$destroy(); backdrop.$el.parentNode!.removeChild(backdrop.$el); const index = this.backdrops.indexOf(backdrop); if (index !== -1) { this.backdrops.splice(index, 1); } } }
import { AppBackdrop } from './backdrop'; import { arrayRemove } from '../../utils/array'; export interface BackdropOptions { context?: HTMLElement; className?: string; } export class Backdrop { private static backdrops: AppBackdrop[] = []; static push(options: BackdropOptions = {}) { const el = document.createElement('div'); if (!options.context) { document.body.appendChild(el); } else { options.context.appendChild(el); } const backdrop = new AppBackdrop({ propsData: { className: options.className, }, }); backdrop.$mount(el); this.backdrops.push(backdrop); document.body.classList.add('backdrop-active'); return backdrop; } static checkBackdrops() { const active = this.backdrops.filter(i => i.active); if (active.length === 0) { document.body.classList.remove('backdrop-active'); } } static remove(backdrop: AppBackdrop) { backdrop.$destroy(); backdrop.$el.parentNode!.removeChild(backdrop.$el); arrayRemove(this.backdrops, i => i === backdrop); this.checkBackdrops(); } }
Fix backdrop not being checked in some situations.
Fix backdrop not being checked in some situations.
TypeScript
mit
gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib
--- +++ @@ -1,4 +1,5 @@ import { AppBackdrop } from './backdrop'; +import { arrayRemove } from '../../utils/array'; export interface BackdropOptions { context?: HTMLElement; @@ -41,10 +42,7 @@ static remove(backdrop: AppBackdrop) { backdrop.$destroy(); backdrop.$el.parentNode!.removeChild(backdrop.$el); - - const index = this.backdrops.indexOf(backdrop); - if (index !== -1) { - this.backdrops.splice(index, 1); - } + arrayRemove(this.backdrops, i => i === backdrop); + this.checkBackdrops(); } }
8d74e8882bb6c5abfce1d26bdfed06e3ca7d3269
types/split/index.d.ts
types/split/index.d.ts
// Type definitions for split v0.3.3 // Project: https://github.com/dominictarr/split // Definitions by: Marcin Porębski <https://github.com/marcinporebski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> /// <reference types="through" /> import { Transform, TransformOptions } from 'stream'; import { ThroughStream } from 'through'; interface SplitOptions { maxLength: number } declare function split(matcher?: any, mapper?: any, options?: SplitOptions): ThroughStream; export = split;
// Type definitions for split v1.0.1 // Project: https://github.com/dominictarr/split // Definitions by: Marcin Porębski <https://github.com/marcinporebski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> /// <reference types="through" /> import { Transform, TransformOptions } from 'stream'; import { ThroughStream } from 'through'; interface SplitOptions { maxLength: number } declare function split(matcher?: any, mapper?: any, options?: SplitOptions): ThroughStream; export = split;
Increase version number for split package
Increase version number for split package
TypeScript
mit
mcliment/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped
--- +++ @@ -1,4 +1,4 @@ -// Type definitions for split v0.3.3 +// Type definitions for split v1.0.1 // Project: https://github.com/dominictarr/split // Definitions by: Marcin Porębski <https://github.com/marcinporebski> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
08e2cb582527773b622d962feea58ee79bf8ed3d
app/VersionInformation.ts
app/VersionInformation.ts
export class VersionInformation { public date: string = "2017-08-03"; public commit: string = "1.0.0"; public link: string = "https://github.com/ultimate-comparisons/ultimate-comparison-BASE/releases/tag/1.0.0"; }
export class VersionInformation { public date: string = "2017-08-10"; public commit: string = "1.0.0"; public link: string = "https://github.com/ultimate-comparisons/ultimate-comparison-BASE/releases/tag/1.0.0"; }
Add correct date for release
Add correct date for release Signed-off-by: Armin Hueneburg <[email protected]>
TypeScript
mit
ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE,ultimate-comparisons/ultimate-comparison-BASE
--- +++ @@ -1,5 +1,5 @@ export class VersionInformation { - public date: string = "2017-08-03"; + public date: string = "2017-08-10"; public commit: string = "1.0.0"; public link: string = "https://github.com/ultimate-comparisons/ultimate-comparison-BASE/releases/tag/1.0.0"; }
4a674833baa7a885408eb8f94720b3f28ff312c2
packages/components/hooks/useEventManager.ts
packages/components/hooks/useEventManager.ts
import { useContext } from 'react'; import { EventManager } from 'proton-shared/lib/eventManager/eventManager'; import Context from '../containers/eventManager/context'; function useEventManager<EventModel, ListenerResult = void>() { const eventManager = useContext(Context); if (!eventManager) { throw new Error('Trying to use uninitialized EventManagerContext'); } return eventManager as EventManager<EventModel, ListenerResult>; } export default useEventManager;
import { useContext } from 'react'; import Context from '../containers/eventManager/context'; function useEventManager() { const eventManager = useContext(Context); if (!eventManager) { throw new Error('Trying to use uninitialized EventManagerContext'); } return eventManager; } export default useEventManager;
Move event manager type inference to subscribe function
Move event manager type inference to subscribe function
TypeScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1,15 +1,14 @@ import { useContext } from 'react'; -import { EventManager } from 'proton-shared/lib/eventManager/eventManager'; import Context from '../containers/eventManager/context'; -function useEventManager<EventModel, ListenerResult = void>() { +function useEventManager() { const eventManager = useContext(Context); if (!eventManager) { throw new Error('Trying to use uninitialized EventManagerContext'); } - return eventManager as EventManager<EventModel, ListenerResult>; + return eventManager; } export default useEventManager;
7ce9f5b6fed80d18e0e8415b973c466903d00116
src/main/ts/ephox/katamari/data/Immutable.ts
src/main/ts/ephox/katamari/data/Immutable.ts
import * as Arr from '../api/Arr'; import * as Fun from '../api/Fun'; export const Immutable = <T = Record<string,() => any>>(...fields: string[]) => { return function(...values: any[]): T { if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } const struct: Record<string,() => any> = {}; Arr.each(fields, function (name, i) { struct[name] = Fun.constant(values[i]); }); return <any>struct; }; };
import * as Arr from '../api/Arr'; import * as Fun from '../api/Fun'; export const Immutable = <T extends string>(...fields: T[]) => { return function(...values): { [key in T]: () => any } { if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } const struct = {} as {[key in T]: () => any}; Arr.each(fields, function (name, i) { struct[name] = Fun.constant(values[i]); }); return struct; }; };
Revert most of the changes to Struct.immutable as the original was better
TINY-1755: Revert most of the changes to Struct.immutable as the original was better
TypeScript
mit
tinymce/tinymce,TeamupCom/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,tinymce/tinymce,FernCreek/tinymce,TeamupCom/tinymce
--- +++ @@ -1,16 +1,18 @@ import * as Arr from '../api/Arr'; import * as Fun from '../api/Fun'; -export const Immutable = <T = Record<string,() => any>>(...fields: string[]) => { - return function(...values: any[]): T { +export const Immutable = <T extends string>(...fields: T[]) => { + return function(...values): { + [key in T]: () => any + } { if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } - const struct: Record<string,() => any> = {}; + const struct = {} as {[key in T]: () => any}; Arr.each(fields, function (name, i) { struct[name] = Fun.constant(values[i]); }); - return <any>struct; + return struct; }; };
498363351afa8edf8e2cca2a235e023efccae11d
app/react/src/client/preview/types-6-0.ts
app/react/src/client/preview/types-6-0.ts
import { ComponentClass, FunctionComponent } from 'react'; import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons'; import { StoryFnReactReturnType } from './types'; export { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons'; type ReactComponent = ComponentClass<any> | FunctionComponent<any>; type ReactReturnType = StoryFnReactReturnType; /** * Metadata to configure the stories for a component. * * @see [Default export](https://storybook.js.org/docs/formats/component-story-format/#default-export) */ export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> & Annotations<Args, ReactReturnType>; /** * Story function that represents a component example. * * @see [Named Story exports](https://storybook.js.org/docs/formats/component-story-format/#named-story-exports) */ export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> & Annotations<Args, ReactReturnType>;
import { ComponentType } from 'react'; import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons'; import { StoryFnReactReturnType } from './types'; export { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons'; type ReactComponent = ComponentType<any>; type ReactReturnType = StoryFnReactReturnType; /** * Metadata to configure the stories for a component. * * @see [Default export](https://storybook.js.org/docs/formats/component-story-format/#default-export) */ export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> & Annotations<Args, ReactReturnType>; /** * Story function that represents a component example. * * @see [Named Story exports](https://storybook.js.org/docs/formats/component-story-format/#named-story-exports) */ export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> & Annotations<Args, ReactReturnType>;
Simplify component type for CSF typing
React: Simplify component type for CSF typing
TypeScript
mit
storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook
--- +++ @@ -1,10 +1,10 @@ -import { ComponentClass, FunctionComponent } from 'react'; +import { ComponentType } from 'react'; import { Args as DefaultArgs, Annotations, BaseMeta, BaseStory } from '@storybook/addons'; import { StoryFnReactReturnType } from './types'; export { Args, ArgTypes, Parameters, StoryContext } from '@storybook/addons'; -type ReactComponent = ComponentClass<any> | FunctionComponent<any>; +type ReactComponent = ComponentType<any>; type ReactReturnType = StoryFnReactReturnType; /**
d069fe16cc151d69a040cbe0d1ba266a48e831a8
client/Library/Listing.ts
client/Library/Listing.ts
import { Listable, ServerListing } from "../../common/Listable"; import { Store } from "../Utility/Store"; export type ListingOrigin = "server" | "account" | "localStorage"; export class Listing<T extends Listable> implements ServerListing { constructor( public Id: string, public Name: string, public Path: string, public SearchHint: string, public Link: string, public Origin: ListingOrigin, value?: T ) { if (value) { this.value(value); } } private value = ko.observable<T>(); public SetValue = value => this.value(value); public GetAsyncWithUpdatedId(callback: (item: T) => any) { if (this.value()) { return callback(this.value()); } if (this.Origin === "localStorage") { const item = Store.Load<T>(this.Link, this.Id); item.Id = this.Id; if (item !== null) { return callback(item); } else { console.error(`Couldn't load item keyed '${this.Id}' from localStorage.`); } } return $.getJSON(this.Link).done(item => { this.value(item); return callback(item); }); } public CurrentName = ko.computed(() => { const current = this.value(); if (current !== undefined) { return current.Name || this.Name; } return this.Name; }); }
import { Listable, ServerListing } from "../../common/Listable"; import { Store } from "../Utility/Store"; export type ListingOrigin = "server" | "account" | "localStorage"; export class Listing<T extends Listable> implements ServerListing { constructor( public Id: string, public Name: string, public Path: string, public SearchHint: string, public Link: string, public Origin: ListingOrigin, value?: T ) { if (value) { this.value(value); } } private value = ko.observable<T>(); public SetValue = value => this.value(value); public GetAsyncWithUpdatedId(callback: (item: T) => any) { if (this.value()) { return callback(this.value()); } if (this.Origin === "localStorage") { const item = Store.Load<T>(this.Link, this.Id); item.Id = this.Id; if (item !== null) { return callback(item); } else { console.error(`Couldn't load item keyed '${this.Id}' from localStorage.`); } } return $.getJSON(this.Link).done(item => { item.Id = this.Id; this.value(item); return callback(item); }); } public CurrentName = ko.computed(() => { const current = this.value(); if (current !== undefined) { return current.Name || this.Name; } return this.Name; }); }
Update item Id when getting from server
Update item Id when getting from server
TypeScript
mit
cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative
--- +++ @@ -39,6 +39,7 @@ } return $.getJSON(this.Link).done(item => { + item.Id = this.Id; this.value(item); return callback(item); });
b6e1551727cc59f8c2b768b756904fc4d17ad685
src/components/__tests__/CuneiformChar.test.tsx
src/components/__tests__/CuneiformChar.test.tsx
import { shallow } from 'enzyme' import {} from 'jest' import React from 'react' import CuneiformChar from '../CuneiformChar' jest.mock('aphrodite/lib/inject') test('<CuneiformChar /> contains the given character', () => { const wrapper = shallow(<CuneiformChar value={'a'} translated={false} />) expect(wrapper.text()).toBe('a') })
import Enzyme, { shallow } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import {} from 'jest' import React from 'react' import CuneiformChar from '../CuneiformChar' Enzyme.configure({ adapter: new Adapter() }) jest.mock('aphrodite/lib/inject') test('<CuneiformChar /> contains the given character', () => { const wrapper = shallow(<CuneiformChar value={'a'} translated={false} />) expect(wrapper.text()).toBe('a') })
Test working on React 16
Test working on React 16
TypeScript
mit
loopingdoge/mesopotamia-jones,loopingdoge/mesopotamia-jones,loopingdoge/mesopotamia-jones
--- +++ @@ -1,8 +1,12 @@ -import { shallow } from 'enzyme' +import Enzyme, { shallow } from 'enzyme' +import Adapter from 'enzyme-adapter-react-16' + import {} from 'jest' import React from 'react' import CuneiformChar from '../CuneiformChar' + +Enzyme.configure({ adapter: new Adapter() }) jest.mock('aphrodite/lib/inject')
f743e043f630801cb7ee8cf70862cb4defe92ddb
test/db/collection.ts
test/db/collection.ts
import assert = require('assert'); import Schema = require('../../lib/db/schema'); import Type = require('../../lib/db/schema/type'); import db = require('../../lib/db'); describe('db.collection', () => { describe('#constructor', () => { it('create Collection with schema', () => { let userSchema = new Schema(1, { firstName: { type: Type.string }, lastName: { type: Type.string }, age: { type: Type.integer } }); let userCollection = new db.Collection("beyond.user", userSchema); assert.equal(userCollection.constructor, db.Collection); }); }); });
import assert = require('assert'); import Schema = require('../../lib/db/schema'); import Type = require('../../lib/db/schema/type'); import connection = require('../../lib/db/connection'); import db = require('../../lib/db'); describe('db.collection', () => { describe('#constructor', () => { it('create Collection with schema', (done: MochaDone) => { connection.initialize('mongodb://localhost:27017/beyondTest') .onSuccess(() => { let userSchema = new Schema(1, { firstName: { type: Type.string }, lastName: { type: Type.string }, age: { type: Type.integer } }); let userCollection = new db.Collection("beyond.user", userSchema); assert.equal(userCollection.constructor, db.Collection); connection.close(true) .onSuccess(() => { done(); }).onFailure((err: Error) => { done(err); }); }) .onFailure((err: Error) => { done(err); }); }); }); });
Initialize db before creating Collection.
Initialize db before creating Collection. The next patch will make Collection use db connection on constructor.
TypeScript
apache-2.0
sgkim126/beyond.ts,noraesae/beyond.ts,sgkim126/beyond.ts,murmur76/beyond.ts,noraesae/beyond.ts,murmur76/beyond.ts,SollmoStudio/beyond.ts,SollmoStudio/beyond.ts
--- +++ @@ -1,18 +1,32 @@ import assert = require('assert'); import Schema = require('../../lib/db/schema'); import Type = require('../../lib/db/schema/type'); +import connection = require('../../lib/db/connection'); import db = require('../../lib/db'); describe('db.collection', () => { describe('#constructor', () => { - it('create Collection with schema', () => { - let userSchema = new Schema(1, { - firstName: { type: Type.string }, - lastName: { type: Type.string }, - age: { type: Type.integer } + it('create Collection with schema', (done: MochaDone) => { + connection.initialize('mongodb://localhost:27017/beyondTest') + .onSuccess(() => { + let userSchema = new Schema(1, { + firstName: { type: Type.string }, + lastName: { type: Type.string }, + age: { type: Type.integer } + }); + let userCollection = new db.Collection("beyond.user", userSchema); + assert.equal(userCollection.constructor, db.Collection); + + connection.close(true) + .onSuccess(() => { + done(); + }).onFailure((err: Error) => { + done(err); + }); + }) + .onFailure((err: Error) => { + done(err); }); - let userCollection = new db.Collection("beyond.user", userSchema); - assert.equal(userCollection.constructor, db.Collection); }); }); });
02b460100935fc7a977ac5a422351e79210a15c8
types/ember-data/types/registries/model.d.ts
types/ember-data/types/registries/model.d.ts
/** * Catch-all for ember-data. */ export default interface ModelRegistry { [key: string]: any; }
/** * Catch-all for ember-data. */ export default interface ModelRegistry { // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; }
Allow any type for registry
Allow any type for registry
TypeScript
mit
ember-data/active-model-adapter,ember-data/active-model-adapter,ember-data/active-model-adapter
--- +++ @@ -2,5 +2,6 @@ * Catch-all for ember-data. */ export default interface ModelRegistry { + // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; }
afea95efb4dd4f8fa10d841fcb8c421e05147c32
bookvoyage-frontend/src/app/header/header.component.ts
bookvoyage-frontend/src/app/header/header.component.ts
import {Component, DoCheck, OnInit} from '@angular/core'; import {AuthService} from "../auth/auth.service"; import {HeaderService} from "./header.service"; import {Router} from "@angular/router"; import {Observable} from "rxjs/Observable"; import {environment} from "../../environments/environment"; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit, DoCheck { isLoggedIn = false; showAccountButtons; constructor(private authService: AuthService, private headerService: HeaderService, private router: Router) { } ngOnInit() { // clear local data if not logged in if (!this.authService.isLoggedIn()) { this.authService.clearLocalBookData(); } // Every so often, refresh token (time period can be set in the environment file) let timer = Observable.timer(0,environment.tokenRefresh); timer.subscribe(t => { // console.log(t); // DEBUG if (this.authService.isLoggedIn()) { this.authService.refreshToken(); } } ); } onAccountButton() { if (this.isLoggedIn) { this.router.navigate(['account']); } else { this.router.navigate(['login']); } } ngDoCheck() { this.isLoggedIn = this.authService.isLoggedIn(); this.showAccountButtons = this.headerService.showAccountButtons; } logout() { this.authService.logout(); this.router.navigate(['/']); } }
import {Component, DoCheck, OnInit} from '@angular/core'; import {AuthService} from "../auth/auth.service"; import {HeaderService} from "./header.service"; import {Router} from "@angular/router"; import {Observable} from "rxjs/Observable"; import {environment} from "../../environments/environment"; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent implements OnInit, DoCheck { isLoggedIn = false; showAccountButtons; constructor(private authService: AuthService, private headerService: HeaderService, private router: Router) { } ngOnInit() { // clear local data if not logged in if (!this.authService.isLoggedIn()) { this.authService.clearLocalBookData(); } // Every so often, refresh token (time period can be set in the environment file) let timer = Observable.timer(0,environment.tokenRefresh); timer.subscribe(t => { // console.log(t); // DEBUG if (this.authService.isLoggedIn()) { this.authService.refreshToken(); } } ); } onAccountButton() { if (this.isLoggedIn) { // this.router.navigate(['account']); } else { this.router.navigate(['login']); } } ngDoCheck() { this.isLoggedIn = this.authService.isLoggedIn(); this.showAccountButtons = this.headerService.showAccountButtons; } logout() { this.authService.logout(); this.router.navigate(['/']); } }
Remove direct click on header for mobile users' sake
Remove direct click on header for mobile users' sake
TypeScript
mit
edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage,edushifts/book-voyage
--- +++ @@ -37,7 +37,7 @@ onAccountButton() { if (this.isLoggedIn) { - this.router.navigate(['account']); + // this.router.navigate(['account']); } else { this.router.navigate(['login']); }
c534753c2c75d601836f20219f30ad89503c43b9
test/helpers/context/WithEnvironment.ts
test/helpers/context/WithEnvironment.ts
import sleep from '../utils/sleep'; export default function WithAutheliaRunning(suitePath: string, waitTimeout: number = 5000) { const suite = suitePath.split('/').slice(-1)[0]; var { setup, teardown } = require(`../../suites/${suite}/environment`); before(async function() { this.timeout(10000); console.log('Preparing environment...'); await setup(); await sleep(waitTimeout); }); after(async function() { this.timeout(30000); console.log('Stopping environment...'); await teardown(); await sleep(waitTimeout); }); }
import sleep from '../utils/sleep'; export default function WithAutheliaRunning(suitePath: string, waitTimeout: number = 5000) { const suite = suitePath.split('/').slice(-1)[0]; var { setup, teardown } = require(`../../suites/${suite}/environment`); before(async function() { this.timeout(30000); console.log('Preparing environment...'); await setup(); await sleep(waitTimeout); }); after(async function() { this.timeout(30000); console.log('Stopping environment...'); await teardown(); await sleep(waitTimeout); }); }
Increase timeout to prepare environment to 30 seconds.
Increase timeout to prepare environment to 30 seconds.
TypeScript
mit
clems4ever/authelia,clems4ever/two-factor-auth-server,clems4ever/authelia,clems4ever/authelia,clems4ever/authelia,clems4ever/two-factor-auth-server,clems4ever/authelia
--- +++ @@ -5,7 +5,7 @@ var { setup, teardown } = require(`../../suites/${suite}/environment`); before(async function() { - this.timeout(10000); + this.timeout(30000); console.log('Preparing environment...'); await setup();
886c6b348c210f1bfe4608d68da3fd4ef0f8b3bd
lib/tasks/Mappings.ts
lib/tasks/Mappings.ts
import Clean from "./Clean"; import NodeWatchBuild from "./NodeWatchBuild"; import Test from "./Test"; import Typescript from "./Typescript"; import Build from "./Build"; import FrontendWatchBuild from "./FrontendWatchBuild"; import Scaffolding from "./Scaffolding"; import Coverage from "./Coverage"; import ModuleWatchBuild from "./ModuleWatchBuild"; const gulp = require("gulp4"); export const frontend = { "clean": Clean, "build": gulp.series(Clean, Build), "watch-build": FrontendWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding }; export const module = { "clean": Clean, "build": Typescript, "watch-build": ModuleWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding }; export const nodejs = { "clean": Clean, "build": Typescript, "watch-build": NodeWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding };
import Clean from "./Clean"; import NodeWatchBuild from "./NodeWatchBuild"; import Test from "./Test"; import Typescript from "./Typescript"; import Build from "./Build"; import FrontendWatchBuild from "./FrontendWatchBuild"; import Scaffolding from "./Scaffolding"; import Coverage from "./Coverage"; import ModuleWatchBuild from "./ModuleWatchBuild"; import { PreBuild, PostBuild } from "./Hooks"; const gulp = require("gulp4"); export const frontend = { "clean": Clean, "build": gulp.series(Clean, Build), "watch-build": FrontendWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding }; export const module = { "clean": Clean, "build": gulp.series(PreBuild, Typescript, PostBuild), "watch-build": ModuleWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding }; export const nodejs = { "clean": Clean, "build": gulp.series(PreBuild, Typescript, PostBuild), "watch-build": NodeWatchBuild, "test": Test, "coverage": Coverage, "new": Scaffolding };
Add PreBuild and PostBuild in module and nodejs
Add PreBuild and PostBuild in module and nodejs
TypeScript
mit
mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild
--- +++ @@ -7,6 +7,7 @@ import Scaffolding from "./Scaffolding"; import Coverage from "./Coverage"; import ModuleWatchBuild from "./ModuleWatchBuild"; +import { PreBuild, PostBuild } from "./Hooks"; const gulp = require("gulp4"); export const frontend = { @@ -20,7 +21,7 @@ export const module = { "clean": Clean, - "build": Typescript, + "build": gulp.series(PreBuild, Typescript, PostBuild), "watch-build": ModuleWatchBuild, "test": Test, "coverage": Coverage, @@ -29,7 +30,7 @@ export const nodejs = { "clean": Clean, - "build": Typescript, + "build": gulp.series(PreBuild, Typescript, PostBuild), "watch-build": NodeWatchBuild, "test": Test, "coverage": Coverage,
9f46376ee03a1479916ffc11d634496a879c24fd
src/extension.ts
src/extension.ts
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Congratulations, your extension "center-editor-window" is now active!'); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand('extension.centerEditorWindow', () => { // The code you place here will be executed every time your command is executed // Display a message box to the user const editor = vscode.window.activeTextEditor; const selection = editor.selection; const range = new vscode.Range(selection.start, selection.end); editor.revealRange(range, vscode.TextEditorRevealType.InCenter); }); context.subscriptions.push(disposable); } // this method is called when your extension is deactivated export function deactivate() { }
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand('extension.centerEditorWindow', () => { // The code you place here will be executed every time your command is executed // Display a message box to the user const editor = vscode.window.activeTextEditor; const selection = editor.selection; const range = new vscode.Range(selection.start, selection.end); editor.revealRange(range, vscode.TextEditorRevealType.InCenter); }); context.subscriptions.push(disposable); } // this method is called when your extension is deactivated export function deactivate() { }
Remove log message and do some cleanup
Remove log message and do some cleanup
TypeScript
mit
kaiwood/vscode-center-editor-window
--- +++ @@ -6,11 +6,6 @@ // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { - - // Use the console to output diagnostic information (console.log) and errors (console.error) - // This line of code will only be executed once when your extension is activated - console.log('Congratulations, your extension "center-editor-window" is now active!'); - // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json @@ -23,7 +18,6 @@ const selection = editor.selection; const range = new vscode.Range(selection.start, selection.end); editor.revealRange(range, vscode.TextEditorRevealType.InCenter); - }); context.subscriptions.push(disposable);
323b33ded7f6a67841ca84746f747ba209afe3b6
tests/utils/fireOnce.test.ts
tests/utils/fireOnce.test.ts
import {fireOnce} from '../../src/utils'; describe('fireOnce', () => { let callback: jasmine.Spy; beforeEach(() => { callback = jasmine.createSpy('callback'); }) it('function should only fire once (with single element)', () => { const element = document.createElement('div'); fireOnce([element], 'click', callback); element.click(); expect(callback.calls.count()).toBe(1); }); it('function should only fire once (with multiple elements)', () => { const elements: HTMLElement[] = []; for (let i = 0; i < 2; i++) { elements.push(document.createElement('div')); } fireOnce(elements, 'click', callback); for (const el of elements) { el.click(); } expect(callback.calls.count()).toBe(1); }); });
import {fireOnce} from '../../src/utils'; describe('fireOnce', () => { let callback: jasmine.Spy; beforeEach(() => { callback = jasmine.createSpy('callback'); }) it('function should only fire once (with single element)', () => { const element = document.createElement('div'); fireOnce([element], 'click', callback); element.click(); expect(callback).toHaveBeenCalledTimes(1); }); it('function should only fire once (with multiple elements)', () => { const elements: HTMLElement[] = []; for (let i = 0; i < 2; i++) { elements.push(document.createElement('div')); } fireOnce(elements, 'click', callback); for (const el of elements) { el.click(); } expect(callback).toHaveBeenCalledTimes(1); }); });
Use a better matcher for mocked funtions
Use a better matcher for mocked funtions
TypeScript
mit
bkazi/react-layout-transition,bkazi/react-layout-transition,bkazi/react-layout-transition
--- +++ @@ -14,7 +14,7 @@ element.click(); - expect(callback.calls.count()).toBe(1); + expect(callback).toHaveBeenCalledTimes(1); }); it('function should only fire once (with multiple elements)', () => { @@ -29,7 +29,7 @@ el.click(); } - expect(callback.calls.count()).toBe(1); + expect(callback).toHaveBeenCalledTimes(1); }); });
2dadbb3b73e47f17dca96fadda080fa1c826a636
client/src/app/admin/admin.service.ts
client/src/app/admin/admin.service.ts
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from "rxjs"; @Injectable() export class AdminService { private url: string = API_URL; constructor(private http:Http) { } getUploadIDs(): Observable<string[]> { return this.http.request(this.url + "uploadIDs", {withCredentials: true}).map(res => res.json()); } getLiveUploadID(): Observable<string> { return this.http.request(this.url + "liveUploadID", {withCredentials: true}).map(res => res.json()); } deleteUploadID(uploadId : string) : Observable<any> { return this.http.delete(this.url + "deleteData/" + uploadId, {withCredentials: true}).map(res => res.json()); } authorized() : Observable<boolean> { return this.http.get(this.url + "check-authorization", {withCredentials: true}).map(res => res.json().authorized); } }
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from "rxjs"; @Injectable() export class AdminService { private url: string = API_URL; constructor(private http:Http) { } getUploadIDs(): Observable<string[]> { return this.http.request(this.url + "uploadIDs", {withCredentials: true}).map(res => res.json()); } getLiveUploadID(): Observable<string> { return this.http.request(this.url + "liveUploadID", {withCredentials: true}).map(res => res.json()); } deleteUploadID(uploadID : string) : Observable<any> { return this.http.delete(this.url + "deleteData/" + uploadID, {withCredentials: true}).map(res => res.json()); } authorized() : Observable<boolean> { return this.http.get(this.url + "check-authorization", {withCredentials: true}).map(res => res.json().authorized); } }
Rename local var in AdminService
Rename local var in AdminService
TypeScript
mit
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,UMM-CSci-3601-S17/digital-display-garden-iteration-4-dorfner-v2
--- +++ @@ -15,8 +15,8 @@ return this.http.request(this.url + "liveUploadID", {withCredentials: true}).map(res => res.json()); } - deleteUploadID(uploadId : string) : Observable<any> { - return this.http.delete(this.url + "deleteData/" + uploadId, {withCredentials: true}).map(res => res.json()); + deleteUploadID(uploadID : string) : Observable<any> { + return this.http.delete(this.url + "deleteData/" + uploadID, {withCredentials: true}).map(res => res.json()); } authorized() : Observable<boolean> {
7fbeb670ec64ceaf271193d9e6cad0b5dc3534b9
source/services/timezone/timezone.service.tests.ts
source/services/timezone/timezone.service.tests.ts
import { timezone } from './timezone.service'; import { defaultFormats } from '../date/date.module'; import * as moment from 'moment'; import 'moment-timezone'; describe('timezone', (): void => { it('should return the timezone', (): void => { let date: moment.Moment = moment('2001-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); expect(timezone.getTimezone(date)).to.equal('-07:00'); }); it('should handle daylight savings time', (): void => { let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); expect(timezone.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00'); expect(timezone.getTimezone(dateWithDaylightSavings)).to.equal('-07:00'); }); });
import { timezone as timezoneService } from './timezone.service'; import { defaultFormats } from '../date/date.module'; import * as moment from 'moment'; import 'moment-timezone'; import { timezones } from './timezone.enum'; describe('timezone', (): void => { it('should return the timezone', (): void => { let date: moment.Moment = moment('2001-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); expect(timezoneService.getTimezone(date)).to.equal('-07:00'); }); it('should handle daylight savings time', (): void => { let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); expect(timezoneService.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00'); expect(timezoneService.getTimezone(dateWithDaylightSavings)).to.equal('-07:00'); }); }); });
Use the PST timezone instead of a magic string. Renamed timezone to timezoneService for clarity.
Use the PST timezone instead of a magic string. Renamed timezone to timezoneService for clarity.
TypeScript
mit
RenovoSolutions/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities
--- +++ @@ -1,19 +1,22 @@ -import { timezone } from './timezone.service'; +import { timezone as timezoneService } from './timezone.service'; import { defaultFormats } from '../date/date.module'; import * as moment from 'moment'; import 'moment-timezone'; +import { timezones } from './timezone.enum'; + describe('timezone', (): void => { it('should return the timezone', (): void => { - let date: moment.Moment = moment('2001-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); - expect(timezone.getTimezone(date)).to.equal('-07:00'); + let date: moment.Moment = moment('2001-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); + expect(timezoneService.getTimezone(date)).to.equal('-07:00'); }); it('should handle daylight savings time', (): void => { - let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); - let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles'); - expect(timezone.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00'); - expect(timezone.getTimezone(dateWithDaylightSavings)).to.equal('-07:00'); + let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); + let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz(timezones.PST.momentName); + expect(timezoneService.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00'); + expect(timezoneService.getTimezone(dateWithDaylightSavings)).to.equal('-07:00'); + }); }); });
b9f91684b527645077831a9c032a186e71c41db0
desktopswitch_ru.ts
desktopswitch_ru.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> <context> <name>DesktopSwitch</name> <message> <source>Desktop %1</source> <translation>рабочий стол %1</translation> </message> </context> </TS>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru"> <context> <name>DesktopSwitch</name> <message> <location filename="../desktopswitch.cpp" line="79"/> <source>Desktop %1</source> <translation>Рабочий стол %1</translation> </message> </context> <context> <name>DesktopSwitchButton</name> <message> <location filename="../desktopswitchbutton.cpp" line="46"/> <source>Switch to desktop %1</source> <translation>Переключиться на рабочий стол %1</translation> </message> </context> </TS>
Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)."
Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)." This reverts commit d538764d91b1cf3ea993cdf0d6200eea2b2c9384. It appeared this change was wrong because it was out of sync.
TypeScript
lgpl-2.1
lxde/lxqt-l10n
--- +++ @@ -1,9 +1,20 @@ -<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> +<?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE TS> +<TS version="2.1" language="ru"> <context> <name>DesktopSwitch</name> <message> + <location filename="../desktopswitch.cpp" line="79"/> <source>Desktop %1</source> - <translation>рабочий стол %1</translation> + <translation>Рабочий стол %1</translation> + </message> +</context> +<context> + <name>DesktopSwitchButton</name> + <message> + <location filename="../desktopswitchbutton.cpp" line="46"/> + <source>Switch to desktop %1</source> + <translation>Переключиться на рабочий стол %1</translation> </message> </context> </TS>
615015738b25854b984d44f4674a649f017eb844
client/src/extension.ts
client/src/extension.ts
/*#######. ########",#: #########',##". ##'##'## .##',##. ## ## ## # ##",#. ## ## ## ## ##' ## ## ## :## ## ## ##*/ 'use strict' import { join } from 'path' import { workspace, ExtensionContext } from 'vscode' import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient' export function activate(context: ExtensionContext) { const serverModule = context.asAbsolutePath(join('server', 'server.js')) const debugOptions = { execArgv: ['--nolazy', '--debug=6004'] } const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } } const clientOptions: LanguageClientOptions = { // Register server for C and C++ files documentSelector: ['c', 'cpp'], synchronize: { configurationSection: 'clangComplete', fileEvents: workspace.createFileSystemWatcher('**/.clang_complete') } } const disposable = new LanguageClient( 'ClangComplete', serverOptions, clientOptions ).start() context.subscriptions.push(disposable) }
/*#######. ########",#: #########',##". ##'##'## .##',##. ## ## ## # ##",#. ## ## ## ## ##' ## ## ## :## ## ## ##*/ 'use strict' import { join } from 'path' import { workspace, ExtensionContext } from 'vscode' import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient' export function activate(context: ExtensionContext) { const serverModule = context.asAbsolutePath(join('server', 'server.js')) const debugOptions = { execArgv: ['--nolazy', '--debug=6004'] } const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } } const clientOptions: LanguageClientOptions = { // Register server for C and C++ files documentSelector: [ { scheme: 'file', language: 'c' }, { scheme: 'file', language: 'cpp' } ], synchronize: { configurationSection: 'clangComplete', fileEvents: workspace.createFileSystemWatcher('**/.clang_complete') } } const disposable = new LanguageClient( 'ClangComplete', serverOptions, clientOptions ).start() context.subscriptions.push(disposable) }
Add schemes to documentSelector in LanguageClientOptions
Add schemes to documentSelector in LanguageClientOptions
TypeScript
mit
kube/vscode-clang-complete,kube/vscode-clang-complete
--- +++ @@ -37,7 +37,10 @@ const clientOptions: LanguageClientOptions = { // Register server for C and C++ files - documentSelector: ['c', 'cpp'], + documentSelector: [ + { scheme: 'file', language: 'c' }, + { scheme: 'file', language: 'cpp' } + ], synchronize: { configurationSection: 'clangComplete', fileEvents: workspace.createFileSystemWatcher('**/.clang_complete')
daca5736eeef967891f02f322184122a57105c3c
src/renderer/pages/BrowserPage/BrowserContext/index.tsx
src/renderer/pages/BrowserPage/BrowserContext/index.tsx
import { messages } from "common/butlerd"; import { Space } from "common/helpers/space"; import { Dispatch } from "common/types"; import React from "react"; import butlerCaller, { LoadingStateDiv } from "renderer/hocs/butlerCaller"; import { hook } from "renderer/hocs/hook"; import { withSpace } from "renderer/hocs/withSpace"; import { browserContextHeight } from "renderer/pages/BrowserPage/BrowserContext/BrowserContextConstants"; import BrowserContextGame from "renderer/pages/BrowserPage/BrowserContext/BrowserContextGame"; import styled, { animations } from "renderer/styles"; const FetchGame = butlerCaller(messages.FetchGame); const BrowserContextContainer = styled.div` height: ${browserContextHeight}px; display: flex; flex-direction: column; justify-content: center; animation: ${animations.enterBottom} 0.2s; `; class BrowserContext extends React.PureComponent<Props> { render() { const { space } = this.props; if (space.prefix === "games") { const gameId = space.numericId(); return ( <BrowserContextContainer> <FetchGame params={{ gameId }} sequence={space.sequence()} render={({ result }) => { return <BrowserContextGame game={result.game} />; }} /> </BrowserContextContainer> ); } return null; } } interface Props { space: Space; dispatch: Dispatch; } export default withSpace(hook()(BrowserContext));
import { messages } from "common/butlerd"; import { Space } from "common/helpers/space"; import { Dispatch } from "common/types"; import React from "react"; import butlerCaller from "renderer/hocs/butlerCaller"; import { hook } from "renderer/hocs/hook"; import { withSpace } from "renderer/hocs/withSpace"; import { browserContextHeight } from "renderer/pages/BrowserPage/BrowserContext/BrowserContextConstants"; import BrowserContextGame from "renderer/pages/BrowserPage/BrowserContext/BrowserContextGame"; import styled from "renderer/styles"; const FetchGame = butlerCaller(messages.FetchGame); const BrowserContextContainer = styled.div` height: ${browserContextHeight}px; display: flex; flex-direction: column; justify-content: center; `; class BrowserContext extends React.PureComponent<Props> { render() { const { space } = this.props; if (space.prefix === "games") { const gameId = space.numericId(); return ( <BrowserContextContainer> <FetchGame params={{ gameId }} sequence={space.sequence()} render={({ result }) => { return <BrowserContextGame game={result.game} />; }} /> </BrowserContextContainer> ); } return null; } } interface Props { space: Space; dispatch: Dispatch; } export default withSpace(hook()(BrowserContext));
Disable animation for BrowserContext, it doesn't play well with BrowserView
Disable animation for BrowserContext, it doesn't play well with BrowserView
TypeScript
mit
itchio/itchio-app,itchio/itchio-app,itchio/itch,itchio/itchio-app,leafo/itchio-app,itchio/itch,leafo/itchio-app,itchio/itch,itchio/itch,itchio/itch,leafo/itchio-app,itchio/itch
--- +++ @@ -2,12 +2,12 @@ import { Space } from "common/helpers/space"; import { Dispatch } from "common/types"; import React from "react"; -import butlerCaller, { LoadingStateDiv } from "renderer/hocs/butlerCaller"; +import butlerCaller from "renderer/hocs/butlerCaller"; import { hook } from "renderer/hocs/hook"; import { withSpace } from "renderer/hocs/withSpace"; import { browserContextHeight } from "renderer/pages/BrowserPage/BrowserContext/BrowserContextConstants"; import BrowserContextGame from "renderer/pages/BrowserPage/BrowserContext/BrowserContextGame"; -import styled, { animations } from "renderer/styles"; +import styled from "renderer/styles"; const FetchGame = butlerCaller(messages.FetchGame); @@ -17,8 +17,6 @@ display: flex; flex-direction: column; justify-content: center; - - animation: ${animations.enterBottom} 0.2s; `; class BrowserContext extends React.PureComponent<Props> {
f7cac1b8fe2b27666d0b1c5e96e1af306878d034
src/dependument.ts
src/dependument.ts
export class Dependument { private package: string; private templates: string; constructor(options: any) { if (!options.path) { throw new Error("No path specified in options"); } } }
export class Dependument { private package: string; private templates: string; constructor(options: any) { if (!options.path) { throw new Error("No path specified in options"); } if (!options.path.package) { throw new Error("No package path specified in options"); } } }
Throw error if no package path
Throw error if no package path
TypeScript
unlicense
dependument/dependument,dependument/dependument,Jameskmonger/dependument,Jameskmonger/dependument
--- +++ @@ -6,5 +6,9 @@ if (!options.path) { throw new Error("No path specified in options"); } + + if (!options.path.package) { + throw new Error("No package path specified in options"); + } } }
f34a8239d0f0ab706de8223616716ad32260d42c
src/environments/environment.ts
src/environments/environment.ts
// This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, resources: ['drachma', 'food', 'water', 'wood', 'iron', 'stone', 'marble', 'grapes', 'wine', 'gold'], style: { default: 'pink', allowed: ['pink', 'red'] }, SOCKET_ENDPOINT: 'https://ewnextv2.ellaswar.com', };
// This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, resources: ['drachma', 'food', 'water', 'wood', 'iron', 'stone', 'marble', 'grapes', 'wine', 'gold'], style: { default: 'red', allowed: ['pink', 'red'] }, SOCKET_ENDPOINT: 'https://ewnextv2.ellaswar.com', };
Switch default style to red
Switch default style to red
TypeScript
agpl-3.0
V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War
--- +++ @@ -6,7 +6,7 @@ production: false, resources: ['drachma', 'food', 'water', 'wood', 'iron', 'stone', 'marble', 'grapes', 'wine', 'gold'], style: { - default: 'pink', + default: 'red', allowed: ['pink', 'red'] }, SOCKET_ENDPOINT: 'https://ewnextv2.ellaswar.com',
68c80261260763c3efc59feb3989016da4909919
app/pages/session-detail/session-detail.ts
app/pages/session-detail/session-detail.ts
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { UserData } from '../../providers/user-data'; @Component({ templateUrl: 'build/pages/session-detail/session-detail.html' }) export class SessionDetailPage { session: any; loggedIn = false; isFavourite = false; constructor( public navParams: NavParams, public userData: UserData ) { this.session = navParams.data; this.userData.hasLoggedIn().then((hasLoggedIn) => { this.loggedIn = hasLoggedIn === 'true'; this.isFavourite = false; }); } addParticipation() { console.log('Clicked participate'); this.userData.addFavorite(this.session.name); this.isFavourite = true; } cancelParticipation() { console.log('Clicked on cancel'); this.userData.removeFavorite(this.session.name); this.isFavourite = false; } }
import { Component } from '@angular/core'; import { NavParams } from 'ionic-angular'; import { UserData } from '../../providers/user-data'; @Component({ templateUrl: 'build/pages/session-detail/session-detail.html' }) export class SessionDetailPage { session: any; loggedIn = false; isFavourite = false; constructor( public navParams: NavParams, public userData: UserData ) { this.session = navParams.data; this.userData.hasLoggedIn().then((hasLoggedIn) => { this.loggedIn = hasLoggedIn === 'true'; this.isFavourite = this.userData.hasFavorite(this.session.name); }); } addParticipation() { console.log('Clicked participate'); this.userData.addFavorite(this.session.name); this.isFavourite = true; } cancelParticipation() { console.log('Clicked on cancel'); this.userData.removeFavorite(this.session.name); this.isFavourite = false; } }
Check if presentation is not already added
Check if presentation is not already added
TypeScript
apache-2.0
laodice/ionic-conference-app-session2,laodice/ionic-conference-app-session2,laodice/ionic-conference-app-session2
--- +++ @@ -21,7 +21,7 @@ this.userData.hasLoggedIn().then((hasLoggedIn) => { this.loggedIn = hasLoggedIn === 'true'; - this.isFavourite = false; + this.isFavourite = this.userData.hasFavorite(this.session.name); }); }
da606dd8b8106dea1beca9afc12e528ef29fb2fc
packages/expo/src/environment/logging.ts
packages/expo/src/environment/logging.ts
import { Constants } from 'expo-constants'; import Logs from '../logs/Logs'; import RemoteLogging from '../logs/RemoteLogging'; if (Constants.manifest && Constants.manifest.logUrl) { // Enable logging to the Expo dev tools only if this JS is not running in a web browser (ex: the // remote debugger) if (!navigator.hasOwnProperty('userAgent')) { Logs.enableExpoCliLogging(); } else { RemoteLogging.enqueueRemoteLogAsync('info', {}, [ 'You are now debugging remotely; check your browser console for your application logs.', ]); } } // NOTE(2018-10-29): temporarily filter out cyclic dependency warnings here since they are noisy and // each warning symbolicates a stack trace, which is slow when there are many warnings const originalWarn = console.warn; console.warn = function warn(...args) { if ( args.length > 0 && typeof args[0] === 'string' && /^Require cycle: .*\/node_modules\//.test(args[0]) ) { return; } originalWarn.apply(console, args); };
import { Constants } from 'expo-constants'; import Logs from '../logs/Logs'; import RemoteLogging from '../logs/RemoteLogging'; if (Constants.manifest && Constants.manifest.logUrl) { // Enable logging to the Expo dev tools only if this JS is not running in a web browser (ex: the // remote debugger) if (!navigator.hasOwnProperty('userAgent')) { Logs.enableExpoCliLogging(); } else { RemoteLogging.enqueueRemoteLogAsync('info', {}, [ 'You are now debugging remotely; check your browser console for your application logs.', ]); } } // NOTE(2018-10-29): temporarily filter out cyclic dependency warnings here since they are noisy and // each warning symbolicates a stack trace, which is slow when there are many warnings const originalWarn = console.warn; console.warn = function warn(...args) { if ( args.length > 0 && typeof args[0] === 'string' && /^Require cycle: .*node_modules\//.test(args[0]) ) { return; } originalWarn.apply(console, args); };
Remove slash before the "node_modules" string in "Require cycle" warn message regex
Remove slash before the "node_modules" string in "Require cycle" warn message regex Previous regex doesn't match any of "Require cycle" warns as they all contain not absolute warned modules path, but relative to project directory and without starting slash. Example warn message "Require cycle: node_modules/react-native-gesture-handler/GestureHandler.js -> node_modules/react-native-gesture-handler/Swipeable.js -> node_modules/react-native-gesture-handler/GestureHandler.js"
TypeScript
bsd-3-clause
exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent
--- +++ @@ -22,7 +22,7 @@ if ( args.length > 0 && typeof args[0] === 'string' && - /^Require cycle: .*\/node_modules\//.test(args[0]) + /^Require cycle: .*node_modules\//.test(args[0]) ) { return; }
6693609566dcd7928faa676ab8fa2ee26f62fb40
packages/passport/src/index.ts
packages/passport/src/index.ts
import "./PassportModule"; export * from "./decorators/authenticate"; export * from "./decorators/overrideProtocol"; export * from "./decorators/protocol"; export * from "./interfaces/IProtocolOptions"; export * from "./interfaces/IProtocol"; export * from "./interfaces/onInstall"; export * from "./interfaces/onVerify"; export * from "./controllers/PassportCtrl"; export * from "./protocols/LocalProtocol"; export * from "./registries/ProtocolRegistries"; export * from "./services/ProtocolsService"; export * from "./services/PassportSerializerService"; export * from "./middlewares/AuthenticateMiddleware";
import "./PassportModule"; export * from "./decorators/authenticate"; export * from "./decorators/overrideProtocol"; export * from "./decorators/protocol"; export * from "./interfaces/IProtocolOptions"; export * from "./interfaces/IProtocol"; export * from "./interfaces/OnInstall"; export * from "./interfaces/OnVerify"; export * from "./controllers/PassportCtrl"; export * from "./protocols/LocalProtocol"; export * from "./registries/ProtocolRegistries"; export * from "./services/ProtocolsService"; export * from "./services/PassportSerializerService"; export * from "./middlewares/AuthenticateMiddleware";
Fix typo on exported file name
fix(passport): Fix typo on exported file name
TypeScript
mit
Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators
--- +++ @@ -6,8 +6,8 @@ export * from "./interfaces/IProtocolOptions"; export * from "./interfaces/IProtocol"; -export * from "./interfaces/onInstall"; -export * from "./interfaces/onVerify"; +export * from "./interfaces/OnInstall"; +export * from "./interfaces/OnVerify"; export * from "./controllers/PassportCtrl"; export * from "./protocols/LocalProtocol";
b37a57f0b7b154b38375a722b1f9c56a5d23a435
src/app/router.animations.ts
src/app/router.animations.ts
/** * Code is from https://medium.com/google-developer-experts/ * angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8 */ import { sequence, trigger, stagger, animate, style, group, query, transition, keyframes, animateChild } from '@angular/animations'; export const routerTransition = trigger('routerTransition', [ transition('* => *', [ query(':enter, :leave', style({ position: 'fixed', width: '100%' }), {optional: true}), query(':enter', style({ opacity: 0 }), {optional: true}), sequence([ query(':leave', animateChild(), {optional: true}), group([ query(':leave', [ style({ opacity: 1 }), animate('500ms cubic-bezier(.75,-0.48,.26,1.52)', style({ opacity: 0 })) ], {optional: true}), query(':enter', [ style({ opacity: 0 }), animate('500ms cubic-bezier(.75,-0.48,.26,1.52)', style({ opacity: 1 })) ], {optional: true}), ]), query(':enter', animateChild(), {optional: true}) ]) ]) ]);
/** * Code is from https://medium.com/google-developer-experts/ * angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8 */ import { sequence, trigger, stagger, animate, style, group, query, transition, keyframes, animateChild } from '@angular/animations'; export const routerTransition = trigger('routerTransition', [ transition('* => *', [ query(':enter, :leave', style({ position: 'fixed', width: '100%' }), {optional: true}), query(':enter', style({ opacity: 0 }), {optional: true}), sequence([ query(':leave', animateChild(), {optional: true}), group([ query(':leave', [ style({ opacity: 1 }), animate('500ms ease-out', style({ opacity: 0 })) ], {optional: true}), query(':enter', [ style({ opacity: 0 }), animate('500ms 300ms ease-in', style({ opacity: 1 })) ], {optional: true}), ]), query(':enter', animateChild(), {optional: true}) ]) ]) ]);
Change animation from bezier to easing
Change animation from bezier to easing
TypeScript
mit
sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com
--- +++ @@ -23,12 +23,12 @@ group([ query(':leave', [ style({ opacity: 1 }), - animate('500ms cubic-bezier(.75,-0.48,.26,1.52)', + animate('500ms ease-out', style({ opacity: 0 })) ], {optional: true}), query(':enter', [ style({ opacity: 0 }), - animate('500ms cubic-bezier(.75,-0.48,.26,1.52)', + animate('500ms 300ms ease-in', style({ opacity: 1 })) ], {optional: true}), ]),
e5a52f6a6ec35a6ca1ffcb9cd4f60fd3b0fa6084
client/app/register/register.component.spec.ts
client/app/register/register.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RegisterComponent } from './register.component'; describe('Component: Register', () => { let component: RegisterComponent; let fixture: ComponentFixture<RegisterComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ RegisterComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RegisterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); /*it('should create', () => { expect(component).toBeTruthy(); }); it('should display the string "Register" in h4', () => { const el = fixture.debugElement.query(By.css('h4')).nativeElement; expect(el.textContent).toContain('Register'); });*/ });
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RegisterComponent } from './register.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ToastComponent } from '../shared/toast/toast.component'; import { Router } from '@angular/router'; import { UserService } from '../services/user.service'; class RouterMock { } class UserServiceMock { } describe('Component: Register', () => { let component: RegisterComponent; let fixture: ComponentFixture<RegisterComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ FormsModule, ReactiveFormsModule ], declarations: [ RegisterComponent ], providers: [ ToastComponent, { provide: Router, useClass: RouterMock }, { provide: UserService, useClass: UserServiceMock } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RegisterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display the page header text', () => { const el = fixture.debugElement.query(By.css('h4')).nativeElement; expect(el.textContent).toContain('Register'); }); it('should display the username, email and password inputs', () => { const [inputUsername, inputEmail, inputPassword] = fixture.debugElement.queryAll(By.css('input')); expect(inputUsername.nativeElement).toBeTruthy(); expect(inputEmail.nativeElement).toBeTruthy(); expect(inputPassword.nativeElement).toBeTruthy(); expect(inputUsername.nativeElement.value).toBeFalsy(); expect(inputEmail.nativeElement.value).toBeFalsy(); expect(inputPassword.nativeElement.value).toBeFalsy(); }); it('should display the register button', () => { const el = fixture.debugElement.query(By.css('button')).nativeElement; expect(el).toBeTruthy(); expect(el.textContent).toContain('Register'); expect(el.disabled).toBeTruthy(); }); });
Add unit tests for register component
Add unit tests for register component
TypeScript
mit
DavideViolante/Angular-Full-Stack,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose,DavideViolante/Angular-Full-Stack,DavideViolante/Angular2-Express-Mongoose
--- +++ @@ -2,6 +2,13 @@ import { By } from '@angular/platform-browser'; import { RegisterComponent } from './register.component'; +import { FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { ToastComponent } from '../shared/toast/toast.component'; +import { Router } from '@angular/router'; +import { UserService } from '../services/user.service'; + +class RouterMock { } +class UserServiceMock { } describe('Component: Register', () => { let component: RegisterComponent; @@ -9,7 +16,13 @@ beforeEach(async(() => { TestBed.configureTestingModule({ - declarations: [ RegisterComponent ] + imports: [ FormsModule, ReactiveFormsModule ], + declarations: [ RegisterComponent ], + providers: [ + ToastComponent, + { provide: Router, useClass: RouterMock }, + { provide: UserService, useClass: UserServiceMock } + ] }) .compileComponents(); })); @@ -20,12 +33,29 @@ fixture.detectChanges(); }); - /*it('should create', () => { + it('should create', () => { expect(component).toBeTruthy(); }); - it('should display the string "Register" in h4', () => { + it('should display the page header text', () => { const el = fixture.debugElement.query(By.css('h4')).nativeElement; expect(el.textContent).toContain('Register'); - });*/ + }); + + it('should display the username, email and password inputs', () => { + const [inputUsername, inputEmail, inputPassword] = fixture.debugElement.queryAll(By.css('input')); + expect(inputUsername.nativeElement).toBeTruthy(); + expect(inputEmail.nativeElement).toBeTruthy(); + expect(inputPassword.nativeElement).toBeTruthy(); + expect(inputUsername.nativeElement.value).toBeFalsy(); + expect(inputEmail.nativeElement.value).toBeFalsy(); + expect(inputPassword.nativeElement.value).toBeFalsy(); + }); + + it('should display the register button', () => { + const el = fixture.debugElement.query(By.css('button')).nativeElement; + expect(el).toBeTruthy(); + expect(el.textContent).toContain('Register'); + expect(el.disabled).toBeTruthy(); + }); });
90eda86b1dc5549355c2a5998ef8252000b6022c
home/components/UserSettingsButton.tsx
home/components/UserSettingsButton.tsx
import Ionicons from '@expo/vector-icons/build/Ionicons'; import { useNavigation, useTheme } from '@react-navigation/native'; import * as React from 'react'; import { Platform, StyleSheet, Text, TouchableOpacity } from 'react-native'; import onlyIfAuthenticated from '../utils/onlyIfAuthenticated'; function UserSettingsButton() { const theme = useTheme(); const navigation = useNavigation(); const onPress = () => { navigation.navigate('UserSettings'); }; return ( <TouchableOpacity style={styles.buttonContainer} onPress={onPress}> {Platform.select({ ios: <Text style={{ fontSize: 17, color: theme.colors.primary }}>Options</Text>, android: <Ionicons name="md-settings" size={27} color={theme.colors.text} />, })} </TouchableOpacity> ); } export default onlyIfAuthenticated(UserSettingsButton); const styles = StyleSheet.create({ loadingContainer: { flex: 1, }, buttonContainer: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingRight: 15, }, });
import Ionicons from '@expo/vector-icons/build/Ionicons'; import { useNavigation, useTheme } from '@react-navigation/native'; import * as React from 'react'; import { Platform, StyleSheet, Text, TouchableOpacity } from 'react-native'; import onlyIfAuthenticated from '../utils/onlyIfAuthenticated'; function UserSettingsButton() { const theme = useTheme(); const navigation = useNavigation(); const onPress = () => { navigation.navigate('UserSettings'); }; return ( <TouchableOpacity style={styles.buttonContainer} onPress={onPress}> {Platform.select({ ios: <Text style={{ fontSize: 17, color: theme.colors.primary }}>Options</Text>, android: <Ionicons name="md-settings-sharp" size={24} color={theme.colors.text} />, })} </TouchableOpacity> ); } export default onlyIfAuthenticated(UserSettingsButton); const styles = StyleSheet.create({ loadingContainer: { flex: 1, }, buttonContainer: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingRight: 15, }, });
Make settings button a bit smaller and better icon
[home] Make settings button a bit smaller and better icon
TypeScript
bsd-3-clause
exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent
--- +++ @@ -16,7 +16,7 @@ <TouchableOpacity style={styles.buttonContainer} onPress={onPress}> {Platform.select({ ios: <Text style={{ fontSize: 17, color: theme.colors.primary }}>Options</Text>, - android: <Ionicons name="md-settings" size={27} color={theme.colors.text} />, + android: <Ionicons name="md-settings-sharp" size={24} color={theme.colors.text} />, })} </TouchableOpacity> );
cba84223b4544b93f619113d96e749bd6b58368c
AngularBasic/webpack.config.ts
AngularBasic/webpack.config.ts
import { AngularCompilerPlugin } from "@ngtools/webpack"; import * as path from "path"; import { Configuration, DllReferencePlugin } from "webpack"; import * as webpackMerge from "webpack-merge"; import { isAOT, isProd, outputDir, WebpackCommonConfig } from "./webpack.config.common"; module.exports = (env: any) => { const prod = isProd(env); const aot = isAOT(env); const bundleConfig: Configuration = webpackMerge(WebpackCommonConfig(env, "main"), { entry: { app: [ "./ClientApp/main.ts", "./ClientApp/styles/main.scss", ], }, plugins: (prod ? [] : [ // AOT chunk splitting does not work while this is active https://github.com/angular/angular-cli/issues/4565 new DllReferencePlugin({ context: __dirname, manifest: require(path.join(__dirname, outputDir, "vendor-manifest.json")), }), ]).concat(aot ? [ new AngularCompilerPlugin({ mainPath: "./ClientApp/main.ts", tsConfigPath: "./tsconfig.json", skipCodeGeneration: false, compilerOptions: { noEmit: false, }, }), ] : []), }); return bundleConfig; };
import { AngularCompilerPlugin } from "@ngtools/webpack"; import * as path from "path"; import { Configuration, DllReferencePlugin } from "webpack"; import * as webpackMerge from "webpack-merge"; import { isAOT, isProd, outputDir, WebpackCommonConfig } from "./webpack.config.common"; module.exports = (env: any) => { const prod = isProd(env); const aot = isAOT(env); if (!prod && aot) { console.warn("Vendor dll bundle will not be used as AOT is enabled"); } const bundleConfig: Configuration = webpackMerge(WebpackCommonConfig(env, "main"), { entry: { app: [ "./ClientApp/main.ts", "./ClientApp/styles/main.scss", ], }, plugins: (prod || aot ? [] : [ // AOT chunk splitting does not work while this is active https://github.com/angular/angular-cli/issues/4565 new DllReferencePlugin({ context: __dirname, manifest: require(path.join(__dirname, outputDir, "vendor-manifest.json")), }), ]).concat(aot ? [ new AngularCompilerPlugin({ mainPath: "./ClientApp/main.ts", tsConfigPath: "./tsconfig.json", skipCodeGeneration: false, compilerOptions: { noEmit: false, }, }), ] : []), }); return bundleConfig; };
Add warning when trying to use dev + aot that vendor bundle will not be used
Add warning when trying to use dev + aot that vendor bundle will not be used
TypeScript
mit
MattJeanes/AngularBasic,MattJeanes/AngularBasic,MattJeanes/AngularBasic,MattJeanes/AngularBasic
--- +++ @@ -8,6 +8,7 @@ module.exports = (env: any) => { const prod = isProd(env); const aot = isAOT(env); + if (!prod && aot) { console.warn("Vendor dll bundle will not be used as AOT is enabled"); } const bundleConfig: Configuration = webpackMerge(WebpackCommonConfig(env, "main"), { entry: { app: [ @@ -15,7 +16,7 @@ "./ClientApp/styles/main.scss", ], }, - plugins: (prod ? [] : [ + plugins: (prod || aot ? [] : [ // AOT chunk splitting does not work while this is active https://github.com/angular/angular-cli/issues/4565 new DllReferencePlugin({ context: __dirname,
bac27f64e1472eff96191f3f36ea11ffa4261c7a
packages/react-day-picker/src/components/Day/utils/createTabIndex.ts
packages/react-day-picker/src/components/Day/utils/createTabIndex.ts
import { isSameDay, isSameMonth } from 'date-fns'; import { DayPickerProps, ModifiersStatus } from '../../../types'; export function createTabIndex( day: Date, modifiers: ModifiersStatus, props: DayPickerProps ): number | undefined { if (!modifiers.interactive) return; let tabIndex: number; if (props.focusedDay && isSameDay(day, props.focusedDay)) { tabIndex = 0; } else if (isSameDay(day, new Date())) { tabIndex = 0; } else if ( !isSameDay(day, new Date()) && !isSameMonth(day, new Date()) && day.getDate() === 1 ) { tabIndex = 0; } else { tabIndex = -1; } return tabIndex; }
import { isSameDay, isSameMonth } from 'date-fns'; import { DayPickerProps, ModifiersStatus } from '../../../types'; export function createTabIndex( day: Date, modifiers: ModifiersStatus, props: DayPickerProps ): number | undefined { let tabIndex: number; if (props.focusedDay && isSameDay(day, props.focusedDay)) { tabIndex = 0; } else if (isSameMonth(day, props.month) && day.getDate() === 1) { tabIndex = 0; } else { tabIndex = -1; } return tabIndex; }
Fix tabIndex not being set correctly
Fix tabIndex not being set correctly
TypeScript
mit
gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker
--- +++ @@ -6,22 +6,13 @@ modifiers: ModifiersStatus, props: DayPickerProps ): number | undefined { - if (!modifiers.interactive) return; - let tabIndex: number; if (props.focusedDay && isSameDay(day, props.focusedDay)) { tabIndex = 0; - } else if (isSameDay(day, new Date())) { - tabIndex = 0; - } else if ( - !isSameDay(day, new Date()) && - !isSameMonth(day, new Date()) && - day.getDate() === 1 - ) { + } else if (isSameMonth(day, props.month) && day.getDate() === 1) { tabIndex = 0; } else { tabIndex = -1; } - return tabIndex; }
e2c912c8ec1fad987caa7a74b719ea355ca28be2
src/Utils/logger.ts
src/Utils/logger.ts
import { head } from "lodash" import { isErrorInfo, sendErrorToService } from "Utils/errors" export const shouldCaptureError = (environment: string) => environment === "staging" || environment === "production" export default function createLogger(namespace = "reaction") { const formattedNamespace = `${namespace} |` return { log: (...messages) => { console.log(formattedNamespace, ...messages, "\n") }, warn: (...warnings) => { console.warn(formattedNamespace, ...warnings, "\n") }, error: (...errors) => { const error = head(errors.filter(e => e instanceof Error)) const errorInfo = head(errors.filter(e => isErrorInfo(e))) if (error && shouldCaptureError(process.env.NODE_ENV)) { sendErrorToService(error, errorInfo) } console.error(formattedNamespace, ...errors, "\n") }, } }
import { isErrorInfo, sendErrorToService } from "Utils/errors" export const shouldCaptureError = (environment: string) => environment === "staging" || environment === "production" export default function createLogger(namespace = "reaction") { const formattedNamespace = `${namespace} |` return { log: (...messages) => { console.log(formattedNamespace, ...messages, "\n") }, warn: (...warnings) => { console.warn(formattedNamespace, ...warnings, "\n") }, error: (...errors) => { const error = errors.find(e => e instanceof Error) const errorInfo = errors.find(isErrorInfo) if (error && shouldCaptureError(process.env.NODE_ENV)) { sendErrorToService(error, errorInfo) } console.error(formattedNamespace, ...errors, "\n") }, } }
Use Array.find when searching for errors and errorInfO
Use Array.find when searching for errors and errorInfO
TypeScript
mit
artsy/reaction-force,xtina-starr/reaction,artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction
--- +++ @@ -1,4 +1,3 @@ -import { head } from "lodash" import { isErrorInfo, sendErrorToService } from "Utils/errors" export const shouldCaptureError = (environment: string) => @@ -15,8 +14,8 @@ console.warn(formattedNamespace, ...warnings, "\n") }, error: (...errors) => { - const error = head(errors.filter(e => e instanceof Error)) - const errorInfo = head(errors.filter(e => isErrorInfo(e))) + const error = errors.find(e => e instanceof Error) + const errorInfo = errors.find(isErrorInfo) if (error && shouldCaptureError(process.env.NODE_ENV)) { sendErrorToService(error, errorInfo)
dba36410c91ca38704806e25c0b7684e318b6e17
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', () => { let mustFunction = function func () { return false; }; let law = new MustLaw(mustFunction); expect(law.getName()).to.be('must'); }); }); describe('verdict', () => { it('should call into function', () => { let functionCalled = false; let mustFunction = function func () { functionCalled = true; return false; }; let law = new MustLaw(mustFunction); law.verdict('a'); expect(functionCalled).to.be(true); }); it('should call into function with given string [test case 1]', () => { let givenString = 'i am a string'; let functionCalled = false; let mustFunction = function func (str: string) { if (str === givenString) { functionCalled = true; } return false; }; let law = new MustLaw(mustFunction); law.verdict(givenString); expect(functionCalled).to.be(true); }); }); });
///<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', () => { let mustFunction = function func () { return false; }; let law = new MustLaw(mustFunction); expect(law.getName()).to.be('must'); }); }); describe('verdict', () => { it('should call into function', () => { let functionCalled = false; let mustFunction = function func () { functionCalled = true; return false; }; let law = new MustLaw(mustFunction); law.verdict('a'); expect(functionCalled).to.be(true); }); it('should call into function with given string [test case 1]', () => { let givenString = 'i am a string'; let functionCalled = false; let mustFunction = function func (str: string) { if (str === givenString) { functionCalled = true; } return false; }; let law = new MustLaw(mustFunction); law.verdict(givenString); expect(functionCalled).to.be(true); }); it('should call into function with given string [test case 2]', () => { let givenString = 'a string, that is what i am, and what i always will be'; let functionCalled = false; let mustFunction = function func (str: string) { if (str === givenString) { functionCalled = true; } return false; }; let law = new MustLaw(mustFunction); law.verdict(givenString); expect(functionCalled).to.be(true); }); }); });
Test case 2 for string value
Test case 2 for string value
TypeScript
mit
Jameskmonger/courtroom,Jameskmonger/courtroom
--- +++ @@ -51,6 +51,24 @@ expect(functionCalled).to.be(true); }); + it('should call into function with given string [test case 2]', () => { + let givenString = 'a string, that is what i am, and what i always will be'; + + let functionCalled = false; + let mustFunction = function func (str: string) { + if (str === givenString) { + functionCalled = true; + } + + return false; + }; + + let law = new MustLaw(mustFunction); + law.verdict(givenString); + + expect(functionCalled).to.be(true); + }); + }); });
d59e2d17cea0110262b72397fe4d25b253e53de7
src/models/BaseModel.ts
src/models/BaseModel.ts
import { SequelizeDB } from '../libs/SequelizeDB'; import * as Sequelize from 'sequelize'; /** * @author Humberto Machado */ export abstract class BaseModel<ModelAttributes extends SequelizeBaseModelAttr> { //Sequelize Model native instance. @see http://docs.sequelizejs.com/en/latest/docs/models-usage/ protected model: Sequelize.Model<ModelAttributes, ModelAttributes>; protected name: string; protected definition: Sequelize.DefineAttributes; public getModelName(): string { return this.name; } public defineModel(sequelize: Sequelize.Sequelize): BaseModel<ModelAttributes> { this.model = sequelize.define<ModelAttributes, ModelAttributes>(this.getModelName(), this.definition, {}); return this; } public associate(sequelizeDB: SequelizeDB): void { //Hook Method } public configure(sequelizeDB: SequelizeDB) { //Hook Method } public getInstance(): Sequelize.Model<ModelAttributes, ModelAttributes> { return this.model; } } export var DataTypes: Sequelize.DataTypes = Sequelize; export interface SequelizeBaseModelAttr extends Sequelize.Instance<SequelizeBaseModelAttr> { id: number }
import { SequelizeDB } from '../libs/SequelizeDB'; import * as Sequelize from 'sequelize'; /** * @author Humberto Machado */ export abstract class BaseModel<ModelAttributes extends SequelizeBaseModelAttr> { //Sequelize Model native instance. @see http://docs.sequelizejs.com/en/latest/docs/models-usage/ protected model: Sequelize.Model<ModelAttributes, ModelAttributes>; protected name: string; protected definition: Sequelize.DefineAttributes; public getModelName(): string { return this.name; } public defineModel(sequelize: Sequelize.Sequelize): BaseModel<ModelAttributes> { this.model = sequelize.define<ModelAttributes, ModelAttributes>(this.getModelName(), this.definition, {}); return this; } public associate(sequelizeDB: SequelizeDB): void { //Hook Method } public configure(sequelizeDB: SequelizeDB) { //Hook Method } public getInstance(): Sequelize.Model<ModelAttributes, ModelAttributes> { return this.model; } } export var DataTypes: Sequelize.DataTypes = Sequelize; export interface SequelizeBaseModelAttr extends Sequelize.Instance<SequelizeBaseModelAttr> { id: number, created_at: Date, updated_at: Date }
Add new default fields. Add created_at and updated_at to model default attributes
Add new default fields. Add created_at and updated_at to model default attributes
TypeScript
mit
linck/protontype
--- +++ @@ -35,5 +35,7 @@ export var DataTypes: Sequelize.DataTypes = Sequelize; export interface SequelizeBaseModelAttr extends Sequelize.Instance<SequelizeBaseModelAttr> { - id: number + id: number, + created_at: Date, + updated_at: Date }
b3700b2e99af6c24a58330885c3767ec6c541a78
WebUtils/src/ts/WebUtils/LabKey.ts
WebUtils/src/ts/WebUtils/LabKey.ts
declare const LABKEY: { CSRF: string, ActionURL: any, getModuleContext(moduleName: string): any; }; export function getCSRF(): string { return LABKEY.CSRF || ""; } export function getCurrentController(): string { return LABKEY.ActionURL.getController(); } export function getCurrentContainer(): string { return LABKEY.ActionURL.getContainer(); } export function getBaseURL(): string { return LABKEY.ActionURL.getBaseURL(); } export function buildURL(controller: string, action: string, container: string): string { return LABKEY.ActionURL.buildURL(controller, action, container); } export function buildURLWithParams(controller: string, action: string, container: string, queryParams: {[name: string]: string}): string { return LABKEY.ActionURL.buildURL(controller, action, container, queryParams); } declare const __WebUtilsPageLoadData: any; export function getPageLoadData(): any { return __WebUtilsPageLoadData; } export function getModuleContext(moduleName: string): any { return LABKEY.getModuleContext(moduleName) || {}; }
declare const LABKEY: { CSRF: string, ActionURL: any, getModuleContext(moduleName: string): any; }; export function getCSRF(): string { return LABKEY.CSRF || ""; } export function getCurrentController(): string { return LABKEY.ActionURL.getController(); } export function getCurrentContainer(): string { return LABKEY.ActionURL.getContainer(); } export function getBaseURL(): string { return LABKEY.ActionURL.getBaseURL(); } export function buildURL(controller: string, action: string, container: string): string { return LABKEY.ActionURL.buildURL(controller, action, container); } export function buildURLWithParams(controller: string, action: string, container: string, queryParams: {[name: string]: string}): string { return LABKEY.ActionURL.buildURL(controller, action, container, queryParams); } declare const __WebUtilsPageLoadData: any; export function getPageLoadData(): any { return __WebUtilsPageLoadData; } export function getModuleContext(moduleName: string): any { return LABKEY.getModuleContext(moduleName) || {}; } export function getLinkToAnimal(id: string): string { return LABKEY.ActionURL.buildURL('ehr', 'participantView', null, {participantId: id}); }
Add method to get a link to an animal.
Add method to get a link to an animal.
TypeScript
apache-2.0
WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules
--- +++ @@ -37,3 +37,7 @@ export function getModuleContext(moduleName: string): any { return LABKEY.getModuleContext(moduleName) || {}; } + +export function getLinkToAnimal(id: string): string { + return LABKEY.ActionURL.buildURL('ehr', 'participantView', null, {participantId: id}); +}
99d223172d84a6bc5ece795d8b7fb4ea7d5ab283
src/plugins/autocompletion_providers/Cd.ts
src/plugins/autocompletion_providers/Cd.ts
import {expandHistoricalDirectory} from "../../shell/BuiltInCommands"; import {directoriesSuggestionsProvider, Suggestion} from "../autocompletion_utils/Common"; import * as _ from "lodash"; import {PluginManager} from "../../PluginManager"; PluginManager.registerAutocompletionProvider("cd", async(context) => { let suggestions: Suggestion[] = []; /** * Historical directories. */ if (context.argument.value.startsWith("-")) { const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] .slice(0, context.historicalPresentDirectoriesStack.size) .map(alias => ({ label: alias, detail: expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack), })); suggestions.push(...historicalDirectoryAliases); } if (context.argument.value.length > 0) { const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath .map(async(directory) => (await directoriesSuggestionsProvider(context, directory))))); suggestions.push(...cdpathDirectories); } return suggestions; });
// import {expandHistoricalDirectory} from "../../shell/BuiltInCommands"; import {directoriesSuggestionsProvider, Suggestion} from "../autocompletion_utils/Common"; // import * as _ from "lodash"; import {PluginManager} from "../../PluginManager"; PluginManager.registerAutocompletionProvider("cd", async(context) => { let suggestions: Suggestion[] = await directoriesSuggestionsProvider(context); // /** // * Historical directories. // */ // if (context.argument.value.startsWith("-")) { // const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] // .slice(0, context.historicalPresentDirectoriesStack.size) // .map(alias => ({ // label: alias, // detail: expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack), // })); // // suggestions.push(...historicalDirectoryAliases); // } // // if (context.argument.value.length > 0) { // const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath // .map(async(directory) => (await directoriesSuggestionsProvider(context, directory))))); // // suggestions.push(...cdpathDirectories); // } return suggestions; });
Fix `cd ` not showing directories.
Fix `cd ` not showing directories.
TypeScript
mit
railsware/upterm,vshatskyi/black-screen,black-screen/black-screen,shockone/black-screen,black-screen/black-screen,railsware/upterm,shockone/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,vshatskyi/black-screen,black-screen/black-screen
--- +++ @@ -1,31 +1,31 @@ -import {expandHistoricalDirectory} from "../../shell/BuiltInCommands"; +// import {expandHistoricalDirectory} from "../../shell/BuiltInCommands"; import {directoriesSuggestionsProvider, Suggestion} from "../autocompletion_utils/Common"; -import * as _ from "lodash"; +// import * as _ from "lodash"; import {PluginManager} from "../../PluginManager"; PluginManager.registerAutocompletionProvider("cd", async(context) => { - let suggestions: Suggestion[] = []; + let suggestions: Suggestion[] = await directoriesSuggestionsProvider(context); - /** - * Historical directories. - */ - if (context.argument.value.startsWith("-")) { - const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] - .slice(0, context.historicalPresentDirectoriesStack.size) - .map(alias => ({ - label: alias, - detail: expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack), - })); - - suggestions.push(...historicalDirectoryAliases); - } - - if (context.argument.value.length > 0) { - const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath - .map(async(directory) => (await directoriesSuggestionsProvider(context, directory))))); - - suggestions.push(...cdpathDirectories); - } + // /** + // * Historical directories. + // */ + // if (context.argument.value.startsWith("-")) { + // const historicalDirectoryAliases = ["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"] + // .slice(0, context.historicalPresentDirectoriesStack.size) + // .map(alias => ({ + // label: alias, + // detail: expandHistoricalDirectory(alias, context.historicalPresentDirectoriesStack), + // })); + // + // suggestions.push(...historicalDirectoryAliases); + // } + // + // if (context.argument.value.length > 0) { + // const cdpathDirectories = _.flatten(await Promise.all(context.environment.cdpath + // .map(async(directory) => (await directoriesSuggestionsProvider(context, directory))))); + // + // suggestions.push(...cdpathDirectories); + // } return suggestions; });
89c42acdf8ac0af854e81769fcfa7265d85e4ab5
packages/db/src/loaders/commands/names.ts
packages/db/src/loaders/commands/names.ts
import { generateProjectNameResolve, generateProjectNamesAssign } from "@truffle/db/loaders/resources/projects"; import { generateNameRecordsLoad } from "@truffle/db/loaders/resources/nameRecords"; import { toIdObject, WorkspaceRequest, WorkspaceResponse } from "@truffle/db/loaders/types"; /** * generator function to load nameRecords and project names into Truffle DB */ export function* generateNamesLoad( project: DataModel.IProject, contractsByCompilation: Array<DataModel.IContract[]> ): Generator<WorkspaceRequest, any, WorkspaceResponse<string>> { let getCurrent = function* (name, type) { return yield* generateProjectNameResolve(toIdObject(project), name, type); }; for (const contracts of contractsByCompilation) { const nameRecords = yield* generateNameRecordsLoad( contracts, "Contract", getCurrent ); yield* generateProjectNamesAssign(toIdObject(project), nameRecords); } }
import { generateProjectNameResolve, generateProjectNamesAssign } from "@truffle/db/loaders/resources/projects"; import { generateNameRecordsLoad } from "@truffle/db/loaders/resources/nameRecords"; import { WorkspaceRequest, WorkspaceResponse, IdObject } from "@truffle/db/loaders/types"; /** * generator function to load nameRecords and project names into Truffle DB */ export function* generateNamesLoad( project: IdObject<DataModel.IProject>, contractsByCompilation: Array<DataModel.IContract[]> ): Generator<WorkspaceRequest, any, WorkspaceResponse<string>> { let getCurrent = function* (name, type) { return yield* generateProjectNameResolve(project, name, type); }; for (const contracts of contractsByCompilation) { const nameRecords = yield* generateNameRecordsLoad( contracts, "Contract", getCurrent ); yield* generateProjectNamesAssign(project, nameRecords); } }
Rework project param to generateNamesLoad
Rework project param to generateNamesLoad
TypeScript
mit
ConsenSys/truffle
--- +++ @@ -5,20 +5,20 @@ import { generateNameRecordsLoad } from "@truffle/db/loaders/resources/nameRecords"; import { - toIdObject, WorkspaceRequest, - WorkspaceResponse + WorkspaceResponse, + IdObject } from "@truffle/db/loaders/types"; /** * generator function to load nameRecords and project names into Truffle DB */ export function* generateNamesLoad( - project: DataModel.IProject, + project: IdObject<DataModel.IProject>, contractsByCompilation: Array<DataModel.IContract[]> ): Generator<WorkspaceRequest, any, WorkspaceResponse<string>> { let getCurrent = function* (name, type) { - return yield* generateProjectNameResolve(toIdObject(project), name, type); + return yield* generateProjectNameResolve(project, name, type); }; for (const contracts of contractsByCompilation) { @@ -28,6 +28,6 @@ getCurrent ); - yield* generateProjectNamesAssign(toIdObject(project), nameRecords); + yield* generateProjectNamesAssign(project, nameRecords); } }
cc1576c64298827251052c9af9596cc54086faeb
src/app/shared/services/settings.service.ts
src/app/shared/services/settings.service.ts
import { BehaviorSubject } from "rxjs/BehaviorSubject"; import { Injectable } from "@angular/core"; @Injectable() export class SettingsService { public showToolsPanel$: BehaviorSubject<boolean> = new BehaviorSubject(false); public splitSelectionPanel$: BehaviorSubject<boolean> = new BehaviorSubject( true ); public alwaysShowFileDetails$: BehaviorSubject<boolean> = new BehaviorSubject( false ); public compactToolList$: BehaviorSubject<boolean> = new BehaviorSubject( false ); }
import { BehaviorSubject } from "rxjs/BehaviorSubject"; import { Injectable } from "@angular/core"; @Injectable() export class SettingsService { public showToolsPanel$: BehaviorSubject<boolean> = new BehaviorSubject(false); public splitSelectionPanel$: BehaviorSubject<boolean> = new BehaviorSubject( true ); public alwaysShowFileDetails$: BehaviorSubject<boolean> = new BehaviorSubject( false ); public compactToolList$: BehaviorSubject<boolean> = new BehaviorSubject(true); }
Make tool list compact by default
Make tool list compact by default
TypeScript
mit
chipster/chipster-web,chipster/chipster-web,chipster/chipster-web
--- +++ @@ -13,7 +13,5 @@ false ); - public compactToolList$: BehaviorSubject<boolean> = new BehaviorSubject( - false - ); + public compactToolList$: BehaviorSubject<boolean> = new BehaviorSubject(true); }