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 |
|---|---|---|---|---|---|---|---|---|---|---|
833ee9ec0195607d5c4f955a57db1f9034acc304 | core/src/index/get-fields-to-index.ts | core/src/index/get-fields-to-index.ts | import {Map} from 'tsfun';
import { Category } from '../model/category';
const defaultFieldsToIndex = ['identifier', 'shortDescription'];
export function getFieldsToIndex(categoriesMap: Map<Category>, categoryName: string): string[] {
return !categoriesMap[categoryName]
? []
: Category.getFields(categoriesMap[categoryName])
.filter(field => field.fulltextIndexed)
.map(field => field.name)
.concat(defaultFieldsToIndex);
}
| import { Map } from 'tsfun';
import { Category } from '../model/category';
const defaultFieldsToIndex = ['identifier', 'shortDescription'];
export function getFieldsToIndex(categoriesMap: Map<Category>, categoryName: string): string[] {
const fields = !categoriesMap[categoryName]
? []
: Category.getFields(categoriesMap[categoryName])
.filter(field => field.fulltextIndexed)
.map(field => field.name);
return fields.concat(defaultFieldsToIndex);
}
| Make sure default fields are always indexed | Make sure default fields are always indexed
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,4 +1,4 @@
-import {Map} from 'tsfun';
+import { Map } from 'tsfun';
import { Category } from '../model/category';
@@ -7,10 +7,10 @@
export function getFieldsToIndex(categoriesMap: Map<Category>, categoryName: string): string[] {
- return !categoriesMap[categoryName]
+ const fields = !categoriesMap[categoryName]
? []
: Category.getFields(categoriesMap[categoryName])
.filter(field => field.fulltextIndexed)
- .map(field => field.name)
- .concat(defaultFieldsToIndex);
+ .map(field => field.name);
+ return fields.concat(defaultFieldsToIndex);
} |
b106e240fe7b741e3398b0ad58958502295ab530 | source/lib/course-search/parse-term.ts | source/lib/course-search/parse-term.ts | export function parseTerm(term: string) {
const semester = term.slice(-1)
const year = term.slice(0, -1)
const currentYear = parseInt(year)
const nextYear = (currentYear + 1).toString().slice(-2)
switch (semester) {
case '0':
return `Abroad ${currentYear}/${nextYear}`
case '1':
return `Fall ${currentYear}/${nextYear}`
case '2':
return `Interim ${currentYear}/${nextYear}`
case '3':
return `Spring ${currentYear}/${nextYear}`
case '4':
return `Summer Term 1 ${currentYear}/${nextYear}`
case '5':
return `Summer Term 2 ${currentYear}/${nextYear}`
case '9':
return `Non-St. Olaf ${currentYear}/${nextYear}`
default:
return 'Unknown term'
}
}
| export function parseTerm(term: string): string {
const semester = term.slice(-1)
const year = term.slice(0, -1)
const currentYear = parseInt(year)
const nextYear = (currentYear + 1).toString().slice(-2)
switch (semester) {
case '0':
return `Abroad ${currentYear}/${nextYear}`
case '1':
return `Fall ${currentYear}/${nextYear}`
case '2':
return `Interim ${currentYear}/${nextYear}`
case '3':
return `Spring ${currentYear}/${nextYear}`
case '4':
return `Summer Term 1 ${currentYear}/${nextYear}`
case '5':
return `Summer Term 2 ${currentYear}/${nextYear}`
case '9':
return `Non-St. Olaf ${currentYear}/${nextYear}`
default:
return 'Unknown term'
}
}
| Add missing module boundary function return type | l/course-search: Add missing module boundary function return type
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
| TypeScript | agpl-3.0 | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | ---
+++
@@ -1,4 +1,4 @@
-export function parseTerm(term: string) {
+export function parseTerm(term: string): string {
const semester = term.slice(-1)
const year = term.slice(0, -1)
const currentYear = parseInt(year) |
53282161b11a88f7e1862224453f372396ea6960 | src/app/default-view.component.spec.ts | src/app/default-view.component.spec.ts | import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { DefaultViewComponent } from './default-view.component';
describe('Default View Component', () => {
let comp: DefaultViewComponent;
let fixture: ComponentFixture<DefaultViewComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DefaultViewComponent ], // declare the test component
}).compileComponents(); // compile template and css
}));
beforeEach(() => {
fixture = TestBed.createComponent(DefaultViewComponent);
comp = fixture.componentInstance; // DefaultViewComponent test instance
});
it('true should be true', () => {
expect(true).toBe(true);
});
});
| import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { DefaultViewComponent } from './default-view.component';
import { HeartButtonComponent } from './heart-button.component';
import { LizardMessageComponent } from './lizard-message.component';
describe('Default View Component', () => {
let comp: DefaultViewComponent;
let fixture: ComponentFixture<DefaultViewComponent>;
let de: DebugElement;
let el: HTMLElement;
beforeEach(async(() => {
let heartButtonStub = {};
let lizardMessageStub = {};
TestBed.configureTestingModule({
declarations: [
DefaultViewComponent,
HeartButtonComponent,
LizardMessageComponent
],
providers: [
{ provide: HeartButtonComponent, useValue: heartButtonStub },
{ provide: LizardMessageComponent, useValue: lizardMessageStub },
]
}).compileComponents(); // compile template and css
}));
beforeEach(() => {
fixture = TestBed.createComponent(DefaultViewComponent);
comp = fixture.componentInstance; // DefaultViewComponent test instance
});
it('true should be true', () => {
expect(true).toBe(true);
});
});
| Update Default View tests to stub new dependencies | Update Default View tests to stub new dependencies
| TypeScript | unlicense | codechaotic/lizard-love-ui,codechaotic/lizard-love-ui,codechaotic/lizard-love-ui | ---
+++
@@ -3,6 +3,8 @@
import { DebugElement } from '@angular/core';
import { DefaultViewComponent } from './default-view.component';
+import { HeartButtonComponent } from './heart-button.component';
+import { LizardMessageComponent } from './lizard-message.component';
describe('Default View Component', () => {
let comp: DefaultViewComponent;
@@ -12,8 +14,18 @@
beforeEach(async(() => {
+ let heartButtonStub = {};
+ let lizardMessageStub = {};
TestBed.configureTestingModule({
- declarations: [ DefaultViewComponent ], // declare the test component
+ declarations: [
+ DefaultViewComponent,
+ HeartButtonComponent,
+ LizardMessageComponent
+ ],
+ providers: [
+ { provide: HeartButtonComponent, useValue: heartButtonStub },
+ { provide: LizardMessageComponent, useValue: lizardMessageStub },
+ ]
}).compileComponents(); // compile template and css
}));
|
ea4808039c22b54cd83f381b5cf701e157522f2f | src/app/pages/login/login.component.ts | src/app/pages/login/login.component.ts | import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthorizationService } from '../../shared/authorization.service';
import { UserService } from '../../shared/user.service';
@Component({
selector: 'login',
styleUrls: [ './login.scss' ],
templateUrl: './login.html'
})
export class LoginComponent {
public username: string;
public password: string;
public isLoginDataIncorrect: boolean = false;
constructor(
private authorizationService: AuthorizationService,
private userService: UserService,
private router: Router
) {}
public logIn(): void {
this.isLoginDataIncorrect = false;
this.authorizationService
.logIn(this.username, this.password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
}
private onLoginSuccess(): void {
this.userService.getUserInfo();
this.router.navigate([ '/' ]);
}
private onLoginFail(): void {
this.isLoginDataIncorrect = true;
}
}
| import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AuthorizationService } from '../../shared/authorization.service';
import { UserService } from '../../shared/user.service';
@Component({
selector: 'login',
styleUrls: [ './login.scss' ],
templateUrl: './login.html'
})
export class LoginComponent {
public username: string;
public password: string;
public isLoginDataIncorrect: boolean = false;
constructor(
private authorizationService: AuthorizationService,
private userService: UserService,
private router: Router
) {}
public logIn(): void {
this.isLoginDataIncorrect = false;
this.authorizationService
.logIn(this.username, this.password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
}
private onLoginSuccess(): void {
this.userService.getUserInfo();
this.router.navigate([ '/' ]);
}
private onLoginFail(): void {
this.isLoginDataIncorrect = true;
this.password = '';
}
}
| Add clearing password field on login fail | Add clearing password field on login fail
| TypeScript | mit | yusk90/courses-app,yusk90/courses-app,yusk90/courses-app | ---
+++
@@ -1,4 +1,4 @@
-import { Component } from '@angular/core';
+import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AuthorizationService } from '../../shared/authorization.service';
@@ -36,5 +36,6 @@
private onLoginFail(): void {
this.isLoginDataIncorrect = true;
+ this.password = '';
}
} |
094c5e0a4d63cae28a8befe61fca5b282481beae | src/app/public/ts/profile.component.ts | src/app/public/ts/profile.component.ts | import { ActivatedRoute } from '@angular/router'
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Socket } from '../../../services/socketio.service';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { User } from '../../../services/user.service';
@Component({
templateUrl: '../html/profile.component.html'
})
export class ProfileComponent implements OnInit, OnDestroy {
public id: any;
public profile: any;
private subPlayer:any;
private subTitle:any;
constructor(private http: HttpClient, public user: User,
private route: ActivatedRoute, public translate: TranslateService,
private titleService: Title, private socket: Socket) {
this.profile = {
'username': ''
}
}
ngOnInit() {
let userId = this.route.snapshot.paramMap.get('id');
let url = this.socket.url+'/api/playerProfile/'+userId+'.json';
this.subPlayer = this.http.get(url).subscribe((player:any) => {
if(player && player.membre_id) {
this.profile = player;
this.subTitle = this.translate.get('Player profile:').subscribe((res: string) => {
this.titleService.setTitle(res+player.username);
});
}
});
}
ngOnDestroy() {
this.subPlayer.unsubscribe();
if(this.subTitle) {
this.subTitle.unsubscribe();
}
}
}
| import { ActivatedRoute } from '@angular/router'
import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Socket } from '../../../services/socketio.service';
import { Title } from '@angular/platform-browser';
import { TranslateService } from '@ngx-translate/core';
import { User } from '../../../services/user.service';
@Component({
templateUrl: '../html/profile.component.html'
})
export class ProfileComponent implements OnInit, OnDestroy {
public id: any;
public profile: any;
private subPlayer:any;
private subTitle:any;
constructor(private http: HttpClient, public user: User,
private route: ActivatedRoute, public translate: TranslateService,
private titleService: Title, private socket: Socket) {
this.profile = {
'username': ''
}
}
ngOnInit() {
let userId = this.route.snapshot.paramMap.get('id');
let url = this.socket.url+'/api/playerProfile/'+userId+'.json';
this.subPlayer = this.http.get(url).subscribe((player:any) => {
if(player && player.membre_id) {
this.profile = player;
this.subTitle = this.translate.get('Player profile:').subscribe((res: string) => {
this.titleService.setTitle(res+' '+player.username);
});
}
});
}
ngOnDestroy() {
this.subPlayer.unsubscribe();
if(this.subTitle) {
this.subTitle.unsubscribe();
}
}
}
| Fix a typo in the profile's title | Fix a typo in the profile's title | TypeScript | agpl-3.0 | V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War,V-Paranoiaque/Ellas-War | ---
+++
@@ -34,7 +34,7 @@
this.profile = player;
this.subTitle = this.translate.get('Player profile:').subscribe((res: string) => {
- this.titleService.setTitle(res+player.username);
+ this.titleService.setTitle(res+' '+player.username);
});
}
}); |
d84140fb87e186637763cbc2949182160e51bd5e | types/koa-bodyparser/koa-bodyparser-tests.ts | types/koa-bodyparser/koa-bodyparser-tests.ts | import * as Koa from "koa";
import bodyParser = require("koa-bodyparser");
const app = new Koa();
app.use(bodyParser({ strict: false }));
app.listen(80) | import * as Koa from "koa";
import * as bodyParser from "koa-bodyparser";
const app = new Koa();
app.use(bodyParser({ strict: false }));
app.listen(80) | Use same import style for dependencies | Use same import style for dependencies
| TypeScript | mit | magny/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,jimthedev/DefinitelyTyped,one-pieces/DefinitelyTyped,zuzusik/DefinitelyTyped,jimthedev/DefinitelyTyped,rolandzwaga/DefinitelyTyped,arusakov/DefinitelyTyped,borisyankov/DefinitelyTyped,mcliment/DefinitelyTyped,AgentME/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,arusakov/DefinitelyTyped,nycdotnet/DefinitelyTyped,alexdresko/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,zuzusik/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,abbasmhd/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,benishouga/DefinitelyTyped,arusakov/DefinitelyTyped,georgemarshall/DefinitelyTyped,benishouga/DefinitelyTyped,chrootsu/DefinitelyTyped,aciccarello/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,nycdotnet/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,abbasmhd/DefinitelyTyped,magny/DefinitelyTyped,jimthedev/DefinitelyTyped,zuzusik/DefinitelyTyped,alexdresko/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,chrootsu/DefinitelyTyped,georgemarshall/DefinitelyTyped,benliddicott/DefinitelyTyped | ---
+++
@@ -1,5 +1,5 @@
import * as Koa from "koa";
-import bodyParser = require("koa-bodyparser");
+import * as bodyParser from "koa-bodyparser";
const app = new Koa();
|
6e0bdb2c7ade7c96be8357418736fb39986f49fb | app/src/container/Books.tsx | app/src/container/Books.tsx | import * as React from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { IBook } from "../lib/books";
import "./style/Books.css";
interface IProps {
books: IBook[];
signedIn: boolean;
}
class Books extends React.Component<IProps> {
public render() {
if (!this.props.signedIn) {
return <Redirect to="/sign-in" />;
}
return (
<div className="Books-container">
{JSON.stringify(this.props.books)}
</div>
);
}
}
export default connect(
({ authState, books }) => ({ ...authState, ...books }),
{},
)(Books);
| import * as React from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { IBook } from "../lib/books";
import Page from "./Page";
import "./style/Books.css";
interface IProps {
books: IBook[];
signedIn: boolean;
}
class Books extends React.Component<IProps> {
public render() {
return (
<Page {...{ menu: false }}>
{JSON.stringify(this.props.books)}
</Page>
);
}
}
export default connect(({ books }) => books)(Books);
| Use Page component in books page | Use Page component in books page
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -3,6 +3,7 @@
import { Redirect } from "react-router-dom";
import { IBook } from "../lib/books";
+import Page from "./Page";
import "./style/Books.css";
interface IProps {
@@ -12,19 +13,12 @@
class Books extends React.Component<IProps> {
public render() {
- if (!this.props.signedIn) {
- return <Redirect to="/sign-in" />;
- }
-
return (
- <div className="Books-container">
+ <Page {...{ menu: false }}>
{JSON.stringify(this.props.books)}
- </div>
+ </Page>
);
}
}
-export default connect(
- ({ authState, books }) => ({ ...authState, ...books }),
- {},
-)(Books);
+export default connect(({ books }) => books)(Books); |
78d6266254e25101950cadce62ad70f7285ebb3b | src/components/__tests__/Navbar.spec.tsx | src/components/__tests__/Navbar.spec.tsx | import * as React from 'react'
import { Button } from '@blueprintjs/core'
import { shallow, mount } from 'enzyme'
import { INavbarProps, Navbar } from '../Navbar'
describe('Navbar', () => {
const mockProps: INavbarProps = {
isSidebarToggled: true,
toggleSidebar: () => {return}
}
it('renders the correct id', () => {
const navbar = shallow(<Navbar {...mockProps} />)
expect(navbar.props().id).toBe('rs-navbar')
})
it('renders the sidebar toggle button and submit button', () => {
const navbar = shallow(<Navbar {...mockProps} />)
expect(navbar.find('#rs-submit').length).toBe(1)
expect(navbar.find('#rs-toggle-sidebar').length).toBe(1)
})
it('renders the sidebar toggle button as active/inactive', () => {
const navbar1 = mount(<Navbar {...mockProps} />)
expect(navbar1.find('#rs-toggle-sidebar')
.hasClass('pt-icon-one-column')).toBe(true)
const mockProps2 = Object.assign({}, mockProps, {
isSidebarToggled: false
})
const navbar2 = mount(<Navbar {...mockProps2} />)
expect(navbar2.find('#rs-toggle-sidebar')
.hasClass('pt-icon-two-columns')).toBe(true)
})
})
| import * as React from 'react'
import { Button } from '@blueprintjs/core'
import { mount, shallow } from 'enzyme'
import { INavbarProps, Navbar } from '../Navbar'
describe('Navbar', () => {
const toggleSidebar = jest.fn()
const mockProps: INavbarProps = {
isSidebarToggled: true,
toggleSidebar
}
it('renders the correct id', () => {
const navbar = shallow(<Navbar {...mockProps} />)
expect(navbar.props().id).toBe('rs-navbar')
})
it('renders the sidebar toggle button and submit button', () => {
const navbar = shallow(<Navbar {...mockProps} />)
expect(navbar.find('#rs-submit').length).toBe(1)
expect(navbar.find('#rs-toggle-sidebar').length).toBe(1)
})
it('calls toggle sidebar when clicked', () => {
const navbar1 = shallow(<Navbar {...mockProps} />)
navbar1.find('#rs-toggle-sidebar').simulate('click')
expect(toggleSidebar.mock.calls.length).toBe(1)
})
it('renders the sidebar toggle button as active/inactive', () => {
const navbar1 = mount(<Navbar {...mockProps} />)
expect(navbar1.find('#rs-toggle-sidebar')
.hasClass('pt-icon-one-column')).toBe(true)
const mockProps2 = Object.assign({}, mockProps, {
isSidebarToggled: false
})
const navbar2 = mount(<Navbar {...mockProps2} />)
expect(navbar2.find('#rs-toggle-sidebar')
.hasClass('pt-icon-two-columns')).toBe(true)
})
})
| Test toggle sidebar button click | Test toggle sidebar button click
| TypeScript | mit | respace-js/respace,respace-js/respace,evansb/respace,evansb/respace,evansb/respace | ---
+++
@@ -1,13 +1,14 @@
import * as React from 'react'
import { Button } from '@blueprintjs/core'
-import { shallow, mount } from 'enzyme'
+import { mount, shallow } from 'enzyme'
import { INavbarProps, Navbar } from '../Navbar'
describe('Navbar', () => {
+ const toggleSidebar = jest.fn()
const mockProps: INavbarProps = {
isSidebarToggled: true,
- toggleSidebar: () => {return}
+ toggleSidebar
}
it('renders the correct id', () => {
@@ -19,6 +20,12 @@
const navbar = shallow(<Navbar {...mockProps} />)
expect(navbar.find('#rs-submit').length).toBe(1)
expect(navbar.find('#rs-toggle-sidebar').length).toBe(1)
+ })
+
+ it('calls toggle sidebar when clicked', () => {
+ const navbar1 = shallow(<Navbar {...mockProps} />)
+ navbar1.find('#rs-toggle-sidebar').simulate('click')
+ expect(toggleSidebar.mock.calls.length).toBe(1)
})
it('renders the sidebar toggle button as active/inactive', () => { |
ca9a604192c2435c9ae6add938c81a6670fae26d | app/src/ui/lib/bytes.ts | app/src/ui/lib/bytes.ts | import { round } from './round'
/**
* Number sign display mode
*/
export const enum Sign {
Normal,
Forced,
}
/**
* Display bytes in human readable format like:
* 23 GiB
* -43 B
* It's also possible to force sign in order to get the
* plus sign in case of positive numbers like:
* +23 GiB
* -43 B
*/
export const formatBytes = (
bytes: number,
signType: Sign = Sign.Normal,
decimals = 0
) => {
if (!Number.isFinite(bytes)) {
return 'Unknown'
}
const sizes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
const sizeIndex = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024))
const sign = signType === Sign.Forced && bytes > 0 ? '+' : ''
const value = round(bytes / Math.pow(1024, sizeIndex), decimals)
return `${sign}${value} ${sizes[sizeIndex]}`
}
| import { round } from './round'
/**
* Number sign display mode
*/
export const enum Sign {
Normal,
Forced,
}
/**
* Display bytes in human readable format like:
* 23 GiB
* -43 B
* It's also possible to force sign in order to get the
* plus sign in case of positive numbers like:
* +23 GiB
* -43 B
*/
export function formatBytes(
bytes: number,
signType: Sign = Sign.Normal,
decimals = 0
) {
if (!Number.isFinite(bytes)) {
return 'Unknown'
}
const sizes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
const sizeIndex = Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024))
const sign = signType === Sign.Forced && bytes > 0 ? '+' : ''
const value = round(bytes / Math.pow(1024, sizeIndex), decimals)
return `${sign}${value} ${sizes[sizeIndex]}`
}
| Use a good ol' regular function | Use a good ol' regular function
| TypeScript | mit | shiftkey/desktop,say25/desktop,say25/desktop,shiftkey/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,kactus-io/kactus,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop | ---
+++
@@ -17,11 +17,11 @@
* +23 GiB
* -43 B
*/
-export const formatBytes = (
+export function formatBytes(
bytes: number,
signType: Sign = Sign.Normal,
decimals = 0
-) => {
+) {
if (!Number.isFinite(bytes)) {
return 'Unknown'
} |
bfa7e87bd41973a941c9e4d354062ee498ad6395 | packages/skin-database/api/server.ts | packages/skin-database/api/server.ts | // import Sentry from "@sentry/node";
import { createApp } from "./app";
import DiscordEventHandler from "./DiscordEventHandler";
const port = process.env.PORT ? Number(process.env.PORT) : 3001;
const handler = new DiscordEventHandler();
// GO!
const app = createApp({
eventHandler: (action) => handler.handle(action),
logger: {
log: (message, context) => console.log(message, context),
logError: (message, context) => console.error(message, context),
},
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
// Initialize Sentry after we start listening. Any crash at start time will appear in the console and we'll notice.
/*
Sentry.init({
dsn:
"https://0e6bc841b4f744b2953a1fe5981effe6@o68382.ingest.sentry.io/5508241",
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});
*/
| // import Sentry from "@sentry/node";
import { createApp } from "./app";
import DiscordEventHandler from "./DiscordEventHandler";
const port = process.env.PORT ? Number(process.env.PORT) : 3001;
const handler = new DiscordEventHandler();
// GO!
const app = createApp({
eventHandler: (action) => handler.handle(action),
logger: {
log: (message, context) => console.log(message, context),
logError: (message, context) => console.error(message, context),
},
});
app.listen(port, () =>
console.log(`Example app listening on http://localhost:${port}!`)
);
// Initialize Sentry after we start listening. Any crash at start time will appear in the console and we'll notice.
/*
Sentry.init({
dsn:
"https://0e6bc841b4f744b2953a1fe5981effe6@o68382.ingest.sentry.io/5508241",
// We recommend adjusting this value in production, or using tracesSampler
// for finer control
tracesSampleRate: 1.0,
});
*/
| Improve message to include link | Improve message to include link
| TypeScript | mit | captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js | ---
+++
@@ -14,7 +14,9 @@
logError: (message, context) => console.error(message, context),
},
});
-app.listen(port, () => console.log(`Example app listening on port ${port}!`));
+app.listen(port, () =>
+ console.log(`Example app listening on http://localhost:${port}!`)
+);
// Initialize Sentry after we start listening. Any crash at start time will appear in the console and we'll notice.
/* |
c4757db1d8e9540e3386d49d9375dde1d1c924c6 | src/components/footer.ts | src/components/footer.ts | import Component from 'inferno-component'
import h from 'inferno-hyperscript'
interface Props {
clearCompleted: () => void
clearAll: () => void
leftCount: number
}
interface State {}
export default class Footer extends Component<Props, State> {
leftCountText(count: number): string {
if (count === 1) {
return `${count} item left`
} else {
return `${count} items left`
}
}
render() {
return h('div', [
h('span', this.leftCountText(this.props.leftCount)),
h('button', { onClick: this.props.clearCompleted }, 'Clear completed'),
h('button', { onClick: this.props.clearAll }, 'Clear lll')
])
}
}
| import Component from 'inferno-component'
import h from 'inferno-hyperscript'
interface Props {
clearCompleted: () => void
clearAll: () => void
leftCount: number
}
interface State {}
export default class Footer extends Component<Props, State> {
leftCountText(count: number): string {
if (count === 1) {
return `${count} item left`
} else {
return `${count} items left`
}
}
render() {
return h('div', [
h('span', this.leftCountText(this.props.leftCount)),
h('button', { onClick: this.props.clearCompleted }, 'Clear completed'),
h('button', { onClick: this.props.clearAll }, 'Clear all')
])
}
}
| Fix typo in Footer component | Fix typo in Footer component
| TypeScript | mit | y0za/typescript-inferno-todo,y0za/typescript-inferno-todo,y0za/typescript-inferno-todo | ---
+++
@@ -21,7 +21,7 @@
return h('div', [
h('span', this.leftCountText(this.props.leftCount)),
h('button', { onClick: this.props.clearCompleted }, 'Clear completed'),
- h('button', { onClick: this.props.clearAll }, 'Clear lll')
+ h('button', { onClick: this.props.clearAll }, 'Clear all')
])
}
} |
d1186c2b36645caa2e7b2087acc70f84d27ec6df | server/src/routes/api/v1/index.ts | server/src/routes/api/v1/index.ts | import { Request, Response, Router } from 'express';
import { ErrorResponse } from '../../../common/responses';
import { RouteModule } from '../../RouteModule';
import { tables } from './tables';
export function v1(): RouteModule {
const router = Router();
const modules: Array<() => RouteModule> = [
tables
];
for (const m of modules) {
const mod = m();
// Install each RouteModule at its requested relative path
router.use(mod.mountPoint, mod.router);
}
// Catch all requests to the API not handled by an API module to ensure the
// client still receives JSON data
router.get('/*', (req: Request, res: Response) => {
const resp: ErrorResponse = {
message: 'Not found',
input: {}
};
res.status(404).json(resp);
});
return {
mountPoint: '/v1',
router
};
}
| import { Request, Response, Router } from 'express';
import { ErrorResponse } from '../../../common/responses';
import { RouteModule } from '../../RouteModule';
import { tables } from './tables';
export function v1(): RouteModule {
const router = Router();
const modules: Array<() => RouteModule> = [
tables
];
for (const m of modules) {
const mod = m();
// Install each RouteModule at its requested relative path
router.use(mod.mountPoint, mod.router);
}
// Catch all requests to the API not handled by an API module to ensure the
// client still receives JSON data
router.get('/*', (req: Request, res: Response) => {
const resp: ErrorResponse = {
message: 'Route not found',
input: {}
};
res.status(404).json(resp);
});
return {
mountPoint: '/v1',
router
};
}
| Make sure the user knows why the API is returning a 404 | Make sure the user knows why the API is returning a 404
| TypeScript | mit | mattbdean/Helium,mattbdean/Helium,mattbdean/Helium,mattbdean/Helium | ---
+++
@@ -21,7 +21,7 @@
// client still receives JSON data
router.get('/*', (req: Request, res: Response) => {
const resp: ErrorResponse = {
- message: 'Not found',
+ message: 'Route not found',
input: {}
};
|
659f3133381751a79df39f62a80290e72ca6741f | src/openstack/OpenStackPluginOptionsForm.tsx | src/openstack/OpenStackPluginOptionsForm.tsx | import * as React from 'react';
import { FormContainer, SelectField } from '@waldur/form-react';
import { translate } from '@waldur/i18n';
export const OpenStackPluginOptionsForm = ({ container, locale }) => {
const STORAGE_MODE_OPTIONS = React.useMemo(
() => [
{
label: translate('Fixed — use common storage quota'),
value: 'fixed',
},
{
label: translate(
'Dynamic — use separate volume types for tracking pricing',
),
value: 'dynamic',
},
],
locale,
);
return (
<FormContainer {...container}>
<SelectField
name="storage_mode"
label={translate('Storage mode')}
options={STORAGE_MODE_OPTIONS}
simpleValue={true}
required={true}
description={translate(
'Offering needs to be saved before pricing for dynamic components could be set.',
)}
/>
</FormContainer>
);
};
| import * as React from 'react';
import { FormContainer, SelectField, NumberField } from '@waldur/form-react';
import { translate } from '@waldur/i18n';
export const OpenStackPluginOptionsForm = ({ container }) => {
const STORAGE_MODE_OPTIONS = React.useMemo(
() => [
{
label: translate('Fixed — use common storage quota'),
value: 'fixed',
},
{
label: translate(
'Dynamic — use separate volume types for tracking pricing',
),
value: 'dynamic',
},
],
[],
);
return (
<FormContainer {...container}>
<SelectField
name="storage_mode"
label={translate('Storage mode')}
options={STORAGE_MODE_OPTIONS}
simpleValue={true}
required={true}
description={translate(
'Offering needs to be saved before pricing for dynamic components could be set.',
)}
/>
<NumberField
name="snapshot_size_limit_gb"
label={translate('Snapshot size limit')}
unit="GB"
/>
</FormContainer>
);
};
| Introduce snapshot size limit as plugin option for OpenStack offering | Introduce snapshot size limit as plugin option for OpenStack offering [WAL-2936]
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -1,9 +1,9 @@
import * as React from 'react';
-import { FormContainer, SelectField } from '@waldur/form-react';
+import { FormContainer, SelectField, NumberField } from '@waldur/form-react';
import { translate } from '@waldur/i18n';
-export const OpenStackPluginOptionsForm = ({ container, locale }) => {
+export const OpenStackPluginOptionsForm = ({ container }) => {
const STORAGE_MODE_OPTIONS = React.useMemo(
() => [
{
@@ -17,7 +17,7 @@
value: 'dynamic',
},
],
- locale,
+ [],
);
return (
@@ -32,6 +32,11 @@
'Offering needs to be saved before pricing for dynamic components could be set.',
)}
/>
+ <NumberField
+ name="snapshot_size_limit_gb"
+ label={translate('Snapshot size limit')}
+ unit="GB"
+ />
</FormContainer>
);
}; |
ca6bbf13f6d0603ee39b2c07de0dcacaf3842749 | demo/app/app.ts | demo/app/app.ts | import "./bundle-config";
import * as application from 'tns-core-modules/application';
import { StoreUpdate, AlertTypesConstant } from "nativescript-store-update";
new StoreUpdate({
notifyNbDaysAfterRelease: 0,
majorUpdateAlertType: AlertTypesConstant.OPTION
});
application.start({ moduleName: "main-page" });
| import "./bundle-config";
import * as application from "tns-core-modules/application";
import { StoreUpdate, AlertTypesConstant } from "nativescript-store-update";
StoreUpdate.init({
notifyNbDaysAfterRelease: 1,
majorUpdateAlertType: AlertTypesConstant.OPTION
})
application.start({ moduleName: "main-page" });
| Update demo use of plugin | Update demo use of plugin
| TypeScript | apache-2.0 | chronogolf/nativescript-store-update,chronogolf/nativescript-store-update,chronogolf/nativescript-store-update,chronogolf/nativescript-store-update | ---
+++
@@ -1,9 +1,9 @@
import "./bundle-config";
-import * as application from 'tns-core-modules/application';
+import * as application from "tns-core-modules/application";
import { StoreUpdate, AlertTypesConstant } from "nativescript-store-update";
-new StoreUpdate({
- notifyNbDaysAfterRelease: 0,
+StoreUpdate.init({
+ notifyNbDaysAfterRelease: 1,
majorUpdateAlertType: AlertTypesConstant.OPTION
-});
+})
application.start({ moduleName: "main-page" }); |
6c3736e705d71d9dd15a81e27bf23b28119e14fd | src/renderer/app/services/player.service.ts | src/renderer/app/services/player.service.ts | import { Injectable } from '@angular/core';
import { Player } from '../models/player.model';
import { BankService } from './bank.service';
@Injectable({
providedIn: 'root'
})
export class PlayerService {
private _players: Player[] = [];
constructor(private _bankService: BankService) { }
public get players(): Player[] {
return this._players;
}
public createPlayer(firstName: string, lastName: string, startingBalance: number): Player {
const account = this._bankService.OpenAccount(startingBalance);
const player = new Player(firstName, lastName, account);
this._players.push(player);
return player;
}
public deletePlayer(player:Player): void {
this._players = this._players.filter(p => p !== player);
}
}
| import { Injectable } from '@angular/core';
import { Player } from '../models/player.model';
import { BankService } from './bank.service';
@Injectable({
providedIn: 'root'
})
export class PlayerService {
private _players: Player[] = [];
constructor(private _bankService: BankService) { }
public get players(): Player[] {
return this._players;
}
public createPlayer(firstName: string, lastName: string, startingBalance: number): Player {
const account = this._bankService.OpenAccount(startingBalance);
const player = new Player(firstName, lastName, account);
this._players.push(player);
this._players.sort((a, b) => a.name.localeCompare(b.name));
return player;
}
public deletePlayer(player:Player): void {
this._players = this._players.filter(p => p !== player);
}
}
| Sort players array on add | Sort players array on add
| TypeScript | apache-2.0 | luminousuk/CriminalContact,luminousuk/CriminalContact,luminousuk/CriminalContact | ---
+++
@@ -19,6 +19,7 @@
const account = this._bankService.OpenAccount(startingBalance);
const player = new Player(firstName, lastName, account);
this._players.push(player);
+ this._players.sort((a, b) => a.name.localeCompare(b.name));
return player;
} |
fd1a375b3f4c9e14bc6a4b19f10b84340b5f488f | app/scripts/modules/amazon/src/serverGroup/configure/wizard/loadBalancers/loadBalancerSelector.component.ts | app/scripts/modules/amazon/src/serverGroup/configure/wizard/loadBalancers/loadBalancerSelector.component.ts | import { IComponentController, IComponentOptions, module } from 'angular';
import { INFRASTRUCTURE_CACHE_SERVICE, InfrastructureCacheService } from '@spinnaker/core';
class LoadBalancerSelectorController implements IComponentController {
public command: any;
public refreshTime: number;
public refreshing = false;
constructor(private awsServerGroupConfigurationService: any, private infrastructureCaches: InfrastructureCacheService) { 'ngInject'; }
public setLoadBalancerRefreshTime(): void {
this.refreshTime = this.infrastructureCaches.get('loadBalancers').getStats().ageMax;
}
public refreshLoadBalancers(): void {
this.refreshing = true;
this.awsServerGroupConfigurationService.refreshLoadBalancers(this.command).then(() => {
this.refreshing = false;
this.setLoadBalancerRefreshTime();
});
}
}
export class LoadBalancerSelectorComponent implements IComponentOptions {
public bindings: any = {
command: '='
};
public controller: any = LoadBalancerSelectorController;
public templateUrl = require('./loadBalancerSelector.component.html');
}
export const LOAD_BALANCER_SELECTOR = 'spinnaker.amazon.serverGroup.configure.wizard.loadBalancers.selector.component';
module (LOAD_BALANCER_SELECTOR, [
require('../../serverGroupConfiguration.service.js'),
INFRASTRUCTURE_CACHE_SERVICE
])
.component('awsServerGroupLoadBalancerSelector', new LoadBalancerSelectorComponent());
| import { IComponentController, IComponentOptions, module } from 'angular';
import { INFRASTRUCTURE_CACHE_SERVICE, InfrastructureCacheService } from '@spinnaker/core';
class LoadBalancerSelectorController implements IComponentController {
public command: any;
public refreshTime: number;
public refreshing = false;
constructor(private awsServerGroupConfigurationService: any, private infrastructureCaches: InfrastructureCacheService) {
'ngInject';
this.setLoadBalancerRefreshTime();
}
public setLoadBalancerRefreshTime(): void {
this.refreshTime = this.infrastructureCaches.get('loadBalancers').getStats().ageMax;
}
public refreshLoadBalancers(): void {
this.refreshing = true;
this.awsServerGroupConfigurationService.refreshLoadBalancers(this.command).then(() => {
this.refreshing = false;
this.setLoadBalancerRefreshTime();
});
}
}
export class LoadBalancerSelectorComponent implements IComponentOptions {
public bindings: any = {
command: '='
};
public controller: any = LoadBalancerSelectorController;
public templateUrl = require('./loadBalancerSelector.component.html');
}
export const LOAD_BALANCER_SELECTOR = 'spinnaker.amazon.serverGroup.configure.wizard.loadBalancers.selector.component';
module (LOAD_BALANCER_SELECTOR, [
require('../../serverGroupConfiguration.service.js'),
INFRASTRUCTURE_CACHE_SERVICE
])
.component('awsServerGroupLoadBalancerSelector', new LoadBalancerSelectorComponent());
| Add originl refresh time back to load balancer selector | fix(provider/amazon): Add originl refresh time back to load balancer selector
| TypeScript | apache-2.0 | spinnaker/deck,kenzanlabs/deck,spinnaker/deck,spinnaker/deck,icfantv/deck,ajordens/deck,icfantv/deck,ajordens/deck,sgarlick987/deck,sgarlick987/deck,kenzanlabs/deck,ajordens/deck,sgarlick987/deck,ajordens/deck,icfantv/deck,kenzanlabs/deck,duftler/deck,sgarlick987/deck,duftler/deck,duftler/deck,icfantv/deck,duftler/deck,spinnaker/deck | ---
+++
@@ -8,7 +8,11 @@
public refreshTime: number;
public refreshing = false;
- constructor(private awsServerGroupConfigurationService: any, private infrastructureCaches: InfrastructureCacheService) { 'ngInject'; }
+ constructor(private awsServerGroupConfigurationService: any, private infrastructureCaches: InfrastructureCacheService) {
+ 'ngInject';
+
+ this.setLoadBalancerRefreshTime();
+}
public setLoadBalancerRefreshTime(): void {
this.refreshTime = this.infrastructureCaches.get('loadBalancers').getStats().ageMax; |
6c771f69a62e624e559b53b4c9acef4ea8978016 | server/couchdb_connector/db_Connection.ts | server/couchdb_connector/db_Connection.ts | /// <reference path="../../typings/meteor/meteor.d.ts" />
declare var process: any;
export function getDbVersion() {
console.log(HTTP.get(process.env.HF_COUCH_DB).content);
}
| /// <reference path="../../typings/meteor/meteor.d.ts" />
declare var process: any;
export function getDbVersion() {
console.log(HTTP.get(process.env.COUCH_URL).content);
}
| Fix server env variable name. | Fix server env variable name.
| TypeScript | apache-2.0 | shmakes/hf_callcenter,shmakes/hf_callcenter | ---
+++
@@ -2,5 +2,5 @@
declare var process: any;
export function getDbVersion() {
- console.log(HTTP.get(process.env.HF_COUCH_DB).content);
+ console.log(HTTP.get(process.env.COUCH_URL).content);
} |
e8bbd04a3aa012146deaaeac20d681a7f974e170 | src/marketplace/resources/list/ResourceActionsButton.tsx | src/marketplace/resources/list/ResourceActionsButton.tsx | import { FunctionComponent } from 'react';
import { ResourceActionsButton as BaseResourceActionsButton } from '@waldur/marketplace/resources/actions/ResourceActionsButton';
import { ActionButtonResource } from '@waldur/resource/actions/ActionButtonResource';
import { Resource } from '../types';
interface ResourceActionsButtonProps {
row: Resource;
refreshList?(): void;
}
export const ResourceActionsButton: FunctionComponent<ResourceActionsButtonProps> = ({
row,
refreshList,
}) =>
row.scope === null ? (
<BaseResourceActionsButton
resource={
{
...row,
marketplace_resource_uuid: row.uuid,
} as any
}
refreshList={refreshList}
/>
) : (
<>
<ActionButtonResource url={row.scope} refreshList={refreshList} />
</>
);
| import { FunctionComponent } from 'react';
import { ResourceActionsButton as BaseResourceActionsButton } from '@waldur/marketplace/resources/actions/ResourceActionsButton';
import { ActionButtonResource } from '@waldur/resource/actions/ActionButtonResource';
import { Resource } from '../types';
interface ResourceActionsButtonProps {
row: Resource;
refreshList?(): void;
}
export const ResourceActionsButton: FunctionComponent<ResourceActionsButtonProps> = ({
row,
refreshList,
}) =>
row.scope === null || row.offering_type === 'Support.OfferingTemplate' ? (
<BaseResourceActionsButton
resource={
{
...row,
marketplace_resource_uuid: row.uuid,
} as any
}
refreshList={refreshList}
/>
) : (
<>
<ActionButtonResource url={row.scope} refreshList={refreshList} />
</>
);
| Fix actions button for request-based items in list view. | Fix actions button for request-based items in list view.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -14,7 +14,7 @@
row,
refreshList,
}) =>
- row.scope === null ? (
+ row.scope === null || row.offering_type === 'Support.OfferingTemplate' ? (
<BaseResourceActionsButton
resource={
{ |
3afbfd84c640e2f9cdc196fa2744801d34aa6605 | components/Draggable.tsx | components/Draggable.tsx | import * as React from 'react'
import * as classnames from 'classnames'
export interface DraggableProps {
coordinates?: { x: number; y: number }
pressed?: boolean
rotation?: number
size?: number
style?: React.CSSProperties
}
interface DraggableStyle {}
const defaultStyle: React.CSSProperties = {
cursor: 'pointer',
position: 'absolute',
transform: 'translate(-50%, -50%)',
transition: 'width 300ms ease, height 300ms ease, border-radius 300ms ease, background-color 300ms ease',
}
const getSize = (show: boolean, pressed: boolean, defaultSize: number) =>
show ? (pressed ? defaultSize * 1.2 : defaultSize) : 0
const Draggable = ({
coordinates,
pressed = false,
rotation = 0,
size = 40,
style,
}: DraggableProps): JSX.Element | null => {
return (
<div
style={{
...defaultStyle,
...style,
width: getSize(!!coordinates, pressed, size),
height: getSize(!!coordinates, pressed, size),
top: coordinates ? coordinates.y : 0,
left: coordinates ? coordinates.x : 0,
boxShadow: pressed ? '3px 3px 12px rgba(0, 0, 0, 0.25)' : '1px 1px 4px rgba(0, 0, 0, 0.75)',
transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
borderRadius: pressed ? size / 3 : size / 2,
backgroundColor: pressed ? 'red' : 'black',
}}
className={classnames({ pressed })}
/>
)
}
export default Draggable
| import * as React from 'react'
import * as classnames from 'classnames'
export interface DraggableProps {
coordinates?: { x: number; y: number }
pressed?: boolean
rotation?: number
size?: number
style?: React.CSSProperties
}
interface DraggableStyle {}
const defaultStyle: React.CSSProperties = {
backgroundColor: 'black',
borderRadius: 20,
boxSizing: 'border-box',
cursor: 'pointer',
height: 40,
position: 'absolute',
transform: 'translate(-50%, -50%)',
transition: 'width 300ms ease, height 300ms ease, border-radius 300ms ease, background-color 300ms ease',
width: 40,
}
const Draggable = ({ coordinates, pressed = false, rotation = 0, size = 40, style }: DraggableProps): JSX.Element => {
return (
<div
style={{
...defaultStyle,
...style,
width: size,
height: size,
top: coordinates ? coordinates.y : 0,
left: coordinates ? coordinates.x : 0,
transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
}}
className={classnames({ pressed })}
/>
)
}
export default Draggable
| Make the draggable component more generic | Make the draggable component more generic
| TypeScript | mit | programbo/react-circular-slider | ---
+++
@@ -12,35 +12,28 @@
interface DraggableStyle {}
const defaultStyle: React.CSSProperties = {
+ backgroundColor: 'black',
+ borderRadius: 20,
+ boxSizing: 'border-box',
cursor: 'pointer',
+ height: 40,
position: 'absolute',
transform: 'translate(-50%, -50%)',
transition: 'width 300ms ease, height 300ms ease, border-radius 300ms ease, background-color 300ms ease',
+ width: 40,
}
-const getSize = (show: boolean, pressed: boolean, defaultSize: number) =>
- show ? (pressed ? defaultSize * 1.2 : defaultSize) : 0
-
-const Draggable = ({
- coordinates,
- pressed = false,
- rotation = 0,
- size = 40,
- style,
-}: DraggableProps): JSX.Element | null => {
+const Draggable = ({ coordinates, pressed = false, rotation = 0, size = 40, style }: DraggableProps): JSX.Element => {
return (
<div
style={{
...defaultStyle,
...style,
- width: getSize(!!coordinates, pressed, size),
- height: getSize(!!coordinates, pressed, size),
+ width: size,
+ height: size,
top: coordinates ? coordinates.y : 0,
left: coordinates ? coordinates.x : 0,
- boxShadow: pressed ? '3px 3px 12px rgba(0, 0, 0, 0.25)' : '1px 1px 4px rgba(0, 0, 0, 0.75)',
transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
- borderRadius: pressed ? size / 3 : size / 2,
- backgroundColor: pressed ? 'red' : 'black',
}}
className={classnames({ pressed })}
/> |
493bcdf7769d6b8ad063fc2cb6b1907d41450bb7 | src/SyntaxNodes/NsfwBlockNode.ts | src/SyntaxNodes/NsfwBlockNode.ts | import { OutlineSyntaxNode } from './OutlineSyntaxNode'
export class NsfwBlockNode {
OUTLINE_SYNTAX_NODE(): void { }
constructor(public children: OutlineSyntaxNode[] = []) { }
protected NSFW_BLOCK_NODE(): void { }
}
| import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode'
export class NsfwBlockNode extends RichOutlineSyntaxNode {
protected NSFW_BLOCK_NODE(): void { }
}
| Use RichOutlineSyntaxNode for NSFW blocks | Use RichOutlineSyntaxNode for NSFW blocks
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,10 +1,6 @@
-import { OutlineSyntaxNode } from './OutlineSyntaxNode'
+import { RichOutlineSyntaxNode } from './RichOutlineSyntaxNode'
-export class NsfwBlockNode {
- OUTLINE_SYNTAX_NODE(): void { }
-
- constructor(public children: OutlineSyntaxNode[] = []) { }
-
+export class NsfwBlockNode extends RichOutlineSyntaxNode {
protected NSFW_BLOCK_NODE(): void { }
} |
59479ad66c7e9e6817b123177bb1e26fc088d284 | skills/index.ts | skills/index.ts | import { Express } from "express";
import * as Alexa from "alexa-app";
// Skills
import StagesSkill from "./stages";
import KMSignalRSkill from "./kmsignalr";
import StreamcheckSkill from "./streamcheck";
export default async function configure(server: Express) {
const auntieDot = new Alexa.app("auntie-dot");
const streamcheck = new Alexa.app("streamcheck");
[StagesSkill, KMSignalRSkill].forEach(async skill => await skill(auntieDot));
await StreamcheckSkill(streamcheck);
auntieDot.express(server, "/skills/");
streamcheck.express(server, "/skills/");
} | import { Express } from "express";
import * as Alexa from "alexa-app";
// Skills
import StagesSkill from "./stages";
import KMSignalRSkill from "./kmsignalr";
import StreamcheckSkill from "./streamcheck";
export default async function configure(server: Express) {
const blackbox = new Alexa.app("blackbox");
const streamcheck = new Alexa.app("streamcheck");
[StagesSkill, KMSignalRSkill].forEach(async skill => await skill(blackbox));
await StreamcheckSkill(streamcheck);
blackbox.express(server, "/skills/");
streamcheck.express(server, "/skills/");
} | Rename auntie-dot skill to blackbox. Auntie Dot doesn't work with Alexa, it fails to make the request. | Rename auntie-dot skill to blackbox.
Auntie Dot doesn't work with Alexa, it fails to make the request.
| TypeScript | mit | nozzlegear/alexa-skills | ---
+++
@@ -7,12 +7,12 @@
import StreamcheckSkill from "./streamcheck";
export default async function configure(server: Express) {
- const auntieDot = new Alexa.app("auntie-dot");
+ const blackbox = new Alexa.app("blackbox");
const streamcheck = new Alexa.app("streamcheck");
- [StagesSkill, KMSignalRSkill].forEach(async skill => await skill(auntieDot));
+ [StagesSkill, KMSignalRSkill].forEach(async skill => await skill(blackbox));
await StreamcheckSkill(streamcheck);
- auntieDot.express(server, "/skills/");
+ blackbox.express(server, "/skills/");
streamcheck.express(server, "/skills/");
} |
af37e2e7fdab564121f1b0d87f654a6d69af899c | src/utils/rc.ts | src/utils/rc.ts | import rc = require('rc')
import extend = require('xtend')
import { PROJECT_NAME, REGISTRY_URL } from './config'
export interface RcConfig {
proxy?: string
httpProxy?: string
httpsProxy?: string
noProxy?: string
rejectUnauthorized?: boolean
ca?: string | string[]
key?: string
cert?: string
userAgent?: string
githubToken?: string
registryURL?: string
defaultSource?: string
defaultAmbientSource?: string
}
export const DEFAULTS = {
userAgent: `${PROJECT_NAME}/{typingsVersion} node/{nodeVersion} {platform} {arch}`,
registryURL: REGISTRY_URL,
defaultSource: 'npm',
defaultAmbientSource: 'dt'
}
export default extend(DEFAULTS, rc(PROJECT_NAME)) as RcConfig
| import rc = require('rc')
import extend = require('xtend')
import { PROJECT_NAME, REGISTRY_URL } from './config'
import { RcConfig } from '../interfaces'
export const DEFAULTS = {
userAgent: `${PROJECT_NAME}/{typingsVersion} node/{nodeVersion} {platform} {arch}`,
registryURL: REGISTRY_URL,
defaultSource: 'npm',
defaultAmbientSource: 'dt'
}
export default extend(DEFAULTS, rc(PROJECT_NAME)) as RcConfig
| Use `RcConfig` interface from "interfaces" | Use `RcConfig` interface from "interfaces"
| TypeScript | mit | typings/core,typings/core | ---
+++
@@ -1,22 +1,7 @@
import rc = require('rc')
import extend = require('xtend')
import { PROJECT_NAME, REGISTRY_URL } from './config'
-
-export interface RcConfig {
- proxy?: string
- httpProxy?: string
- httpsProxy?: string
- noProxy?: string
- rejectUnauthorized?: boolean
- ca?: string | string[]
- key?: string
- cert?: string
- userAgent?: string
- githubToken?: string
- registryURL?: string
- defaultSource?: string
- defaultAmbientSource?: string
-}
+import { RcConfig } from '../interfaces'
export const DEFAULTS = {
userAgent: `${PROJECT_NAME}/{typingsVersion} node/{nodeVersion} {platform} {arch}`, |
1e3abe455e88fa41daee4c231e781269f0fa9cda | client/src/app/users/add-user.component.ts | client/src/app/users/add-user.component.ts | import {Component, Inject} from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material'
import {UserListService} from "./user-list.service";
import {User} from "./user";
@Component({
selector: 'add-user.component',
templateUrl: 'add-user.component.html',
})
export class AddUserComponent {
public newUserName:string;
public newUserAge: number;
public newUserCompany: string;
public newUserEmail: string;
private userAddSuccess : Boolean = false;
public users: User[];
constructor(public userListService: UserListService,
public dialogRef: MatDialogRef<AddUserComponent>,
@Inject(MAT_DIALOG_DATA) public data: {user: User}) {
}
onNoClick(): void {
this.dialogRef.close();
}
}
| import {Component, Inject} from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material'
import {User} from "./user";
@Component({
selector: 'add-user.component',
templateUrl: 'add-user.component.html',
})
export class AddUserComponent {
constructor(
public dialogRef: MatDialogRef<AddUserComponent>,
@Inject(MAT_DIALOG_DATA) public data: {user: User}) {
}
onNoClick(): void {
this.dialogRef.close();
}
}
| Clean out unused pieces in `AddUserComponent` | Clean out unused pieces in `AddUserComponent`
There was a lot of cruft that accumulated in `AddUserComponent`, and
this cleans that up a bit.
| TypeScript | mit | UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo | ---
+++
@@ -1,23 +1,13 @@
import {Component, Inject} from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material'
-import {UserListService} from "./user-list.service";
import {User} from "./user";
-
@Component({
selector: 'add-user.component',
templateUrl: 'add-user.component.html',
})
export class AddUserComponent {
- public newUserName:string;
- public newUserAge: number;
- public newUserCompany: string;
- public newUserEmail: string;
- private userAddSuccess : Boolean = false;
-
- public users: User[];
-
- constructor(public userListService: UserListService,
+ constructor(
public dialogRef: MatDialogRef<AddUserComponent>,
@Inject(MAT_DIALOG_DATA) public data: {user: User}) {
} |
4e9b16ff15624cafcdc1921b79adae222230c6f0 | js/ThreeInstrumentable.ts | js/ThreeInstrumentable.ts | // Copyright 2021-2022, University of Colorado Boulder
/**
* Mixin for THREE.Object3D types that handles instrumentation details.
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
*/
import ThreeObject3DPhetioObject from './ThreeObject3DPhetioObject.js';
import mobius from './mobius.js';
import Constructor from '../../phet-core/js/Constructor.js';
import memoize from '../../phet-core/js/memoize.js';
/**
* @param type - Should be THREE.Object3D or a subtype
*/
const ThreeInstrumentable = memoize( <SuperType extends Constructor>( type: SuperType ) => {
return class extends type {
phetioObject: ThreeObject3DPhetioObject;
/**
* Pass tandem as the first arg, the rest will be passed through
*/
constructor( ...args: any[] ) {
const options = args[ args.length - 1 ];
const threeArgs = args.slice( 0, args.length - 1 );
super( ...threeArgs );
this.phetioObject = new ThreeObject3DPhetioObject( options );
}
/**
* Releases references
*/
dispose() {
// @ts-ignore
super.dispose && super.dispose();
this.phetioObject.dispose();
}
};
} );
mobius.register( 'ThreeInstrumentable', ThreeInstrumentable );
export default ThreeInstrumentable; | // Copyright 2021-2022, University of Colorado Boulder
/**
* Mixin for THREE.Object3D types that handles instrumentation details.
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
*/
import ThreeObject3DPhetioObject from './ThreeObject3DPhetioObject.js';
import mobius from './mobius.js';
import Constructor from '../../phet-core/js/types/Constructor.js';
import memoize from '../../phet-core/js/memoize.js';
/**
* @param type - Should be THREE.Object3D or a subtype
*/
const ThreeInstrumentable = memoize( <SuperType extends Constructor>( type: SuperType ) => {
return class extends type {
phetioObject: ThreeObject3DPhetioObject;
/**
* Pass tandem as the first arg, the rest will be passed through
*/
constructor( ...args: any[] ) {
const options = args[ args.length - 1 ];
const threeArgs = args.slice( 0, args.length - 1 );
super( ...threeArgs );
this.phetioObject = new ThreeObject3DPhetioObject( options );
}
/**
* Releases references
*/
dispose() {
// @ts-ignore
super.dispose && super.dispose();
this.phetioObject.dispose();
}
};
} );
mobius.register( 'ThreeInstrumentable', ThreeInstrumentable );
export default ThreeInstrumentable; | Move phet-core general types to /types | Move phet-core general types to /types
| TypeScript | mit | phetsims/mobius,phetsims/mobius,phetsims/mobius | ---
+++
@@ -8,7 +8,7 @@
import ThreeObject3DPhetioObject from './ThreeObject3DPhetioObject.js';
import mobius from './mobius.js';
-import Constructor from '../../phet-core/js/Constructor.js';
+import Constructor from '../../phet-core/js/types/Constructor.js';
import memoize from '../../phet-core/js/memoize.js';
/** |
db6e2cb5bab28a90cf58ed624064c816e848a090 | app/src/lib/stores/helpers/pull-request-updater.ts | app/src/lib/stores/helpers/pull-request-updater.ts | import { PullRequestStore } from '../pull-request-store'
import { Account } from '../../../models/account'
import { fatalError } from '../../fatal-error'
import { GitHubRepository } from '../../../models/github-repository'
//** Interval to check for pull requests */
const PullRequestInterval = 1000 * 60 * 10
enum TimeoutHandles {
PullRequest = 'PullRequestHandle',
Status = 'StatusHandle',
PushedPullRequest = 'PushedPullRequestHandle',
}
/**
* Acts as a service for downloading the latest pull request
* and status info from GitHub.
*/
export class PullRequestUpdater {
private readonly timeoutHandles = new Map<TimeoutHandles, number>()
private isStopped: boolean = true
public constructor(
private readonly repository: GitHubRepository,
private readonly account: Account,
private readonly store: PullRequestStore
) {}
/** Starts the updater */
public start() {
if (!this.isStopped) {
fatalError(
'Cannot start the Pull Request Updater that is already running.'
)
return
}
this.timeoutHandles.set(
TimeoutHandles.PullRequest,
window.setTimeout(() => {
this.store.refreshPullRequests(this.repository, this.account)
}, PullRequestInterval)
)
}
public stop() {
this.isStopped = true
for (const timeoutHandle of this.timeoutHandles.values()) {
window.clearTimeout(timeoutHandle)
}
this.timeoutHandles.clear()
}
}
| import { PullRequestStore } from '../pull-request-store'
import { Account } from '../../../models/account'
import { GitHubRepository } from '../../../models/github-repository'
//** Interval to check for pull requests */
const PullRequestInterval = 1000 * 60 * 10
/**
* Acts as a service for downloading the latest pull request
* and status info from GitHub.
*/
export class PullRequestUpdater {
private intervalId: number | null = null
public constructor(
private readonly repository: GitHubRepository,
private readonly account: Account,
private readonly store: PullRequestStore
) {}
/** Starts the updater */
public start() {
this.stop()
this.intervalId = window.setInterval(() => {
this.store.refreshPullRequests(this.repository, this.account)
}, PullRequestInterval)
}
public stop() {
if (this.intervalId !== null) {
clearInterval(this.intervalId)
this.intervalId = null
}
}
}
| Clean up and use setInterval, not setTimeout | Clean up and use setInterval, not setTimeout
| TypeScript | mit | say25/desktop,say25/desktop,j-f1/forked-desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,desktop/desktop,artivilla/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,shiftkey/desktop,say25/desktop | ---
+++
@@ -1,24 +1,16 @@
import { PullRequestStore } from '../pull-request-store'
import { Account } from '../../../models/account'
-import { fatalError } from '../../fatal-error'
import { GitHubRepository } from '../../../models/github-repository'
//** Interval to check for pull requests */
const PullRequestInterval = 1000 * 60 * 10
-
-enum TimeoutHandles {
- PullRequest = 'PullRequestHandle',
- Status = 'StatusHandle',
- PushedPullRequest = 'PushedPullRequestHandle',
-}
/**
* Acts as a service for downloading the latest pull request
* and status info from GitHub.
*/
export class PullRequestUpdater {
- private readonly timeoutHandles = new Map<TimeoutHandles, number>()
- private isStopped: boolean = true
+ private intervalId: number | null = null
public constructor(
private readonly repository: GitHubRepository,
@@ -28,30 +20,16 @@
/** Starts the updater */
public start() {
- if (!this.isStopped) {
- fatalError(
- 'Cannot start the Pull Request Updater that is already running.'
- )
-
- return
- }
-
- this.timeoutHandles.set(
- TimeoutHandles.PullRequest,
-
- window.setTimeout(() => {
- this.store.refreshPullRequests(this.repository, this.account)
- }, PullRequestInterval)
- )
+ this.stop()
+ this.intervalId = window.setInterval(() => {
+ this.store.refreshPullRequests(this.repository, this.account)
+ }, PullRequestInterval)
}
public stop() {
- this.isStopped = true
-
- for (const timeoutHandle of this.timeoutHandles.values()) {
- window.clearTimeout(timeoutHandle)
+ if (this.intervalId !== null) {
+ clearInterval(this.intervalId)
+ this.intervalId = null
}
-
- this.timeoutHandles.clear()
}
} |
6e07d6b34c6292b03ece1565c191932c56b887dd | src/js/View/Components/AppAlerts/AppAlert.tsx | src/js/View/Components/AppAlerts/AppAlert.tsx | import * as React from 'react';
interface IAppAlertProps
{
appAlert: IAppAlert;
};
class AppAlert extends React.Component<IAppAlertProps, any>
{
render()
{
return (
<div className={'app-alert '
+ 'app-alert--' + this.props.appAlert.status.toLowerCase()
+ (this.props.appAlert.show
? ' app-alert--show'
: '')}>
<div className="app-alert__inner">
<p>{this.props.appAlert.message}</p>
</div>
</div>
);
}
};
export default AppAlert; | import * as React from 'react';
interface IAppAlertProps
{
appAlert: IAppAlert;
};
class AppAlert extends React.Component<IAppAlertProps, any>
{
render()
{
return (
<div className={'app-alert '
+ 'app-alert--' + this.props.appAlert.status.toLowerCase()
+ (this.props.appAlert.show
? ' app-alert--show'
: '')}>
<div className="app-alert__inner">
<p className="truncate">
{this.props.appAlert.message}
</p>
</div>
</div>
);
}
};
export default AppAlert; | Truncate app alerts if they overflow | Truncate app alerts if they overflow
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -16,7 +16,9 @@
? ' app-alert--show'
: '')}>
<div className="app-alert__inner">
- <p>{this.props.appAlert.message}</p>
+ <p className="truncate">
+ {this.props.appAlert.message}
+ </p>
</div>
</div>
); |
2a85b1a8d3ef647707b97989b96981e9f1dbb2cf | src/main/webapp/src/app/files/file.resolve.ts | src/main/webapp/src/app/files/file.resolve.ts | import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { FileHttpService } from '../util/http/file.http.service';
import { FileForm } from '../util/http/config-file.model';
@Injectable()
export class FileResolver implements Resolve<FileForm> {
constructor(private fileHttpService: FileHttpService) {}
resolve(route: ActivatedRouteSnapshot): Observable<FileForm> {
const fileName = route.paramMap.get('fileName');
const emptyFileForm = new FileForm();
if (fileName && fileName.length > 0) {
return this.fileHttpService.getFile(fileName).flatMap((file) => {
return this.fileHttpService.getFileData(file.name).map((data) => {
return file.toForm();
});
});
} else {
return Observable.of(emptyFileForm);
}
}
}
| import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { FileHttpService } from '../util/http/file.http.service';
import { FileForm } from '../util/http/config-file.model';
@Injectable()
export class FileResolver implements Resolve<FileForm> {
constructor(private fileHttpService: FileHttpService) {}
resolve(route: ActivatedRouteSnapshot): Observable<FileForm> {
const fileName = route.paramMap.get('fileName');
const emptyFileForm = new FileForm();
if (fileName && fileName.length > 0) {
return this.fileHttpService.getFile(fileName).flatMap((file) => {
return this.fileHttpService.getFileData(file.name).map((data) => {
const fileForm = file.toForm();
fileForm.fileContent = data;
return fileForm;
});
});
} else {
return Observable.of(emptyFileForm);
}
}
}
| Fix missing file content in file detail view. | Fix missing file content in file detail view.
| TypeScript | apache-2.0 | cinovo/cloudconductor-server,cinovo/cloudconductor-server,cinovo/cloudconductor-server,cinovo/cloudconductor-server,cinovo/cloudconductor-server | ---
+++
@@ -19,7 +19,9 @@
if (fileName && fileName.length > 0) {
return this.fileHttpService.getFile(fileName).flatMap((file) => {
return this.fileHttpService.getFileData(file.name).map((data) => {
- return file.toForm();
+ const fileForm = file.toForm();
+ fileForm.fileContent = data;
+ return fileForm;
});
});
} else { |
5039130fc0818ea29ad22710797aee889d5560fc | src/components/gene/index.tsx | src/components/gene/index.tsx | import * as React from "react"
import * as Relay from "react-relay"
interface Props extends RelayProps, React.HTMLProps<GeneContents> {
gene: any
}
export class GeneContents extends React.Component<Props, null> {
render() {
return (
<div>
{this.props.gene.name}
{this.props.gene.mode}
</div>
)
}
}
export default Relay.createContainer(GeneContents, {
fragments: {
gene: () => Relay.QL`
fragment on Gene {
mode
name
}
`,
},
})
interface RelayProps {
gene: {
mode: string | null,
name: string | null,
} | any
}
| import * as React from "react"
import * as Relay from "react-relay"
import Artworks from "../artwork_grid"
import ArtistRow from "./artist_row"
const PageSize = 10
interface Props extends RelayProps, React.HTMLProps<GeneContents> {
gene: any
}
export class GeneContents extends React.Component<Props, null> {
render() {
let artists = this.props.gene.artists.edges.map(edge => {
return (
<ArtistRow artist={edge.node as any} key={edge.__dataID__} />
)
})
return (
<div>
{artists}
</div>
)
}
}
export default Relay.createContainer(GeneContents, {
initialVariables: {
showArtists: true,
artworksSize: PageSize,
artistsSize: PageSize,
medium: "*",
aggregations: ["MEDIUM", "TOTAL", "PRICE_RANGE", "DIMENSION_RANGE"],
price_range: "*",
dimension_range: "*",
sort: "-partner_updated_at",
},
fragments: {
gene: () => Relay.QL`
fragment on Gene {
mode
name
artists: artists_connection(first: $artistsSize) @include(if: $showArtists) {
edges {
node {
${ArtistRow.getFragment("artist")}
}
}
}
artworks: artworks_connection(
first: $artworksSize,
aggregations: $aggregations,
medium: $medium,
price_range: $price_range,
dimension_range: $dimension_range,
sort: $sort,
) @skip(if: $showArtists) {
${Artworks.getFragment("artworks")}
}
}
`,
},
})
interface RelayProps {
gene: {
mode: string | null,
name: string | null,
} | any
}
| Add ArtistRow to GeneContents view | Add ArtistRow to GeneContents view
| TypeScript | mit | xtina-starr/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,craigspaeth/reaction,xtina-starr/reaction,artsy/reaction,artsy/reaction-force,craigspaeth/reaction,craigspaeth/reaction,xtina-starr/reaction,artsy/reaction | ---
+++
@@ -1,5 +1,10 @@
import * as React from "react"
import * as Relay from "react-relay"
+
+import Artworks from "../artwork_grid"
+import ArtistRow from "./artist_row"
+
+const PageSize = 10
interface Props extends RelayProps, React.HTMLProps<GeneContents> {
gene: any
@@ -8,21 +13,54 @@
export class GeneContents extends React.Component<Props, null> {
render() {
+
+ let artists = this.props.gene.artists.edges.map(edge => {
+ return (
+ <ArtistRow artist={edge.node as any} key={edge.__dataID__} />
+ )
+ })
+
return (
<div>
- {this.props.gene.name}
- {this.props.gene.mode}
+ {artists}
</div>
)
}
}
export default Relay.createContainer(GeneContents, {
+ initialVariables: {
+ showArtists: true,
+ artworksSize: PageSize,
+ artistsSize: PageSize,
+ medium: "*",
+ aggregations: ["MEDIUM", "TOTAL", "PRICE_RANGE", "DIMENSION_RANGE"],
+ price_range: "*",
+ dimension_range: "*",
+ sort: "-partner_updated_at",
+ },
fragments: {
gene: () => Relay.QL`
fragment on Gene {
mode
name
+ artists: artists_connection(first: $artistsSize) @include(if: $showArtists) {
+ edges {
+ node {
+ ${ArtistRow.getFragment("artist")}
+ }
+ }
+ }
+ artworks: artworks_connection(
+ first: $artworksSize,
+ aggregations: $aggregations,
+ medium: $medium,
+ price_range: $price_range,
+ dimension_range: $dimension_range,
+ sort: $sort,
+ ) @skip(if: $showArtists) {
+ ${Artworks.getFragment("artworks")}
+ }
}
`,
}, |
f7efdc452d0c159ec0f6c5b25186402a5a32b858 | src/entry-options-input/entry-options-input.ts | src/entry-options-input/entry-options-input.ts | import {bindable, bindingMode} from 'aurelia-framework';
import {getLogger} from 'aurelia-logging';
const logger = getLogger('EntryOptionsInputComponent');
export class EntryOptionsInput {
@bindable({ defaultBindingMode: bindingMode.twoWay }) public value: string;
@bindable() public error: string;
@bindable() public label: string;
@bindable() public type: string;
private _inputEl: HTMLInputElement;
errorChanged(newValue: string, oldValue: string) {
if (!this._inputEl) {
return
}
this._inputEl.setCustomValidity(newValue);
}
}
| import {bindable, bindingMode} from 'aurelia-framework';
import {getLogger} from 'aurelia-logging';
const logger = getLogger('EntryOptionsInputComponent');
export class EntryOptionsInput {
@bindable({ defaultBindingMode: bindingMode.twoWay }) public value: string;
@bindable() public error: string;
@bindable() public label: string;
@bindable() public type: string;
private _inputEl: HTMLInputElement;
errorChanged(newValue: string, oldValue: string) {
if (!this._inputEl) {
return
}
this._inputEl.setCustomValidity(newValue);
// Fire input event to force MDL to check validity
const event = new Event('input', {bubbles: true});
this._inputEl.dispatchEvent(event);
}
}
| Fix MDL did not pick up change in error state in entry options input | Fix MDL did not pick up change in error state in entry options input
| TypeScript | mit | Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc | ---
+++
@@ -15,5 +15,9 @@
return
}
this._inputEl.setCustomValidity(newValue);
+
+ // Fire input event to force MDL to check validity
+ const event = new Event('input', {bubbles: true});
+ this._inputEl.dispatchEvent(event);
}
} |
523d4d8603ee6ee43f05834d9e03f33b4e7d3256 | pages/api/competitions/[id].ts | pages/api/competitions/[id].ts | import { NextApiRequest, NextApiResponse } from "next";
import { DEFAULT_CACHE_TIME } from "common/config";
import { fetchResources, resourcePatterns } from "common/hyena";
export default async (req: NextApiRequest, res: NextApiResponse) => {
const {
query: { id },
} = req;
const [{ data: competition }] = await fetchResources([
() => resourcePatterns.competition(id as string),
]);
// @ts-ignore
const seasonId = competition.season["season_id"];
const [
{ data: standings },
{ data: recentFixtures },
{ data: upcomingFixtures },
] = await fetchResources([
() => resourcePatterns.seasonStandings(seasonId),
() => resourcePatterns.seasonRecentFixtures(seasonId),
() => resourcePatterns.seasonUpcomingFixtures(seasonId),
]);
res.setHeader(
"Cache-Control",
`s-maxage=${DEFAULT_CACHE_TIME}, stale-while-revalidate`
);
res
.status(200)
.json({ competition, standings, recentFixtures, upcomingFixtures });
};
| import { NextApiRequest, NextApiResponse } from "next";
import { DEFAULT_CACHE_TIME } from "common/config";
import { fetchResources, resourcePatterns } from "common/hyena";
export default async (req: NextApiRequest, res: NextApiResponse) => {
const {
query: { id },
} = req;
const [{ data: competition }] = await fetchResources([
() => resourcePatterns.competition(id as string),
]);
// @ts-expect-error
const seasonId = competition?.season["season_id"] ?? null;
const [
{ data: standings },
{ data: recentFixtures },
{ data: upcomingFixtures },
] = await fetchResources([
() => resourcePatterns.seasonStandings(seasonId),
() => resourcePatterns.seasonRecentFixtures(seasonId),
() => resourcePatterns.seasonUpcomingFixtures(seasonId),
]);
res.setHeader(
"Cache-Control",
`s-maxage=${DEFAULT_CACHE_TIME}, stale-while-revalidate`
);
res
.status(200)
.json({ competition, standings, recentFixtures, upcomingFixtures });
};
| Fix api 502 error when competition id is invalid | Fix api 502 error when competition id is invalid
| TypeScript | isc | sobstel/golazon,sobstel/golazon,sobstel/golazon | ---
+++
@@ -10,8 +10,9 @@
const [{ data: competition }] = await fetchResources([
() => resourcePatterns.competition(id as string),
]);
- // @ts-ignore
- const seasonId = competition.season["season_id"];
+
+ // @ts-expect-error
+ const seasonId = competition?.season["season_id"] ?? null;
const [
{ data: standings }, |
4f992081cd4ec662bf5f17d4ba028c271d82fdab | app/src/lib/git/format-patch.ts | app/src/lib/git/format-patch.ts | import { git } from './core'
import { revRange } from './rev-list'
import { Repository } from '../../models/repository'
/**
* Generate a patch containing the changes associated with this range of commits
*
* @param repository where to generate path from
* @param base starting commit in range
* @param head ending commit in rage
* @returns patch generated
*/
export async function formatPatch(
repository: Repository,
base: string,
head: string
): Promise<string> {
const range = revRange(base, head)
const result = await git(
['diff', '--unified=1', '--minimal', range],
repository.path,
'formatPatch'
)
return result.stdout
}
| import { git } from './core'
import { revRange } from './rev-list'
import { Repository } from '../../models/repository'
/**
* Generate a patch containing the changes associated with this range of commits
*
* @param repository where to generate path from
* @param base starting commit in range
* @param head ending commit in rage
* @returns patch generated
*/
export async function formatPatch(
repository: Repository,
base: string,
head: string
): Promise<string> {
const range = revRange(base, head)
const result = await git(
['format-patch', '--stdout', range],
repository.path,
'formatPatch'
)
return result.stdout
}
| Revert "vastly improve performance for formatPatch" | Revert "vastly improve performance for formatPatch"
This reverts commit 7c1f7285ae347efe7e47caa40f4634b26ac2fece.
| TypeScript | mit | shiftkey/desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,say25/desktop,say25/desktop,artivilla/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus | ---
+++
@@ -17,7 +17,7 @@
): Promise<string> {
const range = revRange(base, head)
const result = await git(
- ['diff', '--unified=1', '--minimal', range],
+ ['format-patch', '--stdout', range],
repository.path,
'formatPatch'
) |
4be7a18bf84d8e08d3abba0b6862205ce475d7e2 | tests/__tests__/use-strict.spec.ts | tests/__tests__/use-strict.spec.ts | import { } from 'jest';
import { } from 'node';
import runJest from '../__helpers__/runJest';
describe('use strict', () => {
it('should show the error locations for "use strict" violations', () => {
const result = runJest('../use-strict', ['--no-cache', '-t', 'Invalid Strict']);
const stderr = result.stderr.toString();
expect(result.status).toBe(1);
expect(stderr).toContain('Strict.ts:4:4');
expect(stderr).toContain('Strict.test.ts:9:5');
});
it('should work with "use strict"', () => {
const result = runJest('../use-strict', ['--no-cache', '-t', 'Strict1']);
expect(result.status).toBe(0);
});
}); | import { } from 'jest';
import { } from 'node';
import runJest from '../__helpers__/runJest';
describe('use strict', () => {
fit('should show the error locations for "use strict" violations', () => {
const result = runJest('../use-strict', ['--no-cache', '-t', 'Invalid Strict']);
const stderr = result.stderr.toString();
expect(stderr).toContain('Strict.ts:4:4');
expect(stderr).toContain('Strict.test.ts:9:5');
});
it('should work with "use strict"', () => {
const result = runJest('../use-strict', ['--no-cache', '-t', 'Strict1']);
expect(result.status).toBe(0);
});
});
| Update use strict test to only check for line numbers | Update use strict test to only check for line numbers
| TypeScript | mit | kulshekhar/ts-jest,kulshekhar/ts-jest | ---
+++
@@ -4,13 +4,12 @@
describe('use strict', () => {
- it('should show the error locations for "use strict" violations', () => {
+ fit('should show the error locations for "use strict" violations', () => {
const result = runJest('../use-strict', ['--no-cache', '-t', 'Invalid Strict']);
const stderr = result.stderr.toString();
- expect(result.status).toBe(1);
expect(stderr).toContain('Strict.ts:4:4');
expect(stderr).toContain('Strict.test.ts:9:5');
|
57b5d058a832e0ae1d7cb770cb7e0d0f12523b7c | app/src/ui/lib/link-button.tsx | app/src/ui/lib/link-button.tsx | import * as React from 'react'
import { shell } from 'electron'
import * as classNames from 'classnames'
interface ILinkButtonProps {
/** A URI to open on click. */
readonly uri?: string
/** A function to call on click. */
readonly onClick?: () => void
/** The title of the button. */
readonly children?: string
/** CSS classes attached to the component */
readonly className?: string
/** The tab index of the anchor element. */
readonly tabIndex?: number
/** Disable the link from being clicked */
readonly disabled?: boolean
}
/** A link component. */
export class LinkButton extends React.Component<ILinkButtonProps, void> {
public render() {
const href = this.props.uri || ''
const className = classNames('link-button-component', this.props.className)
return (
<a
className={className}
href={href}
onClick={this.onClick}
tabIndex={this.props.tabIndex}
disabled={this.props.disabled}
>
{this.props.children}
</a>
)
}
private onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault()
if (this.props.disabled) {
return
}
const uri = this.props.uri
if (uri) {
shell.openExternal(uri)
}
const onClick = this.props.onClick
if (onClick) {
onClick()
}
}
}
| import * as React from 'react'
import { shell } from 'electron'
import * as classNames from 'classnames'
interface ILinkButtonProps extends React.HTMLProps<HTMLAnchorElement> {
/** A URI to open on click. */
readonly uri?: string
/** A function to call on click. */
readonly onClick?: () => void
/** The title of the button. */
readonly children?: string
/** CSS classes attached to the component */
readonly className?: string
/** The tab index of the anchor element. */
readonly tabIndex?: number
/** Disable the link from being clicked */
readonly disabled?: boolean
}
/** A link component. */
export class LinkButton extends React.Component<ILinkButtonProps, void> {
public render() {
const href = this.props.uri || ''
const className = classNames('link-button-component', this.props.className)
const props = { ...this.props, className, onClick: this.onClick, href }
return (
<a {...props}>
{this.props.children}
</a>
)
}
private onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault()
if (this.props.disabled) {
return
}
const uri = this.props.uri
if (uri) {
shell.openExternal(uri)
}
const onClick = this.props.onClick
if (onClick) {
onClick()
}
}
}
| Allow any props on <LinkButton>s | Allow any props on <LinkButton>s
| TypeScript | mit | desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,say25/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,hjobrien/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,hjobrien/desktop,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,gengjiawen/desktop,kactus-io/kactus,kactus-io/kactus,say25/desktop,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,hjobrien/desktop,gengjiawen/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,hjobrien/desktop,j-f1/forked-desktop,desktop/desktop | ---
+++
@@ -2,7 +2,7 @@
import { shell } from 'electron'
import * as classNames from 'classnames'
-interface ILinkButtonProps {
+interface ILinkButtonProps extends React.HTMLProps<HTMLAnchorElement> {
/** A URI to open on click. */
readonly uri?: string
@@ -27,15 +27,10 @@
public render() {
const href = this.props.uri || ''
const className = classNames('link-button-component', this.props.className)
+ const props = { ...this.props, className, onClick: this.onClick, href }
return (
- <a
- className={className}
- href={href}
- onClick={this.onClick}
- tabIndex={this.props.tabIndex}
- disabled={this.props.disabled}
- >
+ <a {...props}>
{this.props.children}
</a>
) |
387449fd9e81ef5ee056b2a310c897bbd10e7f06 | src/Test/Parsing/RevisionInsertion.ts | src/Test/Parsing/RevisionInsertion.ts | import { expect } from 'chai'
import Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { PlainText } from '../../SyntaxNodes/PlainText'
import { Emphasis } from '../../SyntaxNodes/Emphasis'
import { RevisionInsertion } from '../../SyntaxNodes/RevisionInsertion'
describe('markup surrounded by 2 plus signs', () => {
it('is put inside a revision insertion node', () => {
expect(Up.toDocument('I like ++to brush++ my teeth')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like '),
new RevisionInsertion([
new PlainText('to brush')
]),
new PlainText(' my teeth')
]))
})
})
describe('A revision insertion', () => {
it('is evaluated for other conventions', () => {
expect(Up.toDocument('I like ++to *regularly* brush++ my teeth')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like '),
new RevisionInsertion([
new PlainText('to '),
new Emphasis([
new PlainText('regularly')
]),
new PlainText(' brush')
]),
new PlainText(' my teeth')
]))
})
})
describe('An unmatched revision insertion delimiter', () => {
it('is preserved as plain text', () => {
expect(Up.toDocument('I like pizza++but I never eat it.')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like pizza++but I never eat it.'),
]))
})
})
| import { expect } from 'chai'
import Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { PlainText } from '../../SyntaxNodes/PlainText'
import { Emphasis } from '../../SyntaxNodes/Emphasis'
import { RevisionInsertion } from '../../SyntaxNodes/RevisionInsertion'
describe('Markup surrounded by 2 plus signs', () => {
it('is put inside a revision insertion node', () => {
expect(Up.toDocument('I like ++to brush++ my teeth')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like '),
new RevisionInsertion([
new PlainText('to brush')
]),
new PlainText(' my teeth')
]))
})
})
describe('A revision insertion', () => {
it('is evaluated for other conventions', () => {
expect(Up.toDocument('I like ++to *regularly* brush++ my teeth')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like '),
new RevisionInsertion([
new PlainText('to '),
new Emphasis([
new PlainText('regularly')
]),
new PlainText(' brush')
]),
new PlainText(' my teeth')
]))
})
})
describe('An unmatched revision insertion delimiter', () => {
it('is preserved as plain text', () => {
expect(Up.toDocument('I like pizza++but I never eat it.')).to.deep.equal(
insideDocumentAndParagraph([
new PlainText('I like pizza++but I never eat it.'),
]))
})
})
| Fix capitalization in test description | Fix capitalization in test description
| TypeScript | mit | start/up,start/up | ---
+++
@@ -6,7 +6,7 @@
import { RevisionInsertion } from '../../SyntaxNodes/RevisionInsertion'
-describe('markup surrounded by 2 plus signs', () => {
+describe('Markup surrounded by 2 plus signs', () => {
it('is put inside a revision insertion node', () => {
expect(Up.toDocument('I like ++to brush++ my teeth')).to.deep.equal(
insideDocumentAndParagraph([ |
5dea827c9e6b0bdcdb8e90913d0aaec4ce41382b | frontend/src/hacking-instructor/challenges/codingChallenges.ts | frontend/src/hacking-instructor/challenges/codingChallenges.ts | /*
* Copyright (c) 2014-2021 Bjoern Kimminich & the OWASP Juice Shop contributors.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs, waitForElementToGetClicked
} from '../helpers/helpers'
import { ChallengeInstruction } from '../'
export const CodingChallengesInstruction: ChallengeInstruction = {
name: 'Coding Challenges',
hints: [
{
text:
'Many Juice Shop hacking challenges come with an associated _Coding Challenge_ which will teach you more about the underlying vulnerability on source code level.',
fixture: '#Score\\ Board\\.solved',
resolved: waitInMs(15000)
},
{
text:
'You can launch a Coding Challenge via the `<>`-button. Click the one for the _Score Board_ challenge now.',
fixture: '#Score\\ Board\\.solved',
unskippable: true,
resolved: waitForElementToGetClicked('#Score\\ Board\\.codingChallengeButton')
},
{
text:
'All Coding Challenges take place in a modal dialog like this. They consist of two parts, one for finding and one for fixing the vulnerability in the code.',
fixture: '#code-snippet',
resolved: waitInMs(15000)
}
]
}
| /*
* Copyright (c) 2014-2021 Bjoern Kimminich & the OWASP Juice Shop contributors.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs, waitForElementToGetClicked
} from '../helpers/helpers'
import { ChallengeInstruction } from '../'
export const CodingChallengesInstruction: ChallengeInstruction = {
name: 'Coding Challenges',
hints: [
{
text:
'Many Juice Shop hacking challenges come with an associated _Coding Challenge_ which will teach you more about the underlying vulnerability on source code level.',
fixture: '#Score\\ Board\\.solved',
resolved: waitInMs(15000)
},
{
text:
'You can launch a Coding Challenge via the `<>`-button. Click the one for the _Score Board_ challenge now.',
fixture: '#codingChallengeTutorialButton',
unskippable: true,
resolved: waitForElementToGetClicked('#Score\\ Board\\.codingChallengeButton')
},
{
text:
'All Coding Challenges take place in a modal dialog like this. They consist of two parts, one for finding and one for fixing the vulnerability in the code.',
fixture: '#code-snippet',
resolved: waitInMs(15000)
}
]
}
| Fix hint to actual coding challenge launch button | Fix hint to actual coding challenge launch button
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -20,7 +20,7 @@
{
text:
'You can launch a Coding Challenge via the `<>`-button. Click the one for the _Score Board_ challenge now.',
- fixture: '#Score\\ Board\\.solved',
+ fixture: '#codingChallengeTutorialButton',
unskippable: true,
resolved: waitForElementToGetClicked('#Score\\ Board\\.codingChallengeButton')
}, |
1d95aebf61bdbbf4b0c3f537a6e106e8b3bab256 | client/Combatant/linkComponentToObservables.tsx | client/Combatant/linkComponentToObservables.tsx | import * as React from "react";
import * as ko from "knockout";
import { noop } from "lodash";
export function linkComponentToObservables(component: React.Component) {
let observableSubscription = ko.observable().subscribe(noop);
const oldComponentDidMount = component.componentDidMount || noop;
component.componentDidMount = () => {
observableSubscription = ko
.computed(() => component.render())
.subscribe(() => component.forceUpdate());
oldComponentDidMount();
};
const oldComponentWillUnmount = component.componentWillUnmount || noop;
component.componentWillUnmount = () => {
observableSubscription.dispose();
oldComponentWillUnmount();
};
}
export function useSubscription<T>(observable: KnockoutObservable<T>): T {
const [value, setValue] = React.useState({ current: observable() });
React.useEffect(() => {
const subscription = observable.subscribe(newValue => {
// In case newValue is a reference to the same object as before
// such as with KnockoutObservableArray, we instantiate a wrapper
// object for setValue.
setValue({ current: newValue });
});
return () => subscription.dispose();
}, [observable]);
return value.current;
}
| import * as React from "react";
import * as ko from "knockout";
import { noop } from "lodash";
export function linkComponentToObservables(component: React.Component) {
let observableSubscription = ko.observable().subscribe(noop);
const oldComponentDidMount = component.componentDidMount || noop;
component.componentDidMount = () => {
observableSubscription = ko
.computed(() => component.render())
.subscribe(() => component.forceUpdate());
oldComponentDidMount();
};
const oldComponentWillUnmount = component.componentWillUnmount || noop;
component.componentWillUnmount = () => {
observableSubscription.dispose();
oldComponentWillUnmount();
};
}
export function useSubscription<T>(observable: KnockoutObservable<T>): T {
const [value, setValue] = React.useState({ current: observable() });
React.useEffect(() => {
//If the observable itself changed, we want to get its current value as part of this useEffect.
setValue({ current: observable() });
const subscription = observable.subscribe(newValue => {
// In case newValue is a reference to the same object as before
// such as with KnockoutObservableArray, we instantiate a wrapper
// object for setValue.
setValue({ current: newValue });
});
return () => subscription.dispose();
}, [observable]);
return value.current;
}
| Update value when subscribed observable changes | Update value when subscribed observable changes
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -22,6 +22,9 @@
const [value, setValue] = React.useState({ current: observable() });
React.useEffect(() => {
+ //If the observable itself changed, we want to get its current value as part of this useEffect.
+ setValue({ current: observable() });
+
const subscription = observable.subscribe(newValue => {
// In case newValue is a reference to the same object as before
// such as with KnockoutObservableArray, we instantiate a wrapper |
778de3293a26f1affd31f87480045f1ec7b6f55e | src/client/index.ts | src/client/index.ts | import * as command from "./command";
import * as request from "./request";
import * as path from "path";
import * as vscode from "vscode";
import * as client from "vscode-languageclient";
export function launch(context: vscode.ExtensionContext): vscode.Disposable {
const module = context.asAbsolutePath(path.join("out", "src", "server", "index.js"));
const transport = client.TransportKind.ipc;
const run = { module, transport, options: {} };
const debug = { module, transport, options: { execArgv: [ "--nolazy", "--debug=6004" ] } };
const serverOptions = { run, debug };
const clientOptions = { documentSelector: [ "reason" ] };
const languageClient = new client.LanguageClient("Reason", serverOptions, clientOptions);
command.registerAll(context, languageClient);
request.registerAll(context, languageClient);
return languageClient.start();
}
| import * as command from "./command";
import * as request from "./request";
import * as path from "path";
import * as vscode from "vscode";
import * as client from "vscode-languageclient";
class ClientWindow implements vscode.Disposable {
readonly merlin: vscode.StatusBarItem;
constructor() {
this.merlin = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 0);
this.merlin.text = "$(hubot) [merlin]";
this.merlin.command = "reason.showMerlinFiles";
this.merlin.show();
return this;
}
dispose() {
this.merlin.dispose();
}
}
export function launch(context: vscode.ExtensionContext): vscode.Disposable {
const module = context.asAbsolutePath(path.join("out", "src", "server", "index.js"));
const transport = client.TransportKind.ipc;
const run = { module, transport, options: {} };
const debug = { module, transport, options: { execArgv: [ "--nolazy", "--debug=6004" ] } };
const serverOptions = { run, debug };
const clientOptions = { documentSelector: [ "reason" ] };
const languageClient = new client.LanguageClient("Reason", serverOptions, clientOptions);
command.registerAll(context, languageClient);
request.registerAll(context, languageClient);
context.subscriptions.push(new ClientWindow());
return languageClient.start();
}
| Create a clickable status bar item for merlin | Create a clickable status bar item for merlin
| TypeScript | apache-2.0 | freebroccolo/vscode-reasonml,freebroccolo/vscode-reasonml | ---
+++
@@ -3,6 +3,20 @@
import * as path from "path";
import * as vscode from "vscode";
import * as client from "vscode-languageclient";
+
+class ClientWindow implements vscode.Disposable {
+ readonly merlin: vscode.StatusBarItem;
+ constructor() {
+ this.merlin = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 0);
+ this.merlin.text = "$(hubot) [merlin]";
+ this.merlin.command = "reason.showMerlinFiles";
+ this.merlin.show();
+ return this;
+ }
+ dispose() {
+ this.merlin.dispose();
+ }
+}
export function launch(context: vscode.ExtensionContext): vscode.Disposable {
const module = context.asAbsolutePath(path.join("out", "src", "server", "index.js"));
@@ -14,5 +28,6 @@
const languageClient = new client.LanguageClient("Reason", serverOptions, clientOptions);
command.registerAll(context, languageClient);
request.registerAll(context, languageClient);
+ context.subscriptions.push(new ClientWindow());
return languageClient.start();
} |
2f523e21dd213e6b71e66ffd01f9b8f681c8200b | app/core/datastore/index/index-item.ts | app/core/datastore/index/index-item.ts | import {Document} from 'idai-components-2';
export type TypeName = string;
export interface IndexItem {
id: string;
identifier: string
}
export interface TypeResourceIndexItem extends IndexItem {
instances: { [resourceId: string]: TypeName}
}
/**
* @author Daniel de Oliveira
* @author Thomas Kleinke
*/
export class IndexItem {
private constructor() {} // hide on purpose, use from or copy instead
public static from(document: Document, showWarnings: boolean = false): IndexItem|undefined {
if (!document.resource) {
if (showWarnings) console.warn('no resource, will not index');
return undefined;
}
if (!document.resource.id) {
if (showWarnings) console.warn('no resourceId, will not index');
return undefined;
}
if (!document.resource.identifier) {
if (showWarnings) console.warn('no identifier, will not index');
return undefined;
}
return {
id: document.resource.id,
identifier: document.resource.identifier
};
}
}
| import {Document} from 'idai-components-2';
export type TypeName = string;
export interface IndexItem {
id: string;
identifier: string
}
export interface TypeResourceIndexItem extends IndexItem {
instances: { [resourceId: string]: TypeName}
}
/**
* @author Daniel de Oliveira
* @author Thomas Kleinke
*/
export class IndexItem {
private constructor() {} // hide on purpose, use from or copy instead
public static from(document: Document, showWarnings: boolean = false): IndexItem|undefined {
if (!document.resource) {
throw Error('illegal argument - document.resource undefined');
}
if (!document.resource.id) {
throw Error('illegal argument - document.id undefined');
}
if (!document.resource.identifier) {
if (showWarnings) console.warn('no identifier, will not index');
return undefined;
}
return {
id: document.resource.id,
identifier: document.resource.identifier
};
}
}
| Throw error instead log warning | Throw error instead log warning
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -27,12 +27,10 @@
public static from(document: Document, showWarnings: boolean = false): IndexItem|undefined {
if (!document.resource) {
- if (showWarnings) console.warn('no resource, will not index');
- return undefined;
+ throw Error('illegal argument - document.resource undefined');
}
if (!document.resource.id) {
- if (showWarnings) console.warn('no resourceId, will not index');
- return undefined;
+ throw Error('illegal argument - document.id undefined');
}
if (!document.resource.identifier) {
if (showWarnings) console.warn('no identifier, will not index'); |
599619020704218391edc7c4c9ec4d19da205369 | src/entities/Dam.ts | src/entities/Dam.ts | /**
* Dam names avaiable
*/
export enum DamName {
cantareira = 'Cantareira',
altoTiete = 'Alto Tietê',
guarapiranga = 'Guarapiranga',
cotia = 'Cotia',
rioGrande = 'Rio Grande',
rioClaro = 'Rio Claro',
saoLourenco = 'São Lourenço',
}
/**
* Pluviometry is a measure based on millimeters (mm)
*/
export interface Pluviometry {
/**
* Daily pluviometry
*/
day: string | number;
/**
* Monthly pluviometry
*/
month: string | number;
/**
* Monthly average pluviometry
*/
average: string | number;
}
export class Dam {
public name: DamName;
public volume: string;
public variation: string;
public pluviometry: Pluviometry;
constructor(name: DamName, volume: string, variation: string, pluviometry: Pluviometry) {
this.name = name;
this.volume = volume;
this.variation = variation;
this.pluviometry = pluviometry;
}
}
| /**
* Dam names avaiable
*/
export enum DamName {
cantareira = 'Cantareira',
altoTiete = 'Alto Tietê',
guarapiranga = 'Guarapiranga',
cotia = 'Cotia',
rioGrande = 'Rio Grande',
rioClaro = 'Rio Claro',
saoLourenco = 'São Lourenço',
}
/**
* Pluviometry is a measure based on millimeters (mm)
*/
export interface Pluviometry {
/**
* Daily pluviometry
*/
day: string | number;
/**
* Monthly pluviometry
*/
month: string | number;
/**
* Monthly average pluviometry
*/
average: string | number;
}
export interface Dam {
name: DamName;
volume: string;
variation: string;
pluviometry: Pluviometry;
}
| Change entity implementation to use only interface instead | Change entity implementation to use only interface instead
| TypeScript | mit | rafaell-lycan/sabesp-mananciais-api,rafaell-lycan/sabesp-mananciais-api | ---
+++
@@ -29,16 +29,9 @@
average: string | number;
}
-export class Dam {
- public name: DamName;
- public volume: string;
- public variation: string;
- public pluviometry: Pluviometry;
-
- constructor(name: DamName, volume: string, variation: string, pluviometry: Pluviometry) {
- this.name = name;
- this.volume = volume;
- this.variation = variation;
- this.pluviometry = pluviometry;
- }
+export interface Dam {
+ name: DamName;
+ volume: string;
+ variation: string;
+ pluviometry: Pluviometry;
} |
f0676a1012d9ca5b241af311444bb4310cfa321f | src/app/home/top-page/top-page.component.spec.ts | src/app/home/top-page/top-page.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { It, Mock } from 'typemoq';
import { TitleService } from '../../shared/title.service';
import { MockTitleService } from '../../shared/mocks/mock-title.service';
import { FeatureToggleService } from '../../shared/feature-toggle.service';
import { TopPageComponent } from './top-page.component';
describe('TopPageComponent', () => {
const mockTitleService = new MockTitleService();
let component: TopPageComponent;
let fixture: ComponentFixture<TopPageComponent>;
let compiled: HTMLElement;
const mockFeatureToggleService = Mock.ofType<FeatureToggleService>();
mockFeatureToggleService.setup(m => m.isEnabled(It.isAnyString())).returns(() => false);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [
TopPageComponent
],
providers: [
{ provide: TitleService, useValue: mockTitleService },
{ provide: FeatureToggleService, useFactory: () => mockFeatureToggleService.object }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TopPageComponent);
component = fixture.componentInstance;
compiled = fixture.debugElement.nativeElement;
fixture.detectChanges();
});
it('should create and load images', () => {
expect(component).toBeTruthy();
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { It, Mock } from 'typemoq';
import { TitleService } from '../../shared/title.service';
import { FeatureToggleService } from '../../shared/feature-toggle.service';
import { TopPageComponent } from './top-page.component';
describe('TopPageComponent', () => {
const mockTitleService = Mock.ofType<TitleService>();
mockTitleService.setup(x => x.setTitle(It.isAnyString()));
mockTitleService.setup(x => x.resetTitle());
let component: TopPageComponent;
let fixture: ComponentFixture<TopPageComponent>;
let compiled: HTMLElement;
const mockFeatureToggleService = Mock.ofType<FeatureToggleService>();
mockFeatureToggleService.setup(m => m.isEnabled(It.isAnyString())).returns(() => false);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [
TopPageComponent
],
providers: [
{ provide: TitleService, useFactory: () => mockTitleService.object },
{ provide: FeatureToggleService, useFactory: () => mockFeatureToggleService.object }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TopPageComponent);
component = fixture.componentInstance;
compiled = fixture.debugElement.nativeElement;
fixture.detectChanges();
});
it('should create and load images', () => {
expect(component).toBeTruthy();
});
});
| Update mock usage for top page component test | Update mock usage for top page component test
| TypeScript | apache-2.0 | jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog,jbrowneuk/jblog | ---
+++
@@ -4,13 +4,14 @@
import { It, Mock } from 'typemoq';
import { TitleService } from '../../shared/title.service';
-import { MockTitleService } from '../../shared/mocks/mock-title.service';
import { FeatureToggleService } from '../../shared/feature-toggle.service';
import { TopPageComponent } from './top-page.component';
describe('TopPageComponent', () => {
- const mockTitleService = new MockTitleService();
+ const mockTitleService = Mock.ofType<TitleService>();
+ mockTitleService.setup(x => x.setTitle(It.isAnyString()));
+ mockTitleService.setup(x => x.resetTitle());
let component: TopPageComponent;
let fixture: ComponentFixture<TopPageComponent>;
@@ -26,7 +27,7 @@
TopPageComponent
],
providers: [
- { provide: TitleService, useValue: mockTitleService },
+ { provide: TitleService, useFactory: () => mockTitleService.object },
{ provide: FeatureToggleService, useFactory: () => mockFeatureToggleService.object }
]
}) |
f1dfdf9d62613db65392c6eac97d4b367f9f9826 | packages/platform-express/src/services/PlatformExpressRouter.ts | packages/platform-express/src/services/PlatformExpressRouter.ts | import {InjectorService, PLATFORM_ROUTER_OPTIONS, PlatformHandler, PlatformRouter, PlatformStaticsOptions} from "@tsed/common";
import {Configuration, Inject} from "@tsed/di";
import * as Express from "express";
import {RouterOptions} from "express";
import {staticsMiddleware} from "../middlewares/staticsMiddleware";
declare global {
namespace TsED {
export interface Router extends Express.Router {}
}
}
/**
* @platform
* @express
*/
export class PlatformExpressRouter extends PlatformRouter<Express.Router> {
constructor(
platform: PlatformHandler,
@Configuration() configuration: Configuration,
@Inject(PLATFORM_ROUTER_OPTIONS) routerOptions: Partial<RouterOptions> = {}
) {
super(platform);
const options = Object.assign({}, configuration.express?.router || {}, routerOptions);
this.rawRouter = this.raw = Express.Router(options);
}
statics(endpoint: string, options: PlatformStaticsOptions) {
const {root, ...props} = options;
this.use(endpoint, staticsMiddleware(root, props));
return this;
}
}
| import {PLATFORM_ROUTER_OPTIONS, PlatformHandler, PlatformRouter, PlatformStaticsOptions} from "@tsed/common";
import {Configuration, Inject} from "@tsed/di";
import * as Express from "express";
import {RouterOptions} from "express";
import {staticsMiddleware} from "../middlewares/staticsMiddleware";
declare global {
namespace TsED {
export interface Router extends Express.Router {}
}
}
/**
* @platform
* @express
*/
export class PlatformExpressRouter extends PlatformRouter<Express.Router> {
constructor(
platform: PlatformHandler,
@Configuration() configuration: Configuration,
@Inject(PLATFORM_ROUTER_OPTIONS) routerOptions: Partial<RouterOptions> = {}
) {
super(platform);
const options = Object.assign(
{
mergeParams: true
},
configuration.express?.router || {},
routerOptions
);
this.rawRouter = this.raw = Express.Router(options);
}
statics(endpoint: string, options: PlatformStaticsOptions) {
const {root, ...props} = options;
this.use(endpoint, staticsMiddleware(root, props));
return this;
}
}
| Set mergeStatic to true by default for express | fix(platform-express): Set mergeStatic to true by default for express
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,4 +1,4 @@
-import {InjectorService, PLATFORM_ROUTER_OPTIONS, PlatformHandler, PlatformRouter, PlatformStaticsOptions} from "@tsed/common";
+import {PLATFORM_ROUTER_OPTIONS, PlatformHandler, PlatformRouter, PlatformStaticsOptions} from "@tsed/common";
import {Configuration, Inject} from "@tsed/di";
import * as Express from "express";
import {RouterOptions} from "express";
@@ -22,7 +22,13 @@
) {
super(platform);
- const options = Object.assign({}, configuration.express?.router || {}, routerOptions);
+ const options = Object.assign(
+ {
+ mergeParams: true
+ },
+ configuration.express?.router || {},
+ routerOptions
+ );
this.rawRouter = this.raw = Express.Router(options);
}
|
ad6b064063cc37f37b2e3fdb23464fe50bcf53f3 | server/src/lib/storage/mongo/MongoCollection.ts | server/src/lib/storage/mongo/MongoCollection.ts | import Bluebird = require("bluebird");
import { ICollection } from "../ICollection";
import MongoDB = require("mongodb");
import { IMongoClient } from "../../connectors/mongo/IMongoClient";
export class MongoCollection implements ICollection {
private mongoClient: IMongoClient;
private collectionName: string;
constructor(collectionName: string, mongoClient: IMongoClient) {
this.collectionName = collectionName;
this.mongoClient = mongoClient;
}
private collection(): Bluebird<MongoDB.Collection> {
return this.mongoClient.collection(this.collectionName);
}
find(query: any, sortKeys?: any, count?: number): Bluebird<any> {
return this.collection()
.then((collection) => collection.find(query).sort(sortKeys).limit(count))
.then((query) => query.toArray());
}
findOne(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.findOne(query));
}
update(query: any, updateQuery: any, options?: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.update(query, updateQuery, options));
}
remove(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.remove(query));
}
insert(document: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.insert(document));
}
count(query: any): Bluebird<number> {
return this.collection()
.then((collection) => collection.count(query));
}
} | import Bluebird = require("bluebird");
import { ICollection } from "../ICollection";
import MongoDB = require("mongodb");
import { IMongoClient } from "../../connectors/mongo/IMongoClient";
export class MongoCollection implements ICollection {
private mongoClient: IMongoClient;
private collectionName: string;
constructor(collectionName: string, mongoClient: IMongoClient) {
this.collectionName = collectionName;
this.mongoClient = mongoClient;
}
private collection(): Bluebird<MongoDB.Collection> {
return this.mongoClient.collection(this.collectionName);
}
find(query: any, sortKeys?: any, count?: number): Bluebird<any> {
return this.collection()
.then((collection) => collection.find(query).sort(sortKeys).limit(count))
.then((query) => query.toArray());
}
findOne(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.findOne(query));
}
update(query: any, updateQuery: any, options?: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.update(query, updateQuery, options));
}
remove(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.remove(query));
}
insert(document: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.insert(document));
}
count(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.count(query));
}
} | Fix typing issue when using Dockerfile.dev. | Fix typing issue when using Dockerfile.dev.
| TypeScript | mit | clems4ever/authelia,clems4ever/authelia,clems4ever/authelia,clems4ever/two-factor-auth-server,clems4ever/two-factor-auth-server,clems4ever/authelia,clems4ever/authelia | ---
+++
@@ -43,7 +43,7 @@
.then((collection) => collection.insert(document));
}
- count(query: any): Bluebird<number> {
+ count(query: any): Bluebird<any> {
return this.collection()
.then((collection) => collection.count(query));
} |
dbdc2e238d7a8665cf9a8acf000c95098caf1c46 | src/config.ts | src/config.ts | import $ from 'jquery';
import {TrackingEventHandler, TrackEventType, TrackingData} from './tracking';
import usersessioncookiepersister from './usersessioncookiepersister';
import {UserAgentInfo} from './useragentinfo';
export interface UserSessionPersister {
loadUserSession(): string | null;
saveUserSession(userSession: string, daysToLive: number): void;
}
export interface ConditionFunction {
(userAgentInfo: UserAgentInfo): boolean;
}
export interface SplitTestConfig {
cookieName: string;
globalCondition: ConditionFunction;
sessionPersister: UserSessionPersister;
tracking: TrackingEventHandler;
uiCondition: ConditionFunction;
userSessionDaysToLive: number;
}
const defaultTrackingEventHandler: TrackingEventHandler = (() => {
function log(event: TrackEventType, trackingData: TrackingData) {
console.log('Split testing event: ' + event, trackingData);
}
return {
track: log,
trackLink(elements: Element | JQuery, event: TrackEventType, trackingData: TrackingData) {
$(elements).on('click', () => {
log(event, trackingData);
});
}
};
})();
const config: SplitTestConfig = {
cookieName: 'trustpilotABTest',
globalCondition: () => true,
sessionPersister: usersessioncookiepersister,
tracking: defaultTrackingEventHandler,
userSessionDaysToLive: 3,
uiCondition: () => false,
};
export default config;
| import $ from 'jquery';
import {TrackingEventHandler, TrackEventType, TrackingData} from './tracking';
import usersessioncookiepersister from './usersessioncookiepersister';
import {UserAgentInfo} from './useragentinfo';
export interface UserSessionPersister {
loadUserSession(): string | null;
saveUserSession(userSession: string, daysToLive: number): void;
}
export interface ConditionFunction {
(userAgentInfo: UserAgentInfo): boolean;
}
export interface SplitTestConfig {
cookieName: string;
globalCondition: ConditionFunction;
sessionPersister: UserSessionPersister;
tracking: TrackingEventHandler;
uiCondition: ConditionFunction;
userSessionDaysToLive: number;
}
const defaultTrackingEventHandler: TrackingEventHandler = (() => {
function log(event: TrackEventType, trackingData: TrackingData) {
console.log('Split testing event: ' + event, trackingData);
}
return {
track: log,
trackLink(elements: Element | JQuery, event: TrackEventType, trackingData: TrackingData) {
$(elements).on('click', () => {
log(event, trackingData);
});
}
};
})();
const config: SplitTestConfig = {
cookieName: 'skiftABTest',
globalCondition: () => true,
sessionPersister: usersessioncookiepersister,
tracking: defaultTrackingEventHandler,
userSessionDaysToLive: 3,
uiCondition: () => false
};
export default config;
| Change the default cookie name | Change the default cookie name
| TypeScript | mit | trustpilot/skift,trustpilot/skift | ---
+++
@@ -37,12 +37,12 @@
})();
const config: SplitTestConfig = {
- cookieName: 'trustpilotABTest',
+ cookieName: 'skiftABTest',
globalCondition: () => true,
sessionPersister: usersessioncookiepersister,
tracking: defaultTrackingEventHandler,
userSessionDaysToLive: 3,
- uiCondition: () => false,
+ uiCondition: () => false
};
export default config; |
1e7c91d9624ac5a0667e8a5c90e7e93a5fa54179 | Signum.React.Extensions/Authorization/Login/LoginUserControl.tsx | Signum.React.Extensions/Authorization/Login/LoginUserControl.tsx | import * as React from 'react'
import { NavDropdown, MenuItem, NavItem } from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'
import { AuthMessage, UserEntity } from '../Signum.Entities.Authorization'
import * as AuthClient from '../AuthClient'
export default class LoginUserControl extends React.Component<{}, { user: UserEntity }> {
render() {
const user = AuthClient.currentUser();
if (!user)
return <LinkContainer to="~/auth/login"><NavItem className="sf-login">{AuthMessage.Login.niceToString() }</NavItem></LinkContainer>;
return (
<NavDropdown className="sf-user" title={user.userName!} id="sfUserDropDown">
<LinkContainer to="~/auth/changePassword"><MenuItem><i className="fa fa-key fa-fw"></i> {AuthMessage.ChangePassword.niceToString()}</MenuItem></LinkContainer>
<MenuItem divider />
<MenuItem id="sf-auth-logout" onSelect={() => AuthClient.logout()}><i className="fa fa-sign-out fa-fw"></i> {AuthMessage.Logout.niceToString()}</MenuItem>
</NavDropdown>
);
}
}
| import * as React from 'react'
import { NavDropdown, MenuItem, NavItem } from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'
import { AuthMessage, UserEntity } from '../Signum.Entities.Authorization'
import * as AuthClient from '../AuthClient'
export default class LoginUserControl extends React.Component<{}, { user: UserEntity }> {
render() {
const user = AuthClient.currentUser();
if (!user)
return <LinkContainer to="~/auth/login" className="sf-login"><NavItem>{AuthMessage.Login.niceToString() }</NavItem></LinkContainer>;
return (
<NavDropdown className="sf-user" title={user.userName!} id="sfUserDropDown">
<LinkContainer to="~/auth/changePassword"><MenuItem><i className="fa fa-key fa-fw"></i> {AuthMessage.ChangePassword.niceToString()}</MenuItem></LinkContainer>
<MenuItem divider />
<MenuItem id="sf-auth-logout" onSelect={() => AuthClient.logout()}><i className="fa fa-sign-out fa-fw"></i> {AuthMessage.Logout.niceToString()}</MenuItem>
</NavDropdown>
);
}
}
| Move Login Classname due to Updates | Move Login Classname due to Updates
| TypeScript | mit | signumsoftware/framework,signumsoftware/extensions,MehdyKarimpour/extensions,signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,AlejandroCano/extensions | ---
+++
@@ -10,7 +10,7 @@
const user = AuthClient.currentUser();
if (!user)
- return <LinkContainer to="~/auth/login"><NavItem className="sf-login">{AuthMessage.Login.niceToString() }</NavItem></LinkContainer>;
+ return <LinkContainer to="~/auth/login" className="sf-login"><NavItem>{AuthMessage.Login.niceToString() }</NavItem></LinkContainer>;
return (
<NavDropdown className="sf-user" title={user.userName!} id="sfUserDropDown"> |
a34d7e47cc7c79bf7f776ee9a431c7c1037681f7 | src/app/bills/address-view.ts | src/app/bills/address-view.ts | export class AddressView {
constructor(private readonly address: string) {}
get billName() {
return this.firstLinesWithoutLastTwo.join(' ').substring(0, 70)
}
get billAddress() {
return this.secondLastLine.substring(0, 70)
}
get billZip() {
return this.zipAndCity[1]
}
get billCity() {
return this.zipAndCity[1]
}
get billCountry() {
return 'CH'
}
private get zipAndCity() {
const [zip, ...cityParts] = this.lastLine.split(' ')
return [zip, cityParts.join(' ')]
}
get lines() {
return this.address.split('\n').filter((line) => line)
}
get commaSeparated() {
return this.lines.join(', ')
}
get firstLine() {
return this.lines[0]
}
get firstLinesWithoutLastTwo() {
return this.lines.filter(
(_, index) => index !== this.lines.length - 2 && index !== this.lines.length - 1
)
}
get secondLastLine() {
return this.lines[this.lines.length - 2]
}
get lastLine() {
return this.lines[this.lines.length - 1]
}
get middleLines() {
return this.lines.filter((_, index) => index !== 0 && index !== this.lines.length - 1)
}
}
| export class AddressView {
constructor(private readonly address: string) {}
get billName() {
return this.firstLinesWithoutLastTwo.join(' ').substring(0, 70)
}
get billAddress() {
return this.secondLastLine.substring(0, 70)
}
get billZip() {
return this.zipAndCity[0]
}
get billCity() {
return this.zipAndCity[1]
}
get billCountry() {
return 'CH'
}
private get zipAndCity() {
const [zip, ...cityParts] = this.lastLine.split(' ')
return [zip, cityParts.join(' ')]
}
get lines() {
return this.address.split('\n').filter((line) => line)
}
get commaSeparated() {
return this.lines.join(', ')
}
get firstLine() {
return this.lines[0]
}
get firstLinesWithoutLastTwo() {
return this.lines.filter(
(_, index) => index !== this.lines.length - 2 && index !== this.lines.length - 1
)
}
get secondLastLine() {
return this.lines[this.lines.length - 2]
}
get lastLine() {
return this.lines[this.lines.length - 1]
}
get middleLines() {
return this.lines.filter((_, index) => index !== 0 && index !== this.lines.length - 1)
}
}
| Fix qr bill zip code | Fix qr bill zip code
| TypeScript | mit | lukaselmer/sanhei-bills2,lukaselmer/sanhei-bills2,lukaselmer/sanhei-bills2,lukaselmer/sanhei-bills2 | ---
+++
@@ -10,7 +10,7 @@
}
get billZip() {
- return this.zipAndCity[1]
+ return this.zipAndCity[0]
}
get billCity() { |
f62ad32b33c8850e7c05e5e77e4c3de2011b1504 | src/repeat/index.ts | src/repeat/index.ts |
import { Server } from "../server";
import { RethinkDB } from "../rethinkdb";
interface IRepeats {
[token: string]: {
[command: string]: {
command: string;
period: number;
timeout: number;
};
}[];
};
export class Repeat {
private activeRepeats: IRepeats = {};
constructor(public server: Server, public rethink: RethinkDB) { }
addRepeat(packet: Object): boolean {
let repeat: any = packet;
if (!repeat.token || !repeat.command || !repeat.period) {
return false;
}
if (this.activeRepeats[repeat.token] === (null || undefined)) {
this.activeRepeats[repeat.token] = [];
}
repeat.period = repeat.period * 1000
let document: any = {
command: repeat.command,
period: repeat.period,
timeout: this.startRepeat(repeat)
};
this.activeRepeats[repeat.token][repeat.command] = document;
return true;
}
removeRepeat(packet: Object) {
let data: any = packet;
delete this.activeRepeats[data.token][data.command]
}
private startRepeat(packet: Object): number {
let data: any = packet;
return setInterval(() => {
this.server.broadcastToChannel(data.token, null, "repeat", null, data);
}, data.period);
}
}
|
import { Server } from "../server";
import { RethinkDB } from "../rethinkdb";
interface IRepeats {
[token: string]: {
[command: string]: {
command: string;
period: number;
timeout: number;
};
}[];
};
export class Repeat {
private activeRepeats: IRepeats = {};
constructor(public server: Server, public rethink: RethinkDB) { }
addRepeat(packet: Object): boolean {
let repeat: any = packet;
if (!repeat.token || !repeat.command || !repeat.period) {
return false;
}
if (this.activeRepeats[repeat.token] === (null || undefined)) {
this.activeRepeats[repeat.token] = [];
}
repeat.period = repeat.period * 1000
Promise.resolve(this.rethink.getCommand(repeat.command)).then((data: any) => {
if (data != ([] || null || undefined || {})) {
repeat.command = data[0];
} else {
repeat.command = {};
}
});
let document: any = {
command: repeat.command,
period: repeat.period,
timeout: this.startRepeat(repeat)
};
this.activeRepeats[repeat.token][repeat.command] = document;
return true;
}
removeRepeat(packet: Object) {
let data: any = packet;
delete this.activeRepeats[data.token][data.command]
}
private startRepeat(packet: Object): number {
let data: any = packet;
return setInterval(() => {
this.server.broadcastToChannel(data.token, null, "repeat", null, data);
}, data.period);
}
}
| Add command to repeat packet | Add command to repeat packet
| TypeScript | mit | CactusBot/Sepal,CactusDev/Sepal,CactusDev/Sepal | ---
+++
@@ -29,6 +29,13 @@
}
repeat.period = repeat.period * 1000
+ Promise.resolve(this.rethink.getCommand(repeat.command)).then((data: any) => {
+ if (data != ([] || null || undefined || {})) {
+ repeat.command = data[0];
+ } else {
+ repeat.command = {};
+ }
+ });
let document: any = {
command: repeat.command, |
74d6c37c8bb4e8a7f5e1606ed9655933162d6fb5 | src/testing/testing-module.ts | src/testing/testing-module.ts | import * as optional from 'optional';
import { NestContainer } from '@nestjs/core/injector/container';
import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface';
import { NestApplication, NestApplicationContext } from '@nestjs/core';
import { INestApplication, INestMicroservice } from '@nestjs/common';
import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface';
import { MicroservicesPackageNotFoundException } from '@nestjs/core/errors/exceptions/microservices-package-not-found.exception';
const { NestMicroservice } =
optional('@nestjs/microservices/nest-microservice') || ({} as any);
export class TestingModule extends NestApplicationContext {
constructor(
container: NestContainer,
scope: NestModuleMetatype[],
contextModule,
) {
super(container, scope, contextModule);
}
public createNestApplication(express?): INestApplication {
return new NestApplication(this.container, express);
}
public createNestMicroservice(
config: MicroserviceConfiguration,
): INestMicroservice {
if (!NestMicroservice) {
throw new MicroservicesPackageNotFoundException();
}
return new NestMicroservice(this.container, config);
}
}
| import * as express from 'express';
import * as optional from 'optional';
import { NestContainer } from '@nestjs/core/injector/container';
import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface';
import { NestApplication, NestApplicationContext } from '@nestjs/core';
import { INestApplication, INestMicroservice } from '@nestjs/common';
import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface';
import { MicroservicesPackageNotFoundException } from '@nestjs/core/errors/exceptions/microservices-package-not-found.exception';
const { NestMicroservice } =
optional('@nestjs/microservices/nest-microservice') || ({} as any);
export class TestingModule extends NestApplicationContext {
constructor(
container: NestContainer,
scope: NestModuleMetatype[],
contextModule,
) {
super(container, scope, contextModule);
}
public createNestApplication(express = express()): INestApplication {
return new NestApplication(this.container, express);
}
public createNestMicroservice(
config: MicroserviceConfiguration,
): INestMicroservice {
if (!NestMicroservice) {
throw new MicroservicesPackageNotFoundException();
}
return new NestMicroservice(this.container, config);
}
}
| Create express server if not provided in testing | Create express server if not provided in testing | TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -1,3 +1,4 @@
+import * as express from 'express';
import * as optional from 'optional';
import { NestContainer } from '@nestjs/core/injector/container';
import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface';
@@ -18,7 +19,7 @@
super(container, scope, contextModule);
}
- public createNestApplication(express?): INestApplication {
+ public createNestApplication(express = express()): INestApplication {
return new NestApplication(this.container, express);
}
|
d3804fb98603b766aeb738db4852b2059ab892c0 | src/web/views/ChapterView.tsx | src/web/views/ChapterView.tsx | import * as React from 'react';
import * as mobxReact from 'mobx-react';
import * as mio from '../';
@mobxReact.observer
export class ChapterView extends React.Component<{vm: mio.ChapterViewModel}> {
// TODO: Inline styles like this are pretty bad, eh.
render() {
return (
<div onClick={e => this._onClick(e)} style={{bottom: 0, left: 0, right: 0, position: 'absolute', top: 0}}>
<img src={this.props.vm.img} style={{
display: 'block',
height: '100%',
margin: '0 auto'
}} />
</div>
);
}
private _onClick(e: React.MouseEvent<HTMLDivElement>) {
let tresholdX = window.innerWidth / 2;
let tresholdY = window.innerHeight / 3;
if (e.clientY < tresholdY) {
this.props.vm.close();
} else if (e.clientX < tresholdX) {
this.props.vm.nextPageAsync();
} else {
this.props.vm.previousPageAsync();
}
}
}
| import * as React from 'react';
import * as mobxReact from 'mobx-react';
import * as mio from '../';
@mobxReact.observer
export class ChapterView extends React.Component<{vm: mio.ChapterViewModel}> {
// TODO: Inline styles like this are pretty bad, eh.
render() {
return (
<div onClick={e => this._onClick(e)} style={{bottom: 0, left: 0, right: 0, position: 'absolute', top: 0}}>
<img src={this.props.vm.img} style={{
display: 'block',
maxHeight: '100%',
maxWidth: '100%',
position: 'absolute',
left: '50%',
top: '50%',
transform: 'translate(-50%, -50%)'
}} />
</div>
);
}
private _onClick(e: React.MouseEvent<HTMLDivElement>) {
let tresholdX = window.innerWidth / 2;
let tresholdY = window.innerHeight / 3;
if (e.clientY < tresholdY) {
this.props.vm.close();
} else if (e.clientX < tresholdX) {
this.props.vm.nextPageAsync();
} else {
this.props.vm.previousPageAsync();
}
}
}
| Fix image positioning to be absolute centered and scale both w/h | [Client] Fix image positioning to be absolute centered and scale both w/h
| TypeScript | mit | Deathspike/mangarack.js,MangaRack/mangarack,MangaRack/mangarack,Deathspike/mangarack.js,MangaRack/mangarack,Deathspike/mangarack.js | ---
+++
@@ -10,8 +10,12 @@
<div onClick={e => this._onClick(e)} style={{bottom: 0, left: 0, right: 0, position: 'absolute', top: 0}}>
<img src={this.props.vm.img} style={{
display: 'block',
- height: '100%',
- margin: '0 auto'
+ maxHeight: '100%',
+ maxWidth: '100%',
+ position: 'absolute',
+ left: '50%',
+ top: '50%',
+ transform: 'translate(-50%, -50%)'
}} />
</div>
); |
85f91da4638ce52cf76b520972f634f9ee68dbfe | packages/shared/lib/helpers/cookies.ts | packages/shared/lib/helpers/cookies.ts | import isTruthy from './isTruthy';
export const getCookies = (): string[] => {
try {
return document.cookie.split(';').map((item) => item.trim());
} catch (e) {
return [];
}
};
export const getCookie = (name: string, cookies = document.cookie) => {
return `; ${cookies}`.match(`;\\s*${name}=([^;]+)`)?.[1];
};
export const checkCookie = (name: string, value: string) => {
return getCookies().some((cookie) => cookie.includes(`${name}=${value}`));
};
export interface SetCookieArguments {
cookieName: string;
cookieValue: string | undefined;
expirationDate?: string;
path?: string;
cookieDomain?: string;
}
export const setCookie = ({
cookieName,
cookieValue: maybeCookieValue,
expirationDate: maybeExpirationDate,
path,
cookieDomain,
}: SetCookieArguments) => {
const expirationDate = maybeCookieValue === undefined ? new Date(0).toUTCString() : maybeExpirationDate;
const cookieValue = maybeCookieValue === undefined ? '' : maybeCookieValue;
document.cookie = [
`${cookieName}=${cookieValue}`,
expirationDate && `expires=${expirationDate}`,
cookieDomain && `domain=${cookieDomain}`,
path && `path=${path}`,
]
.filter(isTruthy)
.join(';');
};
| import isTruthy from './isTruthy';
export const getCookies = (): string[] => {
try {
return document.cookie.split(';').map((item) => item.trim());
} catch (e) {
return [];
}
};
export const getCookie = (name: string, cookies = document.cookie) => {
return `; ${cookies}`.match(`;\\s*${name}=([^;]+)`)?.[1];
};
export const checkCookie = (name: string, value: string) => {
return getCookies().some((cookie) => cookie.includes(`${name}=${value}`));
};
export interface SetCookieArguments {
cookieName: string;
cookieValue: string | undefined;
expirationDate?: string;
path?: string;
cookieDomain?: string;
}
export const setCookie = ({
cookieName,
cookieValue: maybeCookieValue,
expirationDate: maybeExpirationDate,
path,
cookieDomain,
}: SetCookieArguments) => {
const expirationDate = maybeExpirationDate === undefined ? new Date(0).toUTCString() : maybeExpirationDate;
const cookieValue = maybeCookieValue === undefined ? '' : maybeCookieValue;
document.cookie = [
`${cookieName}=${cookieValue}`,
expirationDate && `expires=${expirationDate}`,
cookieDomain && `domain=${cookieDomain}`,
path && `path=${path}`,
]
.filter(isTruthy)
.join(';');
};
| Fix variable typo bug for cookie expiration date | Fix variable typo bug for cookie expiration date
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -31,7 +31,7 @@
path,
cookieDomain,
}: SetCookieArguments) => {
- const expirationDate = maybeCookieValue === undefined ? new Date(0).toUTCString() : maybeExpirationDate;
+ const expirationDate = maybeExpirationDate === undefined ? new Date(0).toUTCString() : maybeExpirationDate;
const cookieValue = maybeCookieValue === undefined ? '' : maybeCookieValue;
document.cookie = [
`${cookieName}=${cookieValue}`, |
450a63e2e84a41b868b70588f19d76bd481f80a6 | src/app/js/component/button/fetch-button.tsx | src/app/js/component/button/fetch-button.tsx | import * as ReactDOM from "react-dom";
import * as React from "react";
import { ComponentsRefs } from "./../../components-refs";
import { Button } from "./button";
export class FetchButton extends Button<{}, {}> {
constructor() {
super();
this.state = {
isFetching: true
};
this.onClick = this.onClick.bind(this);
}
render() {
return (
<li>
<i onClick={this.onClick} className="fa fa-download"></i>
</li>
);
}
onClick(event: React.MouseEvent<HTMLElement>) {
const target = event.currentTarget;
this.switchDisplay(target);
ComponentsRefs.feedList.fetchAll().then((result) => {
if (result.success) ComponentsRefs.alertList.alert(`Successfully fetch ${result.success} feed${result.success > 1 ? "s" : ""}`, "success");
if (result.fail) ComponentsRefs.alertList.alert(`Fail to fetch ${result.fail} feed${result.fail > 1 ? "s" : ""}`, "error");
this.switchDisplay(target);
});
}
switchDisplay(target: EventTarget & HTMLElement) {
target.classList.toggle("fa-download");
target.classList.toggle("fa-refresh");
target.classList.toggle("fa-spin");
target.classList.toggle("white-icon");
}
}
interface FetchButtonState {
isFetching: boolean;
}
| import * as ReactDOM from "react-dom";
import * as React from "react";
import { ComponentsRefs } from "./../../components-refs";
import { Button } from "./button";
export class FetchButton extends Button<{}, FetchButtonState> {
constructor() {
super();
this.state = {
isFetching: false
};
this.onClick = this.onClick.bind(this);
}
render() {
return (
<li>
<i onClick={this.onClick} className="fa fa-download"></i>
</li>
);
}
onClick(event: React.MouseEvent<HTMLElement>) {
if (!this.state.isFetching) {
const target = event.currentTarget;
this.switchDisplay(target);
ComponentsRefs.feedList.fetchAll().then((result) => {
if (result.success) ComponentsRefs.alertList.alert(`Successfully fetch ${result.success} feed${result.success > 1 ? "s" : ""}`, "success");
if (result.fail) ComponentsRefs.alertList.alert(`Fail to fetch ${result.fail} feed${result.fail > 1 ? "s" : ""}`, "error");
this.switchDisplay(target);
});
}
}
switchDisplay(target: EventTarget & HTMLElement) {
target.classList.toggle("fa-download");
target.classList.toggle("fa-refresh");
target.classList.toggle("fa-spin");
target.classList.toggle("white-icon");
this.editState({ isFetching: !this.state.isFetching });
}
}
interface FetchButtonState {
isFetching: boolean;
}
| Fix fetch all button behavior | Fix fetch all button behavior
| TypeScript | mit | Xstoudi/alduin,Xstoudi/alduin,Xstoudi/alduin | ---
+++
@@ -4,13 +4,13 @@
import { ComponentsRefs } from "./../../components-refs";
import { Button } from "./button";
-export class FetchButton extends Button<{}, {}> {
+export class FetchButton extends Button<{}, FetchButtonState> {
constructor() {
super();
this.state = {
- isFetching: true
+ isFetching: false
};
this.onClick = this.onClick.bind(this);
@@ -25,14 +25,16 @@
}
onClick(event: React.MouseEvent<HTMLElement>) {
- const target = event.currentTarget;
- this.switchDisplay(target);
- ComponentsRefs.feedList.fetchAll().then((result) => {
- if (result.success) ComponentsRefs.alertList.alert(`Successfully fetch ${result.success} feed${result.success > 1 ? "s" : ""}`, "success");
- if (result.fail) ComponentsRefs.alertList.alert(`Fail to fetch ${result.fail} feed${result.fail > 1 ? "s" : ""}`, "error");
+ if (!this.state.isFetching) {
+ const target = event.currentTarget;
+ this.switchDisplay(target);
+ ComponentsRefs.feedList.fetchAll().then((result) => {
+ if (result.success) ComponentsRefs.alertList.alert(`Successfully fetch ${result.success} feed${result.success > 1 ? "s" : ""}`, "success");
+ if (result.fail) ComponentsRefs.alertList.alert(`Fail to fetch ${result.fail} feed${result.fail > 1 ? "s" : ""}`, "error");
- this.switchDisplay(target);
- });
+ this.switchDisplay(target);
+ });
+ }
}
switchDisplay(target: EventTarget & HTMLElement) {
@@ -40,6 +42,7 @@
target.classList.toggle("fa-refresh");
target.classList.toggle("fa-spin");
target.classList.toggle("white-icon");
+ this.editState({ isFetching: !this.state.isFetching });
}
}
|
a55269774bfcaf9ed3ecbb972715b23ceaf8e2d2 | src/rest-api/login/loginAPI.real.ts | src/rest-api/login/loginAPI.real.ts | import { LoginCredentials } from '../../model/login/loginCredentials';
import { LoginResponse } from '../../model/login/loginResponse';
import { loginMockResponses } from './loginMockData';
import { LoginFunction } from './loginAPI.contract';
// TODO: REPLACE WITH REAL CALL TO API REST WHEN READY
export const login: LoginFunction = (loginInfo: LoginCredentials): Promise<LoginResponse> => {
const promise = new Promise<LoginResponse>((resolve, reject) => {
// TODO: Use env variable for the base URL
// 'http://localhost:5000/api/login'
fetch('http://localhost:5000/api/login', {
method: 'POST',
mode : 'cors',
credentials : 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
loginName: loginInfo.login,
password: loginInfo.password,
}),
})
.then((response) => {
const loginResponse = new LoginResponse();
loginResponse.succeded = true;
// TODO: Temporary get this info from api
loginResponse.userProfile = {
id: 2,
fullname: 'Trainer',
role: 'trainer',
email: 'trainer',
avatar:
'https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-64.png',
};
resolve(loginResponse);
})
.catch((err) => {
reject(err);
});
});
return promise;
};
| import { LoginCredentials } from '../../model/login/loginCredentials';
import { LoginResponse } from '../../model/login/loginResponse';
import { loginMockResponses } from './loginMockData';
import { LoginFunction } from './loginAPI.contract';
export const login: LoginFunction = (loginInfo: LoginCredentials): Promise<LoginResponse> => {
return fetch('http://localhost:5000/api/login', {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: loginInfo.login,
password: loginInfo.password,
}),
}).then((response) => (
response.ok ?
handleSuccessLogin(response) :
handleFailLogin(response)
)).catch((err) => {
Promise.reject(err);
});
};
const handleSuccessLogin = (response: Response): Promise<LoginResponse> => {
const loginResponse = new LoginResponse();
loginResponse.succeded = true;
// TODO: Temporary get this info from api
loginResponse.userProfile = {
id: 2,
fullname: 'Trainer',
role: 'trainer',
email: 'trainer',
avatar: 'https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-64.png',
};
return Promise.resolve(loginResponse);
};
const handleFailLogin = (response: Response): Promise<LoginResponse> => {
const loginResponse = new LoginResponse();
loginResponse.succeded = false;
return Promise.resolve(loginResponse);
};
| Handle success and fail login | Handle success and fail login
| TypeScript | mit | MasterLemon2016/LeanMood,Lemoncode/LeanMood,MasterLemon2016/LeanMood,Lemoncode/LeanMood,Lemoncode/LeanMood,MasterLemon2016/LeanMood | ---
+++
@@ -3,46 +3,46 @@
import { loginMockResponses } from './loginMockData';
import { LoginFunction } from './loginAPI.contract';
-// TODO: REPLACE WITH REAL CALL TO API REST WHEN READY
export const login: LoginFunction = (loginInfo: LoginCredentials): Promise<LoginResponse> => {
+ return fetch('http://localhost:5000/api/login', {
+ method: 'POST',
+ mode: 'cors',
+ credentials: 'include',
+ headers: {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ email: loginInfo.login,
+ password: loginInfo.password,
+ }),
+ }).then((response) => (
+ response.ok ?
+ handleSuccessLogin(response) :
+ handleFailLogin(response)
+ )).catch((err) => {
+ Promise.reject(err);
+ });
+};
- const promise = new Promise<LoginResponse>((resolve, reject) => {
+const handleSuccessLogin = (response: Response): Promise<LoginResponse> => {
+ const loginResponse = new LoginResponse();
+ loginResponse.succeded = true;
+ // TODO: Temporary get this info from api
+ loginResponse.userProfile = {
+ id: 2,
+ fullname: 'Trainer',
+ role: 'trainer',
+ email: 'trainer',
+ avatar: 'https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-64.png',
+ };
- // TODO: Use env variable for the base URL
- // 'http://localhost:5000/api/login'
- fetch('http://localhost:5000/api/login', {
- method: 'POST',
- mode : 'cors',
- credentials : 'include',
- headers: {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- loginName: loginInfo.login,
- password: loginInfo.password,
- }),
- })
- .then((response) => {
- const loginResponse = new LoginResponse();
- loginResponse.succeded = true;
- // TODO: Temporary get this info from api
- loginResponse.userProfile = {
- id: 2,
- fullname: 'Trainer',
- role: 'trainer',
- email: 'trainer',
- avatar:
- 'https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-64.png',
- };
+ return Promise.resolve(loginResponse);
+};
- resolve(loginResponse);
- })
- .catch((err) => {
- reject(err);
- });
+const handleFailLogin = (response: Response): Promise<LoginResponse> => {
+ const loginResponse = new LoginResponse();
+ loginResponse.succeded = false;
- });
-
- return promise;
+ return Promise.resolve(loginResponse);
}; |
b2d968d8fddf9442a5e15585e61078da811e124b | app/components/renderForQuestions/answerState.ts | app/components/renderForQuestions/answerState.ts | import {Response} from "quill-marking-logic"
interface Attempt {
response: Response
}
function getAnswerState(attempt: Attempt|undefined): boolean {
if (attempt) {
return (!!attempt.response.optimal && attempt.response.author === undefined)
}
return false
}
export default getAnswerState; | import {Response} from "quill-marking-logic"
interface Attempt {
response: Response
}
function getAnswerState(attempt: Attempt|undefined): boolean {
if (attempt) {
return (attempt.response.optimal)
}
return false
}
export default getAnswerState; | Update logic for feedback status bar color | Update logic for feedback status bar color
| TypeScript | agpl-3.0 | empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core,empirical-org/Empirical-Core | ---
+++
@@ -6,7 +6,7 @@
function getAnswerState(attempt: Attempt|undefined): boolean {
if (attempt) {
- return (!!attempt.response.optimal && attempt.response.author === undefined)
+ return (attempt.response.optimal)
}
return false
} |
2dbd2f937546bab81f7e243c728c18a7dfe197b9 | test/typescript.ts | test/typescript.ts | import * as merge from '../';
const x = {
foo: 'abc',
bar: 'def',
}
const y = {
foo: 'cba',
bar: 'fed',
}
const z = {
baz: '123',
quux: '456',
}
let merged1 = merge(x, y);
let merged2 = merge(x, z);
let merged3 = merge.all([ x, y, z ]);
merged1.foo;
merged1.bar;
merged2.foo;
merged2.baz;
const options1: merge.Options = {
clone: true,
isMergeableObject (obj) {
return false;
},
};
const options2: merge.Options = {
arrayMerge (target, source, options) {
target.length;
source.length;
options.isMergeableObject(target);
return [];
},
clone: true,
isMergeableObject (obj) {
return false;
},
};
merged1 = merge(x, y, options1);
merged2 = merge(x, z, options2);
merged3 = merge([x, y, z], options1);
| import * as merge from '../';
const x = {
foo: 'abc',
bar: 'def',
}
const y = {
foo: 'cba',
bar: 'fed',
}
const z = {
baz: '123',
quux: '456',
}
let merged1 = merge(x, y);
let merged2 = merge(x, z);
let merged3 = merge.all([ x, y, z ]);
merged1.foo;
merged1.bar;
merged2.foo;
merged2.baz;
const options1: merge.Options = {
clone: true,
isMergeableObject (obj) {
return false;
},
};
const options2: merge.Options = {
arrayMerge (target, source, options) {
target.length;
source.length;
options.isMergeableObject(target);
return [];
},
clone: true,
isMergeableObject (obj) {
return false;
},
};
merged1 = merge(x, y, options1);
merged2 = merge(x, z, options2);
merged3 = merge.all([x, y, z], options1);
| Fix another type test issue | Fix another type test issue
| TypeScript | mit | KyleAMathews/deepmerge,KyleAMathews/deepmerge | ---
+++
@@ -47,4 +47,4 @@
merged1 = merge(x, y, options1);
merged2 = merge(x, z, options2);
-merged3 = merge([x, y, z], options1);
+merged3 = merge.all([x, y, z], options1); |
9abfa4c78ce41493bdc0e6da0d812b1d9aa30344 | typings/sweetalert.d.ts | typings/sweetalert.d.ts | import swal, { SweetAlert } from "./core";
declare global {
const swal: SweetAlert;
const sweetAlert: SweetAlert;
}
export default swal;
export as namespace swal;
| import { SweetAlert } from "./core";
declare global {
const sweetAlert: SweetAlert;
}
declare const swal: SweetAlert;
export default swal;
export as namespace swal;
| Fix Error to TypeScript Import | Fix Error to TypeScript Import
| TypeScript | mit | t4t5/sweetalert,t4t5/sweetalert | ---
+++
@@ -1,9 +1,8 @@
-import swal, { SweetAlert } from "./core";
+import { SweetAlert } from "./core";
declare global {
- const swal: SweetAlert;
const sweetAlert: SweetAlert;
}
-
+declare const swal: SweetAlert;
export default swal;
export as namespace swal; |
daa33469dbcb1f7295cf4070463a77ba06927f11 | scripts/index.ts | scripts/index.ts | import 'app.scss'; // styles
import 'vendor';
import 'core';
import 'templates-cache.generated'; // generated by grunt 'ngtemplates' task
import 'apps';
import 'external-apps';
/* globals __SUPERDESK_CONFIG__: true */
const appConfig = __SUPERDESK_CONFIG__;
if (appConfig.features.useTansaProofing) {
require('apps/tansa');
}
let body = angular.element('body');
function initializeConfigDefaults(config) {
const sunday = '0';
return {
...config,
startingDay: config.startingDay != null ? config.startingDay : sunday,
};
}
body.ready(() => {
// update config via config.js
if (window.superdeskConfig) {
angular.merge(appConfig, window.superdeskConfig);
}
// non-mock app configuration must live here to allow tests to override
// since tests do not import this file.
angular.module('superdesk.config').constant('config', initializeConfigDefaults(appConfig));
/**
* @ngdoc module
* @name superdesk-client
* @packageName superdesk-client
* @description The root superdesk module.
*/
angular.bootstrap(body, [
'superdesk.config',
'superdesk.core',
'superdesk.apps',
].concat(appConfig.apps || []), {strictDi: true});
window['superdeskIsReady'] = true;
});
| import 'app.scss'; // styles
import 'vendor';
import 'core';
import 'templates-cache.generated'; // generated by grunt 'ngtemplates' task
import 'apps';
import 'external-apps';
/* globals __SUPERDESK_CONFIG__: true */
const appConfig = __SUPERDESK_CONFIG__;
if (appConfig.features.useTansaProofing) {
// tslint:disable-next-line:no-var-requires
require('apps/tansa');
}
let body = angular.element('body');
function initializeConfigDefaults(config) {
const sunday = '0';
return {
...config,
startingDay: config.startingDay != null ? config.startingDay : sunday,
};
}
body.ready(() => {
// update config via config.js
if (window.superdeskConfig) {
angular.merge(appConfig, window.superdeskConfig);
}
// non-mock app configuration must live here to allow tests to override
// since tests do not import this file.
angular.module('superdesk.config').constant('config', initializeConfigDefaults(appConfig));
/**
* @ngdoc module
* @name superdesk-client
* @packageName superdesk-client
* @description The root superdesk module.
*/
angular.bootstrap(body, [
'superdesk.config',
'superdesk.core',
'superdesk.apps',
].concat(appConfig.apps || []), {strictDi: true});
window['superdeskIsReady'] = true;
});
| Disable tslint error for tansa load. | Disable tslint error for tansa load.
| TypeScript | agpl-3.0 | superdesk/superdesk-client-core,petrjasek/superdesk-client-core,petrjasek/superdesk-client-core,mdhaman/superdesk-client-core,pavlovicnemanja/superdesk-client-core,superdesk/superdesk-client-core,petrjasek/superdesk-client-core,mdhaman/superdesk-client-core,marwoodandrew/superdesk-client-core,pavlovicnemanja/superdesk-client-core,mdhaman/superdesk-client-core,marwoodandrew/superdesk-client-core,pavlovicnemanja/superdesk-client-core,superdesk/superdesk-client-core,marwoodandrew/superdesk-client-core,pavlovicnemanja/superdesk-client-core,superdesk/superdesk-client-core,pavlovicnemanja/superdesk-client-core,marwoodandrew/superdesk-client-core,petrjasek/superdesk-client-core,petrjasek/superdesk-client-core,marwoodandrew/superdesk-client-core,superdesk/superdesk-client-core,mdhaman/superdesk-client-core,mdhaman/superdesk-client-core | ---
+++
@@ -9,6 +9,7 @@
const appConfig = __SUPERDESK_CONFIG__;
if (appConfig.features.useTansaProofing) {
+ // tslint:disable-next-line:no-var-requires
require('apps/tansa');
}
|
6edee28b4fdfb5ea212d4f2554e587938fcf408d | applications/mail/src/app/components/conversation/TrashWarning.tsx | applications/mail/src/app/components/conversation/TrashWarning.tsx | import React from 'react';
import { c } from 'ttag';
import { InlineLinkButton, Icon } from 'react-components';
interface Props {
inTrash: boolean;
filter: boolean;
onToggle: () => void;
}
const TrashWarning = ({ inTrash, filter, onToggle }: Props) => {
return (
<div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-light">
<div className="flex flex-nowrap flex-items-center">
<Icon name="trash" className="mr1" />
<span>
{inTrash
? c('Info').t`This conversation contains non-trashed messages.`
: c('Info').t`This conversation contains trashed messages.`}
</span>
</div>
<InlineLinkButton onClick={onToggle} className="ml0-5">
{inTrash
? filter
? c('Action').t`Show messages`
: c('Action').t`Hide messages`
: filter
? c('Action').t`Show messages`
: c('Action').t`Hide messages`}
</InlineLinkButton>
</div>
);
};
export default TrashWarning;
| import React from 'react';
import { c } from 'ttag';
import { InlineLinkButton, Icon } from 'react-components';
interface Props {
inTrash: boolean;
filter: boolean;
onToggle: () => void;
}
const TrashWarning = ({ inTrash, filter, onToggle }: Props) => {
return (
<div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-highlight">
<div className="flex flex-nowrap flex-items-center">
<Icon name="trash" className="mr1" />
<span>
{inTrash
? c('Info').t`This conversation contains non-trashed messages.`
: c('Info').t`This conversation contains trashed messages.`}
</span>
</div>
<InlineLinkButton onClick={onToggle} className="ml0-5 underline">
{inTrash
? filter
? c('Action').t`Show messages`
: c('Action').t`Hide messages`
: filter
? c('Action').t`Show messages`
: c('Action').t`Hide messages`}
</InlineLinkButton>
</div>
);
};
export default TrashWarning;
| Fix [MAILWEB-950] show trashed message not themed | Fix [MAILWEB-950] show trashed message not themed
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -10,7 +10,7 @@
const TrashWarning = ({ inTrash, filter, onToggle }: Props) => {
return (
- <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-light">
+ <div className="bordered-container m0-5 mb1 p1 flex flex-nowrap flex-items-center flex-spacebetween bg-global-highlight">
<div className="flex flex-nowrap flex-items-center">
<Icon name="trash" className="mr1" />
<span>
@@ -19,7 +19,7 @@
: c('Info').t`This conversation contains trashed messages.`}
</span>
</div>
- <InlineLinkButton onClick={onToggle} className="ml0-5">
+ <InlineLinkButton onClick={onToggle} className="ml0-5 underline">
{inTrash
? filter
? c('Action').t`Show messages` |
72657c2b94e4a02d4270546506070bacdb8b7bcc | index.ts | index.ts | import { NgModule, ModuleWithProviders, Optional, SkipSelf } from '@angular/core';
import { JwtInterceptor } from './src/jwt.interceptor';
import { JwtHelperService } from './src/jwthelper.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JWT_OPTIONS } from './src/jwtoptions.token';
export * from './src/jwt.interceptor';
export * from './src/jwthelper.service';
export * from './src/jwtoptions.token';
export interface JwtModuleOptions {
config: {
tokenGetter: () => string;
headerName?: string;
authScheme?: string;
whitelistedDomains?: Array<string>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
}
}
@NgModule()
export class JwtModule {
constructor(@Optional() @SkipSelf() parentModule: JwtModule) {
if (parentModule) {
throw new Error('JwtModule is already loaded. It should only be imported in your application\'s main module.');
}
}
static forRoot(options: JwtModuleOptions): ModuleWithProviders {
return {
ngModule: JwtModule,
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
{
provide: JWT_OPTIONS,
useValue: options.config
},
JwtHelperService
]
};
}
}
| import { NgModule, ModuleWithProviders, Optional, SkipSelf } from '@angular/core';
import { JwtInterceptor } from './src/jwt.interceptor';
import { JwtHelperService } from './src/jwthelper.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JWT_OPTIONS } from './src/jwtoptions.token';
export * from './src/jwt.interceptor';
export * from './src/jwthelper.service';
export * from './src/jwtoptions.token';
export interface JwtModuleOptions {
config: {
tokenGetter: () => string;
headerName?: string;
authScheme?: string;
whitelistedDomains?: Array<string | RegExp>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
}
}
@NgModule()
export class JwtModule {
constructor(@Optional() @SkipSelf() parentModule: JwtModule) {
if (parentModule) {
throw new Error('JwtModule is already loaded. It should only be imported in your application\'s main module.');
}
}
static forRoot(options: JwtModuleOptions): ModuleWithProviders {
return {
ngModule: JwtModule,
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
{
provide: JWT_OPTIONS,
useValue: options.config
},
JwtHelperService
]
};
}
}
| Allow RegExp whitelist entries in JwtModuleOptions | Allow RegExp whitelist entries in JwtModuleOptions | TypeScript | mit | auth0/angular2-jwt,hoalex/angular2-jwt,auth0/angular2-jwt,auth0/angular2-jwt,hoalex/angular2-jwt | ---
+++
@@ -13,7 +13,7 @@
tokenGetter: () => string;
headerName?: string;
authScheme?: string;
- whitelistedDomains?: Array<string>;
+ whitelistedDomains?: Array<string | RegExp>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
} |
410e111071d48bb5c1b0d7c81d65b7c9e139feea | stories/index.tsx | stories/index.tsx | import * as React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import InputAutocomplete from '../src/InputAutocomplete'
const onChange = (ev: React.FormEvent<HTMLInputElement>) => {
return action('input onChange')(ev.currentTarget.value)
}
const autocompleteValues = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content',
]
storiesOf('AutocompleteInput', module)
.addDecorator(story => (
<div>
<p>Try writing utm_source, utm_medium, utm_campaign, utm_term or utm_content</p>
{story()}
</div>
))
.add('Uncontrolled input', () => (
<InputAutocomplete
onChange={onChange}
autocompleteValues={autocompleteValues}
type='text'
/>
))
.add('Controlled input', () => {
let state = ''
const handleOnChange = (ev: React.FormEvent<HTMLInputElement>) => {
onChange(ev)
state = ev.currentTarget.value
}
return <InputAutocomplete
onChange={handleOnChange}
value={state}
autocompleteValues={autocompleteValues}
type='text'
/>
})
| import * as React from 'react'
import { storiesOf, action } from '@kadira/storybook'
import InputAutocomplete from '../src/InputAutocomplete'
const onChange = (ev: React.FormEvent<HTMLInputElement>) => {
return action('input onChange')(ev.currentTarget.value)
}
const autocompleteValues = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_content',
]
storiesOf('AutocompleteInput', module)
.addDecorator(story => (
<div>
<p>Try writing utm_source, utm_medium, utm_campaign, utm_term or utm_content</p>
{story()}
</div>
))
.add('Uncontrolled input', () => (
<InputAutocomplete
onChange={onChange}
autocompleteValues={autocompleteValues}
type='text'
/>
))
.add('Controlled input', () => {
const state = {
value: ''
}
const handleOnChange = (ev: React.FormEvent<HTMLInputElement>) => {
onChange(ev)
state.value = ev.currentTarget.value
}
return <InputAutocomplete
onChange={handleOnChange}
value={state.value}
autocompleteValues={autocompleteValues}
type='text'
/>
})
| Make storybook test case more correct | Make storybook test case more correct
IRL a component state would not be a single string but an object
| TypeScript | mit | kevinjhanna/input-autocomplete,kevinjhanna/input-autocomplete | ---
+++
@@ -29,15 +29,18 @@
/>
))
.add('Controlled input', () => {
- let state = ''
+ const state = {
+ value: ''
+ }
+
const handleOnChange = (ev: React.FormEvent<HTMLInputElement>) => {
onChange(ev)
- state = ev.currentTarget.value
+ state.value = ev.currentTarget.value
}
return <InputAutocomplete
onChange={handleOnChange}
- value={state}
+ value={state.value}
autocompleteValues={autocompleteValues}
type='text'
/> |
d3e6ec9aea81a3a17ab83f0f96afb5ba062d6ce8 | src/vue-plugin/vue-plugin.ts | src/vue-plugin/vue-plugin.ts | /*
eslint
@typescript-eslint/explicit-function-return-type: 0,
@typescript-eslint/no-explicit-any: 0
*/
import FeathersVuexFind from '../FeathersVuexFind'
import FeathersVuexGet from '../FeathersVuexGet'
import FeathersVuexFormWrapper from '../FeathersVuexFormWrapper'
import FeathersVuexPagination from '../FeathersVuexPagination'
import { globalModels } from '../service-module/global-models'
export const FeathersVuex = {
install(Vue, options = { components: true }) {
const shouldSetupComponents = options.components !== false
Vue.$FeathersVuex = globalModels
Vue.prototype.$FeathersVuex = globalModels
if (shouldSetupComponents) {
Vue.component('FeathersVuexFind', FeathersVuexFind)
Vue.component('FeathersVuexGet', FeathersVuexGet)
Vue.component('FeathersVuexFormWrapper', FeathersVuexFormWrapper)
Vue.component('FeathersVuexPagination', FeathersVuexPagination)
}
}
}
| /*
eslint
@typescript-eslint/explicit-function-return-type: 0,
@typescript-eslint/no-explicit-any: 0
*/
import FeathersVuexFind from '../FeathersVuexFind'
import FeathersVuexGet from '../FeathersVuexGet'
import FeathersVuexFormWrapper from '../FeathersVuexFormWrapper'
import FeathersVuexInputWrapper from '../FeathersVuexInputWrapper'
import FeathersVuexPagination from '../FeathersVuexPagination'
import { globalModels } from '../service-module/global-models'
export const FeathersVuex = {
install(Vue, options = { components: true }) {
const shouldSetupComponents = options.components !== false
Vue.$FeathersVuex = globalModels
Vue.prototype.$FeathersVuex = globalModels
if (shouldSetupComponents) {
Vue.component('FeathersVuexFind', FeathersVuexFind)
Vue.component('FeathersVuexGet', FeathersVuexGet)
Vue.component('FeathersVuexFormWrapper', FeathersVuexFormWrapper)
Vue.component('FeathersVuexInputWrapper', FeathersVuexInputWrapper)
Vue.component('FeathersVuexPagination', FeathersVuexPagination)
}
}
}
| Add FeathersVuexInputWrapper to the VuePlugin | fix: Add FeathersVuexInputWrapper to the VuePlugin
The Form Wrapper was getting registered, properly, but the Input Wrapper was missing.
| TypeScript | mit | feathers-plus/feathers-vuex,feathers-plus/feathers-vuex | ---
+++
@@ -6,6 +6,7 @@
import FeathersVuexFind from '../FeathersVuexFind'
import FeathersVuexGet from '../FeathersVuexGet'
import FeathersVuexFormWrapper from '../FeathersVuexFormWrapper'
+import FeathersVuexInputWrapper from '../FeathersVuexInputWrapper'
import FeathersVuexPagination from '../FeathersVuexPagination'
import { globalModels } from '../service-module/global-models'
@@ -20,6 +21,7 @@
Vue.component('FeathersVuexFind', FeathersVuexFind)
Vue.component('FeathersVuexGet', FeathersVuexGet)
Vue.component('FeathersVuexFormWrapper', FeathersVuexFormWrapper)
+ Vue.component('FeathersVuexInputWrapper', FeathersVuexInputWrapper)
Vue.component('FeathersVuexPagination', FeathersVuexPagination)
}
} |
cdcf4cece0068387269904b0f69af96b5ac43f9f | src/Harvester.ts | src/Harvester.ts | import * as Hmngr from "./HarvesterManager";
export function run(creep: Creep, src: string): void {
if (creep.carry.energy! < creep.carryCapacity) {
let source = <Source>Game.getObjectById(src);
if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
creep.moveTo(source);
}
} else {
// TODO: consumer should be passed into run() instead.
let consumer = Hmngr.HarvesterManager.getMyConsumer(creep);
if (consumer == null) {
return;
}
if (creep.transfer(consumer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(consumer);
}
}
}
| import * as Hmngr from "./HarvesterManager";
export function run(creep: Creep, src: string): void {
if (creep.memory.harvesting && creep.carry.energy == creep.carryCapacity) {
creep.memory.harvesting = false;
} else if (!creep.memory.harvesting && creep.carry.energy == 0) {
creep.memory.harvesting = true;
}
if (creep.memory.harvesting) {
let source = <Source>Game.getObjectById(src);
if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
creep.moveTo(source);
}
} else {
// TODO: consumer should be passed into run() instead.
let consumer = Hmngr.HarvesterManager.getMyConsumer(creep);
if (consumer == null) {
return;
}
if (creep.transfer(consumer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(consumer);
}
}
}
| Make harvesters a little less stupid | Make harvesters a little less stupid
| TypeScript | unlicense | lennytmp/screeps,lennytmp/screeps | ---
+++
@@ -1,7 +1,12 @@
import * as Hmngr from "./HarvesterManager";
export function run(creep: Creep, src: string): void {
- if (creep.carry.energy! < creep.carryCapacity) {
+ if (creep.memory.harvesting && creep.carry.energy == creep.carryCapacity) {
+ creep.memory.harvesting = false;
+ } else if (!creep.memory.harvesting && creep.carry.energy == 0) {
+ creep.memory.harvesting = true;
+ }
+ if (creep.memory.harvesting) {
let source = <Source>Game.getObjectById(src);
if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
creep.moveTo(source); |
dcf05bafe7086bffe64aa7aa8d1a8dc2e50b413e | ee_tests/src/specs/login.spec.ts | ee_tests/src/specs/login.spec.ts | import { browser, ExpectedConditions as EC, $, $$ } from 'protractor';
import * as support from './support';
import { HomePage } from './page_objects/home.page';
import { LoginPage } from './page_objects/login.page';
// declare let expect:any
describe('HomePage', () => {
let homePage: HomePage;
beforeEach( async () => {
support.desktopTestSetup();
homePage = new HomePage(browser.params.target.url);
await homePage.open();
});
it('shows the title', async () => {
await expect(browser.getTitle()).toEqual('OpenShift.io');
});
it('show login button', async () => {
await expect($$('div').first()).toAppear('Atleast one div should appear on the page');
await expect( homePage.login).toAppear('Login must be present');
});
it('can login using correct username and password', async () => {
await homePage.login.click();
let loginPage = new LoginPage();
await loginPage.login(browser.params.login.user, browser.params.login.password);
});
});
| import { browser, ExpectedConditions as EC, $, $$ } from 'protractor';
import * as support from './support';
import { HomePage } from './page_objects/home.page';
import { LoginPage } from './page_objects/login.page';
// declare let expect:any
describe('HomePage', () => {
let homePage: HomePage;
beforeEach( async () => {
support.desktopTestSetup();
homePage = new HomePage(browser.params.target.url);
await homePage.open();
});
it('shows the title', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
});
it('show login button', async () => {
await expect($$('div').first()).toAppear('Atleast one div should appear on the page');
await expect( homePage.login).toAppear('Login must be present');
});
it('can login using correct username and password', async () => {
await homePage.login.click();
let loginPage = new LoginPage();
await loginPage.login(browser.params.login.user, browser.params.login.password);
});
});
| Fix await for browser.getTitle() pointed by typescript | Fix await for browser.getTitle() pointed by typescript
| TypeScript | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | ---
+++
@@ -16,7 +16,7 @@
});
it('shows the title', async () => {
- await expect(browser.getTitle()).toEqual('OpenShift.io');
+ await expect(await browser.getTitle()).toEqual('OpenShift.io');
});
it('show login button', async () => { |
f2ae27e831f611a798c3fb696c4d06b35bb3bb19 | modules/food-menu/lib/choose-meal.ts | modules/food-menu/lib/choose-meal.ts | import type {Moment} from 'moment'
import type {ProcessedMealType} from '../types'
import type {FilterType} from '@frogpond/filter'
import {findMeal} from './find-menu'
export function chooseMeal(
meals: ProcessedMealType[],
filters: FilterType[],
now: Moment,
): ProcessedMealType {
const mealChooserFilter: FilterType | undefined = filters.find(
(f) => f.type === 'picker' && f.spec.title === "Today's Menus",
)
let selectedMeal = meals[0]
if (
mealChooserFilter &&
mealChooserFilter.spec.selected &&
mealChooserFilter.spec.selected.label
) {
const label = mealChooserFilter.spec.selected.label
selectedMeal = meals.find((meal) => meal.label === label)
} else {
selectedMeal = findMeal(meals, now)
}
if (!selectedMeal) {
selectedMeal = {
label: '',
stations: [],
starttime: '0:00',
endtime: '0:00',
}
}
return selectedMeal
}
| import type {Moment} from 'moment'
import type {ProcessedMealType} from '../types'
import type {FilterType, PickerType} from '@frogpond/filter'
import {findMeal} from './find-menu'
export function chooseMeal(
meals: ProcessedMealType[],
filters: FilterType[],
now: Moment,
): ProcessedMealType {
let mealChooserFilter: FilterType | undefined = filters.find(
(f) => f.type === 'picker' && f.spec.title === "Today's Menus",
) as PickerType | undefined
let selectedMeal: ProcessedMealType | undefined = meals[0]
if (
mealChooserFilter &&
mealChooserFilter.spec.selected &&
mealChooserFilter.spec.selected.label
) {
const label = mealChooserFilter.spec.selected.label
selectedMeal = meals.find((meal) => meal.label === label)
} else {
selectedMeal = findMeal(meals, now)
}
if (!selectedMeal) {
selectedMeal = {
label: '',
stations: [],
starttime: '0:00',
endtime: '0:00',
}
}
return selectedMeal
}
| Add some type annotations to help TypeScript figure it out | m/food-menu: Add some type annotations to help TypeScript figure it out
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
| TypeScript | agpl-3.0 | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | ---
+++
@@ -1,6 +1,6 @@
import type {Moment} from 'moment'
import type {ProcessedMealType} from '../types'
-import type {FilterType} from '@frogpond/filter'
+import type {FilterType, PickerType} from '@frogpond/filter'
import {findMeal} from './find-menu'
export function chooseMeal(
@@ -8,11 +8,11 @@
filters: FilterType[],
now: Moment,
): ProcessedMealType {
- const mealChooserFilter: FilterType | undefined = filters.find(
+ let mealChooserFilter: FilterType | undefined = filters.find(
(f) => f.type === 'picker' && f.spec.title === "Today's Menus",
- )
+ ) as PickerType | undefined
- let selectedMeal = meals[0]
+ let selectedMeal: ProcessedMealType | undefined = meals[0]
if (
mealChooserFilter &&
mealChooserFilter.spec.selected && |
52f54b2747565dcb45c8126e513e676b7d2a5133 | generators/component/templates/_component.spec.ts | generators/component/templates/_component.spec.ts | /* beautify ignore:start */
import {
it,
inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import {<%=componentnameClass%>Component} from './<%=componentnameFile%>.component.ts';
/* beautify ignore:end */
describe('Component: <%=componentnameClass%>Component', () => {
let builder;
beforeEachProviders(() => []);
beforeEach(inject([TestComponentBuilder], (tcb) => {
builder = tcb;
}));
it('should be defined', (done) => {
return builder
.createAsync(<%=componentnameClass%>Component)
.then((fixture) => {
fixture.detectChanges();
let cmpInstance = fixture.debugElement.componentInstance;
let element = fixture.debugElement.nativeElement;
expect(cmpInstance).toBeDefined();
expect(element).toBeDefined();
done();
});
});
}); | /* beautify ignore:start */
import {
it,
//inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
import {<%=componentnameClass%>Component} from './<%=componentnameFile%>.component.ts';
/* beautify ignore:end */
describe('Component: <%=componentnameClass%>Component', () => {
let builder;
beforeEachProviders(() => []);
it('should be defined', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(<%=componentnameClass%>Component)
.then((fixture) => {
fixture.detectChanges();
let element = fixture.debugElement.nativeElement;
let cmpInstance = fixture.debugElement.componentInstance;
expect(cmpInstance).toBeDefined();
expect(element).toBeDefined();
});
}));
}); | Revert unit test for component | fix(component): Revert unit test for component
| TypeScript | mit | mcfly-io/generator-mcfly-ng2,mcfly-io/generator-mcfly-ng2,mcfly-io/generator-mcfly-ng2 | ---
+++
@@ -1,7 +1,7 @@
/* beautify ignore:start */
import {
it,
- inject,
+ //inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
@@ -13,21 +13,15 @@
let builder;
beforeEachProviders(() => []);
- beforeEach(inject([TestComponentBuilder], (tcb) => {
- builder = tcb;
+ it('should be defined', injectAsync([TestComponentBuilder], (tcb) => {
+ return tcb.createAsync(<%=componentnameClass%>Component)
+ .then((fixture) => {
+ fixture.detectChanges();
+ let element = fixture.debugElement.nativeElement;
+ let cmpInstance = fixture.debugElement.componentInstance;
+ expect(cmpInstance).toBeDefined();
+ expect(element).toBeDefined();
+ });
}));
- it('should be defined', (done) => {
- return builder
- .createAsync(<%=componentnameClass%>Component)
- .then((fixture) => {
- fixture.detectChanges();
- let cmpInstance = fixture.debugElement.componentInstance;
- let element = fixture.debugElement.nativeElement;
- expect(cmpInstance).toBeDefined();
- expect(element).toBeDefined();
- done();
- });
- });
-
}); |
b319125165f07861c71835a26e85981798c119e3 | src/ui/RendererUI.ts | src/ui/RendererUI.ts | /// <reference path="../../typings/threejs/three.d.ts" />
import * as THREE from "three";
export class RendererUI {
private renderer: THREE.WebGLRenderer;
private camera: THREE.PerspectiveCamera;
private scene: THREE.Scene;
constructor (container: HTMLElement) {
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(640, 480);
this.renderer.setClearColor(new THREE.Color(0x202020), 1.0);
this.renderer.sortObjects = false;
this.renderer.domElement.style.width = "100%";
this.renderer.domElement.style.height = "100%";
container.appendChild(this.renderer.domElement);
this.camera = new THREE.PerspectiveCamera(50, 4 / 3, 0.4, 1100);
this.scene = new THREE.Scene();
this.renderer.render(this.scene, this.camera);
window.requestAnimationFrame(this.animate.bind(this));
}
private animate(): void {
window.requestAnimationFrame(this.animate.bind(this));
this.renderer.render(this.scene, this.camera);
}
}
export default RendererUI;
| /// <reference path="../../typings/threejs/three.d.ts" />
import * as THREE from "three";
import {Node} from "../Graph";
import {IActivatableUI} from "../UI";
export class RendererUI implements IActivatableUI {
public graphSupport: boolean = true;
private renderer: THREE.WebGLRenderer;
private camera: THREE.PerspectiveCamera;
private scene: THREE.Scene;
constructor (container: HTMLElement) {
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(640, 480);
this.renderer.setClearColor(new THREE.Color(0x202020), 1.0);
this.renderer.sortObjects = false;
this.renderer.domElement.style.width = "100%";
this.renderer.domElement.style.height = "100%";
container.appendChild(this.renderer.domElement);
this.camera = new THREE.PerspectiveCamera(50, 4 / 3, 0.4, 1100);
this.scene = new THREE.Scene();
this.renderer.render(this.scene, this.camera);
window.requestAnimationFrame(this.animate.bind(this));
}
public activate(): void {
return;
}
public deactivate(): void {
return;
}
public display(node: Node): void {
return;
}
private animate(): void {
window.requestAnimationFrame(this.animate.bind(this));
this.renderer.render(this.scene, this.camera);
}
}
export default RendererUI;
| Implement activatable interface in renderer. | Implement activatable interface in renderer.
| TypeScript | mit | mapillary/mapillary-js,mapillary/mapillary-js | ---
+++
@@ -1,8 +1,12 @@
/// <reference path="../../typings/threejs/three.d.ts" />
import * as THREE from "three";
+import {Node} from "../Graph";
+import {IActivatableUI} from "../UI";
-export class RendererUI {
+export class RendererUI implements IActivatableUI {
+ public graphSupport: boolean = true;
+
private renderer: THREE.WebGLRenderer;
private camera: THREE.PerspectiveCamera;
private scene: THREE.Scene;
@@ -25,6 +29,18 @@
window.requestAnimationFrame(this.animate.bind(this));
}
+ public activate(): void {
+ return;
+ }
+
+ public deactivate(): void {
+ return;
+ }
+
+ public display(node: Node): void {
+ return;
+ }
+
private animate(): void {
window.requestAnimationFrame(this.animate.bind(this));
|
bd89862edeeebaa97adf1a0d85f16a4bdd0f916b | src/ILogger.ts | src/ILogger.ts | import { IBuildLogMessage } from './IBuildLogMessage';
export interface ILogger {
Error(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
Warn(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
Debug(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
Information(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
Trace(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
}
| import { IBuildLogMessage } from './IBuildLogMessage';
export interface ILogger {
error(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
warn(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
debug(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
information(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
trace(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
}
| Change interface to lowercase methods | Change interface to lowercase methods
| TypeScript | mit | Supercide/loxium,Supercide/loxium | ---
+++
@@ -1,9 +1,9 @@
import { IBuildLogMessage } from './IBuildLogMessage';
export interface ILogger {
- Error(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
- Warn(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
- Debug(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
- Information(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
- Trace(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
+ error(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
+ warn(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
+ debug(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
+ information(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
+ trace(logMessageBuilder: (b: IBuildLogMessage) => void, method?: string): void;
} |
96a244a317040bde13786e694b8cf8e174d55011 | src/app/core/filter.service.ts | src/app/core/filter.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class FilterService {
search(array: any[], query: string) {
let lQuery = query.toLowerCase();
if (!query) {
return array;
} else if (array) {
let filteredArray = array.filter(item => {
for (let key in item) {
let value = item[key];
if ((typeof value === 'string') && (value.toLowerCase().indexOf(lQuery) !== -1)) {
return true;
}
}
});
return filteredArray;
}
}
}
| import { Injectable } from '@angular/core';
@Injectable()
export class FilterService {
search(array: any[], query: string) {
let lQuery = query.toLowerCase();
if (!query) {
return array;
} else if (array) {
let filteredArray = array.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string') && (item[key].toLowerCase().indexOf(lQuery) !== -1)) {
return true;
}
}
});
return filteredArray;
}
}
}
| Remove let in for in | Remove let in for in
| TypeScript | mit | auth0-blog/ng2-dinos,kmaida/ng2-dinos,kmaida/ng2-dinos,kmaida/ng2-dinos,auth0-blog/ng2-dinos,auth0-blog/ng2-dinos | ---
+++
@@ -10,9 +10,7 @@
} else if (array) {
let filteredArray = array.filter(item => {
for (let key in item) {
- let value = item[key];
-
- if ((typeof value === 'string') && (value.toLowerCase().indexOf(lQuery) !== -1)) {
+ if ((typeof item[key] === 'string') && (item[key].toLowerCase().indexOf(lQuery) !== -1)) {
return true;
}
} |
0633e8ff5447d0718ed6a7b6866c3fbd7241540b | examples/sparklineDemo.ts | examples/sparklineDemo.ts | ///<reference path="../lib/d3.d.ts" />
///<reference path="../src/table.ts" />
///<reference path="../src/renderer.ts" />
///<reference path="../src/interaction.ts" />
///<reference path="../src/labelComponent.ts" />
///<reference path="../src/axis.ts" />
///<reference path="exampleUtil.ts" />
if ((<any> window).demoName === "sparkline-demo") {
var yScale = new LinearScale();
var xScale = new LinearScale();
var left = new YAxis(yScale, "left");
var data = makeRandomData(1000, 200);
var renderer = new CircleRenderer(data, xScale, yScale);
var bottomAxis = new XAxis(xScale, "bottom");
var ySpark = new LinearScale();
var sparkline = new LineRenderer(data, xScale, ySpark);
sparkline.rowWeight(0.3);
var r1: Component[] = [left, renderer];
var r2: Component[] = [null, bottomAxis];
var r3: Component[] = [null, sparkline];
var chart = new Table([r1, r2, r3]);
chart.xMargin = 10;
chart.yMargin = 10;
var svg = d3.select("#table");
chart.anchor(svg);
chart.computeLayout();
chart.render();
}
| ///<reference path="../lib/d3.d.ts" />
///<reference path="../src/table.ts" />
///<reference path="../src/renderer.ts" />
///<reference path="../src/interaction.ts" />
///<reference path="../src/labelComponent.ts" />
///<reference path="../src/axis.ts" />
///<reference path="exampleUtil.ts" />
if ((<any> window).demoName === "sparkline-demo") {
var yScale = new LinearScale();
var xScale = new LinearScale();
var left = new YAxis(yScale, "left");
var data = makeRandomData(1000, 200);
var renderer = new CircleRenderer(data, xScale, yScale);
var bottomAxis = new XAxis(xScale, "bottom");
var ySpark = new LinearScale();
var sparkline = new LineRenderer(data, xScale, ySpark);
sparkline.rowWeight(0.3);
var r1: Component[] = [left, renderer];
var r2: Component[] = [null, bottomAxis];
var r3: Component[] = [null, sparkline];
var chart = new Table([r1, r2, r3]);
chart.xMargin = 10;
chart.yMargin = 10;
var brushZoom = new BrushZoomInteraction(sparkline, xScale, ySpark);
var zoomCoordinator = new ScaleDomainCoordinator([yScale, ySpark]);
var svg = d3.select("#table");
chart.anchor(svg);
chart.computeLayout();
chart.render();
}
| Add coordinators to the sparkline demo | Add coordinators to the sparkline demo
| TypeScript | mit | gdseller/plottable,NextTuesday/plottable,RobertoMalatesta/plottable,danmane/plottable,palantir/plottable,jacqt/plottable,iobeam/plottable,alyssaq/plottable,palantir/plottable,palantir/plottable,palantir/plottable,NextTuesday/plottable,jacqt/plottable,iobeam/plottable,iobeam/plottable,gdseller/plottable,softwords/plottable,onaio/plottable,softwords/plottable,alyssaq/plottable,gdseller/plottable,danmane/plottable,jacqt/plottable,alyssaq/plottable,onaio/plottable,RobertoMalatesta/plottable,danmane/plottable,NextTuesday/plottable,onaio/plottable,softwords/plottable,RobertoMalatesta/plottable | ---
+++
@@ -26,6 +26,11 @@
var chart = new Table([r1, r2, r3]);
chart.xMargin = 10;
chart.yMargin = 10;
+
+var brushZoom = new BrushZoomInteraction(sparkline, xScale, ySpark);
+var zoomCoordinator = new ScaleDomainCoordinator([yScale, ySpark]);
+
+
var svg = d3.select("#table");
chart.anchor(svg);
chart.computeLayout(); |
be6c8ec0465ab26bc616f2ae11134310dacefb90 | src/Parsing/Inline/Token.ts | src/Parsing/Inline/Token.ts | import { TextConsumer } from '../TextConsumer'
export enum TokenMeaning {
PlainText,
EmphasisStart,
EmphasisEnd,
StressStart,
StressEnd,
InlineCode,
RevisionDeletionStart,
RevisionDeletionEnd,
RevisionInserionStart,
RevisionInsertionEnd,
SpoilerStart,
SpoilerEnd,
InlineAsideStart,
InlineAsideEnd,
LinkStart,
LinkUrlAndLinkEnd,
EmphasisStartAndStressStart,
EmphasisEndAndStressEnd
}
export class Token {
public value: string
public consumerBefore: TextConsumer
constructor(public meaning: TokenMeaning, valueOrConsumerBefore?: string|TextConsumer) {
if (typeof valueOrConsumerBefore === 'string') {
this.value = valueOrConsumerBefore
} else {
this.consumerBefore = valueOrConsumerBefore
}
}
textIndex(): number {
return this.consumerBefore.lengthConsumed()
}
} | import { TextConsumer } from '../TextConsumer'
export enum TokenMeaning {
PlainText,
EmphasisStart,
EmphasisEnd,
StressStart,
StressEnd,
InlineCode,
RevisionDeletionStart,
RevisionDeletionEnd,
RevisionInserionStart,
RevisionInsertionEnd,
SpoilerStart,
SpoilerEnd,
InlineAsideStart,
InlineAsideEnd,
LinkStart,
LinkUrlAndLinkEnd
}
export class Token {
public value: string
public consumerBefore: TextConsumer
constructor(public meaning: TokenMeaning, valueOrConsumerBefore?: string|TextConsumer) {
if (typeof valueOrConsumerBefore === 'string') {
this.value = valueOrConsumerBefore
} else {
this.consumerBefore = valueOrConsumerBefore
}
}
textIndex(): number {
return this.consumerBefore.lengthConsumed()
}
} | Remove special token meanings for stress+emphasis | Remove special token meanings for stress+emphasis
| TypeScript | mit | start/up,start/up | ---
+++
@@ -16,9 +16,7 @@
InlineAsideStart,
InlineAsideEnd,
LinkStart,
- LinkUrlAndLinkEnd,
- EmphasisStartAndStressStart,
- EmphasisEndAndStressEnd
+ LinkUrlAndLinkEnd
}
export class Token { |
0318818d4f5697d5906ce146631f35ef4cf805c3 | demo/src/app/components/home.component.ts | demo/src/app/components/home.component.ts | import {Component} from '@angular/core';
import {IOption} from 'ng-select';
import {OptionService} from '../services/option.service';
@Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class Home {
version: string = '1.0.0-rc.1';
countries: Array<IOption> = this.optionService.getCountries();
singleSelectValue: string = 'NL';
multiSelectValue: Array<string> = ['BE', 'LU', 'NL'];
constructor(
private optionService: OptionService
) {}
}
| import {Component} from '@angular/core';
import {IOption} from 'ng-select';
import {OptionService} from '../services/option.service';
@Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class Home {
version: string = '1.0.0-rc.2';
countries: Array<IOption> = this.optionService.getCountries();
singleSelectValue: string = 'NL';
multiSelectValue: Array<string> = ['BE', 'LU', 'NL'];
constructor(
private optionService: OptionService
) {}
}
| Update version on demo site home page. | Update version on demo site home page.
| TypeScript | isc | basvandenberg/ng-select,basvandenberg/angular2-select,basvandenberg/ng-select,basvandenberg/angular2-select,benelliott/angular2-select,basvandenberg/angular2-select,benelliott/angular2-select,benelliott/angular2-select,basvandenberg/ng-select,basvandenberg/ng-select,benelliott/angular2-select | ---
+++
@@ -8,7 +8,7 @@
})
export class Home {
- version: string = '1.0.0-rc.1';
+ version: string = '1.0.0-rc.2';
countries: Array<IOption> = this.optionService.getCountries();
singleSelectValue: string = 'NL'; |
1ea52564139ce2652c8fca6ba21899d826f336a5 | server/src/models/base.model.ts | server/src/models/base.model.ts | import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
Generated,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity()
export class BaseModel extends BaseEntity {
public static async deleteAll(): Promise<void> {
await this.createQueryBuilder()
.delete()
.from(this)
.execute();
}
@PrimaryGeneratedColumn()
public id!: number;
@Column()
@Generated('uuid')
public uuid!: string;
@CreateDateColumn()
public createdOn!: Date;
@UpdateDateColumn()
public updatedOn!: Date;
}
| import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
Generated,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity()
export class BaseModel extends BaseEntity {
public static async deleteAll(): Promise<void> {
await this.createQueryBuilder()
.delete()
.from(this)
.execute();
}
@PrimaryGeneratedColumn()
public id!: number;
@Column()
@Generated('uuid')
public uuid!: string;
@CreateDateColumn({
select: false,
})
public createdOn!: Date;
@UpdateDateColumn({
select: false,
})
public updatedOn!: Date;
}
| Hide createdOn/updatedOn columns by default | Hide createdOn/updatedOn columns by default
| TypeScript | mit | Ionaru/EVE-Track,Ionaru/EVE-Track,Ionaru/EVE-Track | ---
+++
@@ -25,9 +25,13 @@
@Generated('uuid')
public uuid!: string;
- @CreateDateColumn()
+ @CreateDateColumn({
+ select: false,
+ })
public createdOn!: Date;
- @UpdateDateColumn()
+ @UpdateDateColumn({
+ select: false,
+ })
public updatedOn!: Date;
} |
ae30ebc0bb8863c5788135c3407295462c783df6 | ts/dashboard/properties.ts | ts/dashboard/properties.ts | /*
* Register a bunch of editable properties that are used by many
* dashboard items.
*/
ts.properties.register([
{
name: 'query',
category: 'base',
template: '{{item.query.name}}',
edit_options: {
type: 'select',
source: function() {
var queries = ds.manager.current.dashboard.definition.queries
return Object.keys(queries).map(function(k) {
return { value: k, text: k }
})
},
value: function(item) {
return item.query ? item.query.name : undefined
}
}
},
{
name: 'style',
type: 'select',
edit_options: {
source: [
undefined,
'well',
'callout_neutral',
'callout_info',
'callout_success',
'callout_warning',
'callout_danger',
'alert_neutral',
'alert_info',
'alert_success',
'alert_warning',
'alert_danger'
]
}
},
{
name: 'transform',
type: 'select',
edit_options: {
source: [
undefined,
'sum',
'min',
'max',
'mean',
'median',
'first',
'last',
'last_non_zero',
'count'
]
}
}
])
| /*
* Register a bunch of editable properties that are used by many
* dashboard items.
*/
ts.properties.register([
{
name: 'query',
category: 'base',
template: '{{item.query.name}}',
edit_options: {
type: 'select',
source: function() {
var queries = ds.manager.current.dashboard.definition.queries
return Object.keys(queries).map(function(k) {
return { value: k, text: k }
})
},
value: function(item) {
return item.query ? item.query.name : undefined
},
update: function(item, value) {
item.set_query(value)
}
}
},
{
name: 'style',
type: 'select',
edit_options: {
source: [
undefined,
'well',
'callout_neutral',
'callout_info',
'callout_success',
'callout_warning',
'callout_danger',
'alert_neutral',
'alert_info',
'alert_success',
'alert_warning',
'alert_danger'
]
}
},
{
name: 'transform',
type: 'select',
edit_options: {
source: [
undefined,
'sum',
'min',
'max',
'mean',
'median',
'first',
'last',
'last_non_zero',
'count'
]
}
}
])
| Fix setting queries in the editor | Fix setting queries in the editor
| TypeScript | apache-2.0 | jmptrader/tessera,urbanairship/tessera,jmptrader/tessera,Slach/tessera,section-io/tessera,aalpern/tessera,tessera-metrics/tessera,aalpern/tessera,tessera-metrics/tessera,Slach/tessera,urbanairship/tessera,jmptrader/tessera,section-io/tessera,aalpern/tessera,urbanairship/tessera,jmptrader/tessera,aalpern/tessera,Slach/tessera,aalpern/tessera,Slach/tessera,section-io/tessera,jmptrader/tessera,tessera-metrics/tessera,tessera-metrics/tessera,section-io/tessera,urbanairship/tessera,tessera-metrics/tessera,urbanairship/tessera | ---
+++
@@ -18,6 +18,9 @@
},
value: function(item) {
return item.query ? item.query.name : undefined
+ },
+ update: function(item, value) {
+ item.set_query(value)
}
}
}, |
835b2f4dbd0828fd6f2383a15909a922fb570551 | app/app.module.ts | app/app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent, HeroDetailComponent, HeroesComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
| import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent, HeroDetailComponent, HeroesComponent],
bootstrap: [ AppComponent ],
providers: [ HeroService ]
})
export class AppModule { }
| Add the supporting import statements for AppComponent | Add the supporting import statements for AppComponent
| TypeScript | mit | amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes,amalshehu/angular-tour-of-heroes | ---
+++
@@ -1,12 +1,17 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'
+
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
+import { HeroesComponent } from './heroes.component';
+import { HeroService } from './hero.service';
+
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent, HeroDetailComponent, HeroesComponent],
- bootstrap: [ AppComponent ]
+ bootstrap: [ AppComponent ],
+ providers: [ HeroService ]
})
export class AppModule { } |
114e1bd93a84b5e2ee7ac91e7304f91860490fbd | .github/actions/issue_template_bot/index.ts | .github/actions/issue_template_bot/index.ts | import * as core from "@actions/core";
import * as github from "@actions/github";
async function run() {
console.log("START");
console.log(github.context);
if (github.context.eventName !== "issue") {
core.setFailed("Can only run on issues!");
return;
}
const payload = github.context.payload;
if (!payload) {
core.setFailed("No payload!");
return;
}
const issue = payload.issue;
if (!issue) {
core.setFailed("No issue on payload!");
return;
}
console.log(`Issue number: ${issue.number}`);
console.log(`Issue body: ${issue.body}`);
}
run().catch(error => core.setFailed(`Workflow failed with error message: ${error.message}`));
| import * as core from "@actions/core";
import * as github from "@actions/github";
async function run() {
core.info("START");
core.info(github.context.eventName);
if (github.context.eventName !== "issue") {
core.setFailed("Can only run on issues!");
return;
}
const payload = github.context.payload;
if (!payload) {
core.setFailed("No payload!");
return;
}
const issue = payload.issue;
if (!issue) {
core.setFailed("No issue on payload!");
return;
}
core.info(`Issue number: ${issue.number}`);
core.info(`Issue body: ${issue.body}`);
}
run().catch(error => core.setFailed(`Workflow failed with error message: ${error.message}`));
| Use core api for console logs | Use core api for console logs
| TypeScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -2,8 +2,8 @@
import * as github from "@actions/github";
async function run() {
- console.log("START");
- console.log(github.context);
+ core.info("START");
+ core.info(github.context.eventName);
if (github.context.eventName !== "issue") {
core.setFailed("Can only run on issues!");
return;
@@ -21,8 +21,8 @@
return;
}
- console.log(`Issue number: ${issue.number}`);
- console.log(`Issue body: ${issue.body}`);
+ core.info(`Issue number: ${issue.number}`);
+ core.info(`Issue body: ${issue.body}`);
}
run().catch(error => core.setFailed(`Workflow failed with error message: ${error.message}`)); |
2d7c1ebb4e3e69ae87fb73bded26c5a7a1ef1fb3 | src/examples/minimal-example.ts | src/examples/minimal-example.ts | /*
Simplest Rimu TypeScript application.
npm install rimu # Install Rimu module.
tsc --module commonjs minimal-example.ts # Compile example.
node minimal-example.js # Run example.
*/
// Use this in a nodejs application.
// Compiles using rimu.d.ts typings from rimu npm package.
import Rimu = require('rimu');
// Use this in a generic application.
// Compiles using rimu.d.ts typings located in current directory.
// import Rimu = require('./rimu');
console.log(Rimu.render('Hello *Rimu*!', {safeMode:1}));
| /*
Simplest Rimu TypeScript application.
npm install rimu # Install Rimu module.
tsc --module commonjs minimal-example.ts # Compile example.
node minimal-example.js # Run example.
*/
import * as rimu from 'rimu'
console.log(rimu.render('Hello *Rimu*!', {safeMode: 1}))
| Simplify minimal example and use import instead or require. | doc: Simplify minimal example and use import instead or require.
| TypeScript | mit | srackham/rimu | ---
+++
@@ -7,15 +7,7 @@
*/
-// Use this in a nodejs application.
-// Compiles using rimu.d.ts typings from rimu npm package.
+import * as rimu from 'rimu'
-import Rimu = require('rimu');
+console.log(rimu.render('Hello *Rimu*!', {safeMode: 1}))
-// Use this in a generic application.
-// Compiles using rimu.d.ts typings located in current directory.
-
-// import Rimu = require('./rimu');
-
-console.log(Rimu.render('Hello *Rimu*!', {safeMode:1}));
- |
61abb3fe0c758eb9b9f92630e4ae2f15d2ef01d2 | src/app/components/app-header.ts | src/app/components/app-header.ts | import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-header',
template: `
<nav class="navbar navbar-default">
<div class="container">
<a href="/orders" class="navbar-brand">Bibille Brigade</a>
<ul class="nav navbar-nav">
<li><a href="/meals">Lunch</a></li>
<li><a href="/orders">Orders</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li *ngIf="authenticated"><a (click)="signOut.emit()" href="#">Sign out</a></li>
</ul>
</div>
</nav>
`
})
export class AppHeaderComponent {
@Input() authenticated: boolean;
@Output() signOut = new EventEmitter(false);
}
| import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-header',
template: `
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="/orders" class="navbar-brand">Bibille Brigade</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="/meals">Lunch</a></li>
<li><a href="/orders">Orders</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li *ngIf="authenticated"><a (click)="signOut.emit()" href="#">Sign out</a></li>
</ul>
</div>
</div>
</nav>
`
})
export class AppHeaderComponent {
@Input() authenticated: boolean;
@Output() signOut = new EventEmitter(false);
}
| Make collasible navbar for mobile | Make collasible navbar for mobile
| TypeScript | mit | tchen10/bbrigade,tchen10/bbrigade,tchen10/bbrigade | ---
+++
@@ -5,8 +5,17 @@
selector: 'app-header',
template: `
<nav class="navbar navbar-default">
- <div class="container">
- <a href="/orders" class="navbar-brand">Bibille Brigade</a>
+ <div class="container-fluid">
+ <div class="navbar-header">
+ <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
+ <span class="sr-only">Toggle navigation</span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ </button>
+ <a href="/orders" class="navbar-brand">Bibille Brigade</a>
+ </div>
+ <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="/meals">Lunch</a></li>
<li><a href="/orders">Orders</a></li>
@@ -14,6 +23,7 @@
<ul class="nav navbar-nav navbar-right">
<li *ngIf="authenticated"><a (click)="signOut.emit()" href="#">Sign out</a></li>
</ul>
+ </div>
</div>
</nav>
` |
dd7cf273e254d665ae591582b6760102bf0a9358 | packages/swagger/src/interfaces/ISwaggerResponses.ts | packages/swagger/src/interfaces/ISwaggerResponses.ts | import {Type} from "@tsed/core";
import {Header} from "swagger-schema-official";
export interface ISwaggerResponses {
/**
* Use IResponseOptions.type instead of
* @deprecated
*/
use?: Type<any>;
type?: Type<any>;
collection?: Type<any>;
description?: string;
examples?: {[exampleName: string]: string};
headers?: {[headerName: string]: Header};
}
| import {Type} from "@tsed/core";
import {Header, Schema} from "swagger-schema-official";
export interface ISwaggerResponses {
/**
* Use IResponseOptions.type instead of
* @deprecated
*/
use?: Type<any>;
type?: Type<any>;
collection?: Type<any>;
description?: string;
examples?: {[exampleName: string]: string};
headers?: {[headerName: string]: Header};
schema?: Schema;
}
| Add schema on ISwaggerResponse interface | fix(swagger): Add schema on ISwaggerResponse interface
Closes: #739
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,5 +1,5 @@
import {Type} from "@tsed/core";
-import {Header} from "swagger-schema-official";
+import {Header, Schema} from "swagger-schema-official";
export interface ISwaggerResponses {
/**
@@ -12,4 +12,5 @@
description?: string;
examples?: {[exampleName: string]: string};
headers?: {[headerName: string]: Header};
+ schema?: Schema;
} |
5b738d79b62f8755a39ed088b1a3d4877ee6a0e0 | schedules_web/src/components/Header.tsx | schedules_web/src/components/Header.tsx | import * as React from 'react';
import { Col, Row } from 'reactstrap';
require('../css/iconbadge.css');
const Header = () => (
<div>
<Row className="justify-content-end my-5 px-3">
<span className="fa-stack fa-3x has-badge" data-count="0">
<i className="fa fas fa-shopping-bag fa-stack-1x" />
</span>
</Row>
<Row className="justify-content-center my-5">
<h1>
<i className="far fa-calendar-alt" /> Schedules
</h1>
<div className="w-100 mb-3" />
<Col md="6">
<p>
This is a catchy slogan that concisely describes the site with a lot of words that looks good on
mobile ahh.
</p>
</Col>
</Row>
</div>
);
export default Header;
| import * as React from 'react';
import { Col, Row } from 'reactstrap';
require('../css/iconbadge.css');
const Header = () => (
<div>
{/* TODO Extract into its own components with state management. */}
<Row className="justify-content-end my-5 px-3">
<span className="fa-stack fa-3x has-badge" data-count="0">
<i className="fa fas fa-shopping-bag fa-stack-1x" />
</span>
</Row>
<Row className="justify-content-center my-5">
<h1>
<i className="far fa-calendar-alt" /> Schedules
</h1>
<div className="w-100 mb-3" />
<Col md="6">
<p>
This is a catchy slogan that concisely describes the site with a lot of words that looks good on
mobile ahh.
</p>
</Col>
</Row>
</div>
);
export default Header;
| Add note about icon badge | Add note about icon badge
- stateful component coming soon
| TypeScript | apache-2.0 | srct/schedules,srct/schedules,srct/schedules | ---
+++
@@ -5,6 +5,7 @@
const Header = () => (
<div>
+ {/* TODO Extract into its own components with state management. */}
<Row className="justify-content-end my-5 px-3">
<span className="fa-stack fa-3x has-badge" data-count="0">
<i className="fa fas fa-shopping-bag fa-stack-1x" /> |
746450b0fb50fcea67d9d058b202f60443367aed | src/SyntaxNodes/UnorderedListNode.ts | src/SyntaxNodes/UnorderedListNode.ts | import { OutlineSyntaxNode } from './OutlineSyntaxNode'
export class UnorderedListNode implements OutlineSyntaxNode {
constructor(public items: UnorderedListNode.Item[]) { }
OUTLINE_SYNTAX_NODE(): void { }
}
export module UnorderedListNode {
export class Item {
constructor(public children: OutlineSyntaxNode[]) { }
protected UNORDERED_LIST_ITEM(): void { }
}
} | import { OutlineSyntaxNode } from './OutlineSyntaxNode'
import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer'
export class UnorderedListNode implements OutlineSyntaxNode {
constructor(public items: UnorderedListNode.Item[]) { }
OUTLINE_SYNTAX_NODE(): void { }
}
export module UnorderedListNode {
export class Item extends OutlineSyntaxNodeContainer {
protected UNORDERED_LIST_ITEM(): void { }
}
} | Make unordered list item extend outline container | Make unordered list item extend outline container
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,4 +1,5 @@
import { OutlineSyntaxNode } from './OutlineSyntaxNode'
+import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer'
export class UnorderedListNode implements OutlineSyntaxNode {
@@ -7,10 +8,9 @@
OUTLINE_SYNTAX_NODE(): void { }
}
+
export module UnorderedListNode {
- export class Item {
- constructor(public children: OutlineSyntaxNode[]) { }
-
+ export class Item extends OutlineSyntaxNodeContainer {
protected UNORDERED_LIST_ITEM(): void { }
}
} |
9071ad4dcd5835dd550aaa4af23faea0b95c02cd | src/app/shared/services/auth.service.ts | src/app/shared/services/auth.service.ts | import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
if (isNotExpired && profile != null && profile.userId == null) {
return false;
} else if (isNotExpired && profile == null) {
profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {JwtHelperService} from '@auth0/angular-jwt';
import {ProfileService} from '@shared/services/profile.service';
@Injectable()
export class AuthService implements CanActivate {
helper = new JwtHelperService();
constructor(private router: Router, private profileService: ProfileService) {
}
async loggedIn() {
const token = localStorage.getItem('id_token');
if (token != null) {
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
if (isNotExpired) {
if (profile == null || (profile != null && profile.userId == null)) {
profile = await this.profileService.getProfile().toPromise();
this.profileService.setProfile(profile);
}
}
return isNotExpired;
}
return false;
}
async canActivate() {
if (await this.loggedIn()) {
return true;
} else {
this.router.navigate(['unauthorized']);
return false;
}
}
}
| Fix login on old system | Fix login on old system
| TypeScript | unknown | BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app,OmicsDI/ddi-web-app,BD2K-DDI/ddi-web-app,OmicsDI/ddi-web-app | ---
+++
@@ -17,11 +17,11 @@
const expired = this.helper.decodeToken(token).expires;
const isNotExpired = new Date().getMilliseconds() < expired;
let profile = this.profileService.getProfileFromLocal();
- if (isNotExpired && profile != null && profile.userId == null) {
- return false;
- } else if (isNotExpired && profile == null) {
- profile = await this.profileService.getProfile().toPromise();
- this.profileService.setProfile(profile);
+ if (isNotExpired) {
+ if (profile == null || (profile != null && profile.userId == null)) {
+ profile = await this.profileService.getProfile().toPromise();
+ this.profileService.setProfile(profile);
+ }
}
return isNotExpired;
} |
dbfcfb6c300e2d885dd581387b75efd334aef075 | ui/common/src/wakeLock.ts | ui/common/src/wakeLock.ts | const supported: boolean = 'wakeLock' in navigator;
let sentinel: WakeLockSentinel | null = null;
export const request = () => {
if (supported) {
navigator.wakeLock
.request('screen')
.then((response: WakeLockSentinel) => {
sentinel = response;
})
.catch((error: Error) => {
console.error('wakeLock - request failure. ' + error.message);
});
}
};
export const release = () => {
if (supported) {
sentinel
.release()
.then(() => {
sentinel = null;
})
.catch((error: Error) => {
console.error('wakeLock - release failure. ' + error.message);
});
}
};
document.addEventListener('visibilitychange', () => {
if (sentinel !== null && document.visibilityState === 'visible') {
request();
}
});
| const supported: boolean = 'wakeLock' in navigator;
let shouldLock: boolean = false;
let sentinel: WakeLockSentinel;
export const request = () => {
if (supported) {
navigator.wakeLock
.request('screen')
.then((response: WakeLockSentinel) => {
shouldLock = true;
sentinel = response;
})
.catch((error: Error) => {
console.error('wakeLock - request failure. ' + error.message);
});
}
};
export const release = () => {
if (supported) {
sentinel
.release()
.then(() => {
shouldLock = false;
})
.catch((error: Error) => {
console.error('wakeLock - release failure. ' + error.message);
});
}
};
/* Since the act of switching tabs automatically releases
* the wake lock, we re-request wake lock here based on the
* `shouldLock` flag.
*/
document.addEventListener('visibilitychange', () => {
if (shouldLock && document.visibilityState === 'visible') {
request();
}
});
| Use separate var to keep track of persistence | Use separate var to keep track of persistence
| TypeScript | agpl-3.0 | luanlv/lila,luanlv/lila,luanlv/lila,arex1337/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,luanlv/lila,arex1337/lila,arex1337/lila,arex1337/lila,luanlv/lila,luanlv/lila | ---
+++
@@ -1,11 +1,13 @@
const supported: boolean = 'wakeLock' in navigator;
-let sentinel: WakeLockSentinel | null = null;
+let shouldLock: boolean = false;
+let sentinel: WakeLockSentinel;
export const request = () => {
if (supported) {
navigator.wakeLock
.request('screen')
.then((response: WakeLockSentinel) => {
+ shouldLock = true;
sentinel = response;
})
.catch((error: Error) => {
@@ -19,7 +21,7 @@
sentinel
.release()
.then(() => {
- sentinel = null;
+ shouldLock = false;
})
.catch((error: Error) => {
console.error('wakeLock - release failure. ' + error.message);
@@ -27,8 +29,12 @@
}
};
+/* Since the act of switching tabs automatically releases
+ * the wake lock, we re-request wake lock here based on the
+ * `shouldLock` flag.
+ */
document.addEventListener('visibilitychange', () => {
- if (sentinel !== null && document.visibilityState === 'visible') {
+ if (shouldLock && document.visibilityState === 'visible') {
request();
}
}); |
385fe9873902d4203f084dd8a8da6f8869156b6e | web-interface/web-interface-client/src/main/ts/services-list.component.ts | web-interface/web-interface-client/src/main/ts/services-list.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Model, Service } from './model';
import { ModelService } from './model.service';
@Component({
selector: 'services-list',
template: `<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body scroll-panel">
<div class="list-group">
<a *ngFor="let service of model.services" (click)="onSelect(service)" class="list-group-item"><span class="list-group-item-text">{{service.name}}</span></a>
<a routerLink="/createService" class="list-group-item"><span class="list-group-item-text">Create new service</span></a>
</div>
</div>
<div>
</div>`
})
export class ServicesListComponent implements OnInit {
model: Model = {
services: []
};
showCreateComponent = false;
constructor(private router: Router, private modelService: ModelService) {
this.model = this.modelService.model;
}
onSelect(service: Service): void {
let link = ['/service', service.name];
this.router.navigate(link);
}
createService(): void {
this.showCreateComponent = true;
}
ngOnInit(): void {
this.modelService.getModel().then(model => {}, error => {
console.error(error);
});
}
}
| import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Model, Service } from './model';
import { ModelService } from './model.service';
@Component({
selector: 'services-list',
template: `<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Services</h3>
</div>
<ul class="list-group">
<li *ngFor="let service of model.services" (click)="onSelect(service)" class="list-group-item"><span class="list-group-item-text">{{service.name}}</span></li>
<li routerLink="/createService" class="list-group-item"><span class="list-group-item-text">Create new service</span></li>
</ul>
</div>
</div>`
})
export class ServicesListComponent implements OnInit {
model: Model = {
services: []
};
showCreateComponent = false;
constructor(private router: Router, private modelService: ModelService) {
this.model = this.modelService.model;
}
onSelect(service: Service): void {
let link = ['/service', service.name];
this.router.navigate(link);
}
createService(): void {
this.showCreateComponent = true;
}
ngOnInit(): void {
this.modelService.getModel().then(model => {}, error => {
console.error(error);
});
}
}
| Update HTML for the list of services to follow latest Push style guidelines. | Update HTML for the list of services to follow latest Push style guidelines.
| TypeScript | apache-2.0 | pushtechnology/diffusion-rest-adapter,pushtechnology/diffusion-rest-adapter | ---
+++
@@ -8,13 +8,14 @@
selector: 'services-list',
template: `<div class="col-md-3">
<div class="panel panel-default">
- <div class="panel-body scroll-panel">
- <div class="list-group">
- <a *ngFor="let service of model.services" (click)="onSelect(service)" class="list-group-item"><span class="list-group-item-text">{{service.name}}</span></a>
- <a routerLink="/createService" class="list-group-item"><span class="list-group-item-text">Create new service</span></a>
- </div>
+ <div class="panel-heading">
+ <h3 class="panel-title">Services</h3>
</div>
- <div>
+ <ul class="list-group">
+ <li *ngFor="let service of model.services" (click)="onSelect(service)" class="list-group-item"><span class="list-group-item-text">{{service.name}}</span></li>
+ <li routerLink="/createService" class="list-group-item"><span class="list-group-item-text">Create new service</span></li>
+ </ul>
+ </div>
</div>`
})
export class ServicesListComponent implements OnInit { |
62e93b965e4b301527ec5441c40957dfd2f033cd | app/app.module.ts | app/app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AppRoutingModule, routedComponents } from './app-routing.module';
import { ContentService } from './content.service';
import { StorageService } from './storage.service';
@NgModule({
imports: [
BrowserModule,
HttpModule,
AppRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
routedComponents
],
bootstrap: [AppComponent],
providers: [
ContentService,
StorageService
]
})
export class AppModule {
}
| import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
import { AppRoutingModule, routedComponents } from './app-routing.module';
import { ContentService } from './content.service';
import { StorageService } from './storage.service';
export const entryComponents: any[] = [HomeComponent];
@NgModule({
imports: [
BrowserModule,
HttpModule,
AppRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
routedComponents
],
bootstrap: [AppComponent],
providers: [
ContentService,
StorageService
],
entryComponents: entryComponents
})
export class AppModule {
}
| Make home an entry component | Make home an entry component
| TypeScript | mit | stvnhrlnd/sh-app,stvnhrlnd/sh-app,stvnhrlnd/sh-app | ---
+++
@@ -7,6 +7,8 @@
import { AppRoutingModule, routedComponents } from './app-routing.module';
import { ContentService } from './content.service';
import { StorageService } from './storage.service';
+
+export const entryComponents: any[] = [HomeComponent];
@NgModule({
imports: [
@@ -23,7 +25,8 @@
providers: [
ContentService,
StorageService
- ]
+ ],
+ entryComponents: entryComponents
})
export class AppModule {
} |
b91830f72f5a229b7376fcfa238ef38c077b2122 | types/vfile-location/index.d.ts | types/vfile-location/index.d.ts | // Type definitions for vfile-location 2.0
// Project: https://github.com/vfile/vfile-location
// Definitions by: Ika <https://github.com/ikatyang>
// Junyoung Choi <https://github.com/rokt33r>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import * as VFile from "vfile";
declare function vfileLocation(vfile: string | VFile.VFile): vfileLocation.Location;
declare namespace vfileLocation {
interface Location {
/**
* Get the `offset` (`number`) for a line and column-based `position` in the bound file.
* Returns `-1` when given invalid or out of bounds input.
*/
toOffset(position: { line: number; column: number }): number;
/**
* Get the line and column-based `position` for `offset` in the bound file.
*/
toPosition(offset: number): { line: number; column: number; offset: number };
}
}
export = vfileLocation;
| // Type definitions for vfile-location 2.0
// Project: https://github.com/vfile/vfile-location
// Definitions by: Ika <https://github.com/ikatyang>
// Junyoung Choi <https://github.com/rokt33r>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
import * as VFile from "vfile";
declare function vfileLocation(vfile: string | VFile.VFile): vfileLocation.Location;
declare namespace vfileLocation {
interface Location {
/**
* Get the `offset` (`number`) for a line and column-based `position` in the bound file.
* Returns `-1` when given invalid or out of bounds input.
*/
toOffset(position: { line: number; column: number }): number;
/**
* Get the line and column-based `position` for `offset` in the bound file.
*/
toPosition(offset: number): { line: number; column: number; offset: number };
}
}
export = vfileLocation;
| Fix typescript version of vfile-location | Fix typescript version of vfile-location
| TypeScript | mit | dsebastien/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,mcliment/DefinitelyTyped | ---
+++
@@ -3,7 +3,7 @@
// Definitions by: Ika <https://github.com/ikatyang>
// Junyoung Choi <https://github.com/rokt33r>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-// TypeScript Version: 2.4
+// TypeScript Version: 3.0
import * as VFile from "vfile";
|
7e92a3dcd170ef2afebc9f98e7a9c9ff356a2d16 | app/src/lib/stores/pull-request-store.ts | app/src/lib/stores/pull-request-store.ts | import { PullRequestDatabase } from '../databases'
/** The store for GitHub Pull Requests. */
export class PullRequestStore {
private db: PullRequestDatabase
public constructor(db: PullRequestDatabase) {
this.db = db
}
}
| import { PullRequestDatabase } from '../databases'
import { GitHubRepository } from '../../models/github-repository'
import { API, IAPIPullRequest } from '../api'
/** The store for GitHub Pull Requests. */
export class PullRequestStore {
private db: PullRequestDatabase
public constructor(db: PullRequestDatabase) {
this.db = db
}
public async fetchPullRequests(
repository: GitHubRepository,
account: Account
) {
const api = API.fromAccount(account)
const pullRequests = await api.fetchPullRequests(
repository.owner.login,
'',
'open'
)
}
}
| Add fetch method; only needed to work from personal computer | Add fetch method; only needed to work from personal computer
| TypeScript | mit | desktop/desktop,gengjiawen/desktop,desktop/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,shiftkey/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,gengjiawen/desktop,gengjiawen/desktop,j-f1/forked-desktop,say25/desktop | ---
+++
@@ -1,4 +1,6 @@
import { PullRequestDatabase } from '../databases'
+import { GitHubRepository } from '../../models/github-repository'
+import { API, IAPIPullRequest } from '../api'
/** The store for GitHub Pull Requests. */
export class PullRequestStore {
@@ -7,4 +9,17 @@
public constructor(db: PullRequestDatabase) {
this.db = db
}
+
+ public async fetchPullRequests(
+ repository: GitHubRepository,
+ account: Account
+ ) {
+ const api = API.fromAccount(account)
+
+ const pullRequests = await api.fetchPullRequests(
+ repository.owner.login,
+ '',
+ 'open'
+ )
+ }
} |
e299ab7566bac622fe596e44bced0800f15e6a24 | manup-demo/src/app/app.component.ts | manup-demo/src/app/app.component.ts | import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { ManUpService } from 'ionic-manup';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = TabsPage;
constructor(platform: Platform, private manup: ManUpService) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
manup.validate();
});
}
}
| import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { ManUpService } from 'ionic-manup';
import { TranslateService } from 'ng2-translate'
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage = TabsPage;
constructor(platform: Platform, private manup: ManUpService, private translate: TranslateService) {
translate.setDefaultLang('en');
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
manup.validate();
});
}
}
| Set default languate to english | Set default languate to english
| TypeScript | mit | NextFaze/ionic-manup,NextFaze/ionic-manup,NextFaze/ionic-manup | ---
+++
@@ -5,6 +5,7 @@
import { TabsPage } from '../pages/tabs/tabs';
import { ManUpService } from 'ionic-manup';
+import { TranslateService } from 'ng2-translate'
@Component({
templateUrl: 'app.html'
@@ -12,7 +13,8 @@
export class MyApp {
rootPage = TabsPage;
- constructor(platform: Platform, private manup: ManUpService) {
+ constructor(platform: Platform, private manup: ManUpService, private translate: TranslateService) {
+ translate.setDefaultLang('en');
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need. |
bba7bf48bbc95dfbb320621cbc30e60a855813e6 | src/app/modal/modal.component.ts | src/app/modal/modal.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
interface ModalConfig extends Object {
title?: string;
id?: string;
}
const defaultConfig = <ModalConfig> {};
let id = 0;
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
@Input() options: ModalConfig;
@Output() opened = new EventEmitter<any>();
@Output() closed = new EventEmitter<any>();
private show: boolean = false;
private id: string;
private titleId: string;
private contentId: string;
private html: HTMLElement = document.getElementsByTagName('html')[0];
constructor() {}
ngOnInit() {
this.options = Object.assign({}, defaultConfig, this.options);
this.id = this.options.id || `modal-${id++}`;
this.titleId = `${this.id}-title`;
this.contentId = `${this.id}-content`;
}
open() {
this.show = true;
this.opened.emit(null);
this.preventBgScrolling();
}
close() {
this.show = false;
this.closed.emit(null);
this.preventBgScrolling();
}
private preventBgScrolling() {
this.html.style.overflow = this.show ? 'hidden' : '';
}
}
| import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
interface ModalConfig extends Object {
title?: string;
id?: string;
}
const defaultConfig = <ModalConfig> {};
let id = 0;
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
@Input() options: ModalConfig;
@Output() opened = new EventEmitter<any>();
@Output() closed = new EventEmitter<any>();
private show: boolean = false;
private id: string;
private titleId: string;
private contentId: string;
private html: HTMLElement = document.querySelector('html');
constructor() {}
ngOnInit() {
this.options = Object.assign({}, defaultConfig, this.options);
this.id = this.options.id || `modal-${id++}`;
this.titleId = `${this.id}-title`;
this.contentId = `${this.id}-content`;
}
open() {
this.show = true;
this.opened.emit(null);
this.preventBgScrolling();
}
close() {
this.show = false;
this.closed.emit(null);
this.preventBgScrolling();
}
private preventBgScrolling() {
this.html.style.overflow = this.show ? 'hidden' : '';
}
}
| Use querySelector instead of getElementsByTagName ✍️ | Use querySelector instead of getElementsByTagName ✍️
| TypeScript | mit | filoxo/an-angular-modal,filoxo/an-angular-modal,filoxo/an-angular-modal | ---
+++
@@ -22,7 +22,7 @@
private id: string;
private titleId: string;
private contentId: string;
- private html: HTMLElement = document.getElementsByTagName('html')[0];
+ private html: HTMLElement = document.querySelector('html');
constructor() {}
|
65f8127ceb4382e7635578e122dbd4c45c3fa345 | packages/@sanity/base/src/preview/index.ts | packages/@sanity/base/src/preview/index.ts | import observeFields from './observeFields'
import resolveRefType from './utils/resolveRefType'
import {createPathObserver} from './createPathObserver'
import {createPreviewObserver} from './createPreviewObserver'
export {default} from './components/SanityDefaultPreview'
export {default as SanityDefaultPreview} from './components/SanityDefaultPreview'
export {default as PreviewFields} from './components/PreviewFields'
export {default as SanityPreview} from './components/SanityPreview'
export {default as PreviewSubscriber} from './components/PreviewSubscriber'
export {default as WithVisibility} from './components/WithVisibility'
export const observePaths = createPathObserver(observeFields)
export const observeForPreview = createPreviewObserver(observePaths, resolveRefType)
| import observeFields from './observeFields'
import resolveRefType from './utils/resolveRefType'
import {createPathObserver} from './createPathObserver'
import {createPreviewObserver} from './createPreviewObserver'
export {default} from './components/SanityPreview'
export {default as SanityDefaultPreview} from './components/SanityDefaultPreview'
export {default as PreviewFields} from './components/PreviewFields'
export {default as SanityPreview} from './components/SanityPreview'
export {default as PreviewSubscriber} from './components/PreviewSubscriber'
export {default as WithVisibility} from './components/WithVisibility'
export const observePaths = createPathObserver(observeFields)
export const observeForPreview = createPreviewObserver(observePaths, resolveRefType)
| Fix wrong reexport from base/preview | [base] Fix wrong reexport from base/preview
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -3,7 +3,7 @@
import {createPathObserver} from './createPathObserver'
import {createPreviewObserver} from './createPreviewObserver'
-export {default} from './components/SanityDefaultPreview'
+export {default} from './components/SanityPreview'
export {default as SanityDefaultPreview} from './components/SanityDefaultPreview'
export {default as PreviewFields} from './components/PreviewFields'
export {default as SanityPreview} from './components/SanityPreview' |
577c86c807da1b6f8f5783068f18272895cddf42 | desktop/src/main/project/index.ts | desktop/src/main/project/index.ts | import { dialog, ipcMain } from 'electron'
import fs from 'fs'
import { projects } from 'stencila'
import { CHANNEL } from '../../preload'
import { openProjectWindow, projectWindow } from './window'
export const registerProjectHandlers = () => {
ipcMain.handle(
CHANNEL.SHOW_PROJECT_WINDOW,
async (_event, directoryPath: string) => {
return openProjectWindow(directoryPath)
}
)
ipcMain.handle(CHANNEL.SELECT_PROJECT_DIR, async () => {
const { filePaths } = await dialog.showOpenDialog({
properties: ['openDirectory', 'createDirectory'],
})
const projectPath = filePaths[0]
if (projectPath !== undefined) {
openProjectWindow(projectPath)
}
})
ipcMain.handle(
CHANNEL.OPEN_PROJECT,
async (_event, directoryPath: string) => {
return openProjectWindow(directoryPath)
}
)
ipcMain.handle(
CHANNEL.GET_PROJECT_FILES,
async (_event, directoryPath: string) => {
return projects.open(directoryPath, (_topic, event) => {
projectWindow?.webContents.send(CHANNEL.GET_PROJECT_FILES, event)
})
}
)
ipcMain.handle(
CHANNEL.GET_DOCUMENT_CONTENTS,
async (_event, filePath: string) => fs.readFileSync(filePath).toString()
)
}
| import { dialog, ipcMain } from 'electron'
import { documents, projects } from 'stencila'
import { CHANNEL } from '../../preload'
import { openProjectWindow, projectWindow } from './window'
export const registerProjectHandlers = () => {
ipcMain.handle(
CHANNEL.SHOW_PROJECT_WINDOW,
async (_event, directoryPath: string) => {
return openProjectWindow(directoryPath)
}
)
ipcMain.handle(CHANNEL.SELECT_PROJECT_DIR, async () => {
const { filePaths } = await dialog.showOpenDialog({
properties: ['openDirectory', 'createDirectory'],
})
const projectPath = filePaths[0]
if (projectPath !== undefined) {
openProjectWindow(projectPath)
}
})
ipcMain.handle(
CHANNEL.OPEN_PROJECT,
async (_event, directoryPath: string) => {
return openProjectWindow(directoryPath)
}
)
ipcMain.handle(
CHANNEL.GET_PROJECT_FILES,
async (_event, directoryPath: string) => {
return projects.open(directoryPath, (_topic, event) => {
projectWindow?.webContents.send(CHANNEL.GET_PROJECT_FILES, event)
})
}
)
ipcMain.handle(
CHANNEL.GET_DOCUMENT_CONTENTS,
async (_event, filePath: string) => {
documents.open(filePath)
return documents.read(filePath)
}
)
}
| Use Stencila node bindings to read document contents | refactor(Editor): Use Stencila node bindings to read document contents
| TypeScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila | ---
+++
@@ -1,6 +1,5 @@
import { dialog, ipcMain } from 'electron'
-import fs from 'fs'
-import { projects } from 'stencila'
+import { documents, projects } from 'stencila'
import { CHANNEL } from '../../preload'
import { openProjectWindow, projectWindow } from './window'
@@ -41,6 +40,9 @@
ipcMain.handle(
CHANNEL.GET_DOCUMENT_CONTENTS,
- async (_event, filePath: string) => fs.readFileSync(filePath).toString()
+ async (_event, filePath: string) => {
+ documents.open(filePath)
+ return documents.read(filePath)
+ }
)
} |
f2e0c578cc09b13ebdebf255bf6a4b9340dda246 | src/workspace-module-resolver.ts | src/workspace-module-resolver.ts | import * as path from 'path';
import { IWorkspaceModuleProvider } from './workspace-module-provider';
import { matchByWords, stripExtension } from './utils';
import { getConfig } from './config';
export function findWorkspaceModules(moduleProvider: IWorkspaceModuleProvider, currentDocumentPath: string, packageName: string) {
if (!packageName) {
return [];
}
return moduleProvider.getWorkspaceModules()
.filter((fileInfo) => matchByWords(packageName, fileInfo.fileName))
.map((fileInfo) => composeImportPath(currentDocumentPath, fileInfo.fsPath))
.filter((importString) => !!importString);
}
function composeImportPath(currentDocumentPath: string, fsPath: string) {
let relativePath = path.relative(currentDocumentPath, fsPath).replace('.', '');
const config = getConfig();
if (config.skipInitialDotForRelativePath && relativePath.startsWith('./..')) {
relativePath = relativePath.substring(2);
}
if (config.excludeExtension) {
relativePath = stripExtension(relativePath);
}
return relativePath;
}
| import * as path from 'path';
import { IWorkspaceModuleProvider } from './workspace-module-provider';
import { matchByWords, stripExtension } from './utils';
import { getConfig } from './config';
export function findWorkspaceModules(moduleProvider: IWorkspaceModuleProvider, currentDocumentPath: string, packageName: string) {
if (!packageName) {
return [];
}
return moduleProvider.getWorkspaceModules()
.filter((fileInfo) => matchByWords(packageName, fileInfo.fileName))
.map((fileInfo) => composeImportPath(currentDocumentPath, fileInfo.fsPath))
.filter((importString) => !!importString);
}
function composeImportPath(currentDocumentPath: string, fsPath: string) {
let relativePath = path.relative(currentDocumentPath, fsPath).replace('.', '');
const config = getConfig();
if (config.skipInitialDotForRelativePath && relativePath.startsWith('./..')) {
relativePath = relativePath.substring(2);
}
if (config.excludeExtension) {
relativePath = stripExtension(relativePath);
}
return normalizeWindowsPath(relativePath);
}
function normalizeWindowsPath(windowsPath: string) {
return windowsPath.replace(/\\/g, "/");
}
| Normalize import path for Windows OS. | Normalize import path for Windows OS.
| TypeScript | mit | reflectiondm/vscode-npmsmartimporter | ---
+++
@@ -27,5 +27,9 @@
relativePath = stripExtension(relativePath);
}
- return relativePath;
+ return normalizeWindowsPath(relativePath);
}
+
+function normalizeWindowsPath(windowsPath: string) {
+ return windowsPath.replace(/\\/g, "/");
+} |
b4c569e3df4ba7fd3402f79968421231dba1086c | javascript/src/createLocation.ts | javascript/src/createLocation.ts | import * as messages from '@cucumber/messages'
export default function createLocation(props: {
line?: number
column?: number
}): messages.Location {
const location: messages.Location = { ...props }
if (location.line === 0) {
location.line = undefined
}
if (location.column === 0) {
location.column = undefined
}
return location
}
| import * as messages from '@cucumber/messages'
export default function createLocation(props: {
line: number
column?: number
}): messages.Location {
return { ...props }
}
| Change schema to make more properties required | Change schema to make more properties required
| TypeScript | mit | cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin,cucumber/gherkin | ---
+++
@@ -1,16 +1,8 @@
import * as messages from '@cucumber/messages'
export default function createLocation(props: {
- line?: number
+ line: number
column?: number
}): messages.Location {
- const location: messages.Location = { ...props }
- if (location.line === 0) {
- location.line = undefined
- }
- if (location.column === 0) {
- location.column = undefined
- }
-
- return location
+ return { ...props }
} |
0ffe24c64b7bfee0bd001e95866c6e4a460db44e | tests/cases/fourslash/findAllRefsForObjectSpread.ts | tests/cases/fourslash/findAllRefsForObjectSpread.ts | /// <reference path='fourslash.ts'/>
////interface A1 { readonly [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string };
////interface A2 { [|{| "isWriteAccess": true, "isDefinition": true |}a|]?: number };
////let a1: A1;
////let a2: A2;
////let a12 = { ...a1, ...a2 };
////a12.[|a|];
////a1.[|a|];
const ranges = test.ranges();
const [r0, r1, r2, r3] = ranges;
// members of spread types only refer to themselves and the resulting property
verify.referenceGroups(r0, [{ definition: "(property) A1.a: string", ranges: [r0, r2, r3] }]);
verify.referenceGroups(r1, [{ definition: "(property) A2.a: number", ranges: [r1, r2] }]);
// but the resulting property refers to everything
verify.referenceGroups(r2, [
{ definition: "(property) A1.a: string", ranges: [r0, r3] },
{ definition: "(property) A2.a: number", ranges: [r1] },
{ definition: "(property) a: string | number", ranges: [r2] }
]);
| /// <reference path='fourslash.ts'/>
////interface A1 { readonly [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string };
////interface A2 { [|{| "isWriteAccess": true, "isDefinition": true |}a|]?: number };
////let a1: A1;
////let a2: A2;
////let a12 = { ...a1, ...a2 };
////a12.[|a|];
////a1.[|a|];
const ranges = test.ranges();
const [r0, r1, r2, r3] = ranges;
// members of spread types only refer to themselves and the resulting property
verify.referenceGroups(r0, [{ definition: "(property) A1.a: string", ranges: [r0, r2, r3] }]);
verify.referenceGroups(r1, [{ definition: "(property) A2.a: number", ranges: [r1, r2] }]);
// but the resulting property refers to everything
verify.referenceGroups(r2, [
{ definition: "(property) A1.a: string", ranges: [r0, r3] },
{ definition: "(property) A2.a: number", ranges: [r1] },
{ definition: "(property) a: string | number", ranges: [r2] }
]);
verify.referenceGroups(r3, [{ definition: "(property) A1.a: string", ranges: [r0, r2, r3] }]);
| Expand spread property find-all-ref test | Expand spread property find-all-ref test
| TypeScript | apache-2.0 | synaptek/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,nojvek/TypeScript,mihailik/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,kpreisser/TypeScript,basarat/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,RyanCavanaugh/TypeScript,basarat/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,chuckjaz/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,donaldpipowitch/TypeScript,TukekeSoft/TypeScript,alexeagle/TypeScript,Eyas/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,nojvek/TypeScript,nojvek/TypeScript,basarat/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,Eyas/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,minestarks/TypeScript,chuckjaz/TypeScript,kpreisser/TypeScript,chuckjaz/TypeScript,chuckjaz/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,synaptek/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,Eyas/TypeScript,weswigham/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,minestarks/TypeScript,TukekeSoft/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,synaptek/TypeScript,RyanCavanaugh/TypeScript,Eyas/TypeScript | ---
+++
@@ -20,3 +20,5 @@
{ definition: "(property) A2.a: number", ranges: [r1] },
{ definition: "(property) a: string | number", ranges: [r2] }
]);
+
+verify.referenceGroups(r3, [{ definition: "(property) A1.a: string", ranges: [r0, r2, r3] }]); |
0bd21f6ac42c86362706bf04ba367720c5324e8c | app/client/store.ts | app/client/store.ts | import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware,
apollo.middleware()
];
const store: any = createStore(
combineReducers({
...reducers,
apollo: apollo.reducer()
}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
| import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';
import rootSaga from './sagas';
let reduxStore = null;
const proc = process as any;
const sagaMiddleware = createSagaMiddleware();
function create(apollo, initialState) {
const middlewares = [
sagaMiddleware
];
const store: any = createStore(
combineReducers({...reducers}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
);
store.sagaTask = sagaMiddleware.run(rootSaga);
return store;
}
export function initRedux(apollo, initialState = {}) {
if (!proc.browser) {
return create(apollo, initialState);
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState);
}
return reduxStore;
}
| Remove apollo middleware and reducer | Remove apollo middleware and reducer
| TypeScript | mit | DashBouquet/react-hipstaplate,DashBouquet/react-hipstaplate | ---
+++
@@ -10,15 +10,11 @@
function create(apollo, initialState) {
const middlewares = [
- sagaMiddleware,
- apollo.middleware()
+ sagaMiddleware
];
const store: any = createStore(
- combineReducers({
- ...reducers,
- apollo: apollo.reducer()
- }),
+ combineReducers({...reducers}),
initialState,
composeWithDevTools(applyMiddleware(...middlewares))
); |
a5282c59e5a212d6c6212bebe627802612db0136 | src/desktop/apps/purchases/server.tsx | src/desktop/apps/purchases/server.tsx | import { buildServerApp } from "reaction/Artsy/Router/server"
import { stitch } from "@artsy/stitch"
import { routes } from "reaction/Apps/Purchase/routes"
import React from "react"
import { buildServerAppContext } from "desktop/lib/buildServerAppContext"
import express, { Request, Response, NextFunction } from "express"
import { skipIfClientSideRoutingEnabled } from "desktop/components/split_test/skipIfClientSideRoutingEnabled"
export const app = express()
app.get(
"/user/purchases",
skipIfClientSideRoutingEnabled,
async (req: Request, res: Response, next: NextFunction) => {
try {
const context = buildServerAppContext(req, res, {})
const {
bodyHTML,
redirect,
status,
headTags,
styleTags,
scripts,
} = await buildServerApp({
routes,
url: req.url,
userAgent: req.header("User-Agent"),
context,
})
if (redirect) {
res.redirect(302, redirect.url)
return
}
// Render layout
const layout = await stitch({
basePath: __dirname,
layout: "../../components/main_layout/templates/react_redesign.jade",
blocks: {
head: () => <React.Fragment>{headTags}</React.Fragment>,
body: bodyHTML,
},
locals: {
...res.locals,
assetPackage: "purchases",
scripts,
styleTags,
},
})
res.status(status).send(layout)
} catch (error) {
next(error)
}
}
)
| import { buildServerApp } from "reaction/Artsy/Router/server"
import { stitch } from "@artsy/stitch"
import { routes } from "reaction/Apps/Purchase/routes"
import React from "react"
import { buildServerAppContext } from "desktop/lib/buildServerAppContext"
import express, { Request, Response, NextFunction } from "express"
export const app = express()
app.get(
"/user/purchases",
async (req: Request, res: Response, next: NextFunction) => {
try {
const context = buildServerAppContext(req, res, {})
const {
bodyHTML,
redirect,
status,
headTags,
styleTags,
scripts,
} = await buildServerApp({
routes,
url: req.url,
userAgent: req.header("User-Agent"),
context,
})
if (redirect) {
res.redirect(302, redirect.url)
return
}
// Render layout
const layout = await stitch({
basePath: __dirname,
layout: "../../components/main_layout/templates/react_redesign.jade",
blocks: {
head: () => <React.Fragment>{headTags}</React.Fragment>,
body: bodyHTML,
},
locals: {
...res.locals,
assetPackage: "purchases",
scripts,
styleTags,
},
})
res.status(status).send(layout)
} catch (error) {
next(error)
}
}
)
| Remove appShell related code that was causing 404 on staging and prod | Remove appShell related code that was causing 404 on staging and prod
| TypeScript | mit | joeyAghion/force,anandaroop/force,artsy/force,erikdstock/force,anandaroop/force,izakp/force,joeyAghion/force,damassi/force,artsy/force,artsy/force-public,yuki24/force,yuki24/force,yuki24/force,oxaudo/force,erikdstock/force,eessex/force,damassi/force,yuki24/force,izakp/force,anandaroop/force,eessex/force,oxaudo/force,damassi/force,oxaudo/force,artsy/force,erikdstock/force,oxaudo/force,izakp/force,damassi/force,anandaroop/force,artsy/force,joeyAghion/force,joeyAghion/force,eessex/force,izakp/force,erikdstock/force,eessex/force,artsy/force-public | ---
+++
@@ -4,13 +4,11 @@
import React from "react"
import { buildServerAppContext } from "desktop/lib/buildServerAppContext"
import express, { Request, Response, NextFunction } from "express"
-import { skipIfClientSideRoutingEnabled } from "desktop/components/split_test/skipIfClientSideRoutingEnabled"
export const app = express()
app.get(
"/user/purchases",
- skipIfClientSideRoutingEnabled,
async (req: Request, res: Response, next: NextFunction) => {
try {
const context = buildServerAppContext(req, res, {}) |
024060e87cf85f5742c07b15a029fb84845ef7cd | server/dbconnection.test.ts | server/dbconnection.test.ts | import { MongoClient } from "mongodb";
import MongodbMemoryServer from "mongodb-memory-server";
import { StatBlock } from "../common/StatBlock";
import { probablyUniqueString } from "../common/Toolbox";
import * as DB from "./dbconnection";
describe("User Accounts", () => {
let mongod: MongodbMemoryServer;
let uri;
beforeAll(async () => {
mongod = new MongodbMemoryServer();
uri = await mongod.getUri();
DB.initialize(uri);
});
afterAll(async () => {
await mongod.stop();
});
test("Should initialize user with empty entity sets", async (done) => {
const user = await DB.upsertUser(probablyUniqueString(), "accessKey", "refreshKey", "pledge");
expect(user.encounters).toEqual({});
expect(user.playercharacters).toEqual({});
expect(user.statblocks).toEqual({});
expect(user.spells).toEqual({});
expect(user.persistentcharacters).toEqual({});
done();
});
test("baseline", async (done) => {
expect.assertions(1);
const db = await MongoClient.connect(uri);
const test = await db.collection("test").insertOne({ "foo": "bar" });
const id = test.insertedId;
const lookup = await db.collection("test").findOne({ _id: id });
expect(lookup.foo).toEqual("bar");
done();
});
});
| import { MongoClient } from "mongodb";
import MongodbMemoryServer from "mongodb-memory-server";
import { StatBlock } from "../common/StatBlock";
import { probablyUniqueString } from "../common/Toolbox";
import * as DB from "./dbconnection";
describe("User Accounts", () => {
let mongod: MongodbMemoryServer;
let uri;
beforeAll(async () => {
mongod = new MongodbMemoryServer();
uri = await mongod.getUri();
DB.initialize(uri);
}, 60000);
afterAll(async () => {
await mongod.stop();
});
test("Should initialize user with empty entity sets", async (done) => {
const user = await DB.upsertUser(probablyUniqueString(), "accessKey", "refreshKey", "pledge");
expect(user.encounters).toEqual({});
expect(user.playercharacters).toEqual({});
expect(user.statblocks).toEqual({});
expect(user.spells).toEqual({});
expect(user.persistentcharacters).toEqual({});
done();
});
test("baseline", async (done) => {
expect.assertions(1);
const db = await MongoClient.connect(uri);
const test = await db.collection("test").insertOne({ "foo": "bar" });
const id = test.insertedId;
const lookup = await db.collection("test").findOne({ _id: id });
expect(lookup.foo).toEqual("bar");
done();
});
});
| Extend timeout to allow for downloading mongodb-memory-server binary | Extend timeout to allow for downloading mongodb-memory-server binary
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -12,7 +12,7 @@
mongod = new MongodbMemoryServer();
uri = await mongod.getUri();
DB.initialize(uri);
- });
+ }, 60000);
afterAll(async () => {
await mongod.stop(); |
47a0992131fd8c717c3ef09f3eb333044173b0fe | src/api/configuration/db.ts | src/api/configuration/db.ts | import * as db from '../../data'
const defaultConfig: Concierge.Configuration = {
name: '',
conciergePort: 3141,
debug: 0,
dockerRegistry: undefined,
proxyHostname: undefined,
registryCredentials: undefined,
statsBinSize: 60,
statsRetentionDays: 3,
maxConcurrentBuilds: 2,
gitPollingIntervalSecs: 5
}
export async function getConfig() {
const result: Schema.Configuration = await db
.configurations()
.select()
.where('id', 1)
.first()
const config: Concierge.Configuration = JSON.parse(result.config)
return {
...defaultConfig,
...config
}
}
export async function setConfig(config: Partial<Concierge.Configuration>) {
const original = await getConfig()
const next: Concierge.Configuration = {
...defaultConfig,
...original,
...config,
conciergePort: original.conciergePort
}
await db
.configurations()
.update({ config: next })
.where('id', 1)
return next
}
| import * as db from '../../data'
const defaultConfig: Concierge.Configuration = {
name: '',
conciergePort: 3141,
debug: 0,
dockerRegistry: undefined,
proxyHostname: undefined,
registryCredentials: undefined,
statsBinSize: 60,
statsRetentionDays: 3,
maxConcurrentBuilds: 2,
gitPollingIntervalSecs: 5
}
export async function getConfig() {
const result: Schema.Configuration = await db
.configurations()
.select()
.where('id', 1)
.first()
const config: Concierge.Configuration = JSON.parse(result.config)
return {
...defaultConfig,
...config
}
}
export async function setConfig(config: Partial<Concierge.Configuration>) {
const original = await getConfig()
const next: Concierge.Configuration = {
...defaultConfig,
...original,
...config,
conciergePort: original.conciergePort
}
const keys = Object.keys(config) as Array<keyof Concierge.Configuration>
const badKeys: string[] = []
for (const key of keys) {
const validator = validate[key]
if (!validator) {
continue
}
if (!validator(config[key])) {
badKeys.push(key)
}
}
if (badKeys.length > 0) {
const message = badKeys.join(', ')
throw new Error(`Invalid configuration, keys have invalid values: ${message}`)
}
await db
.configurations()
.update({ config: next })
.where('id', 1)
return next
}
const validate: { [key in keyof Concierge.Configuration]?: (value: any) => boolean } = {
debug: val => typeof val === 'number',
gitPollingIntervalSecs: val => typeof val === 'number' && val > 0,
statsBinSize: val => typeof val === 'number' && val > 0,
maxConcurrentBuilds: val => typeof val === 'number' && val > 0,
statsRetentionDays: val => typeof val === 'number' && val > 0
}
| Implement config validation on update | Implement config validation on update
| TypeScript | mit | the-concierge/concierge,the-concierge/concierge,the-concierge/concierge | ---
+++
@@ -37,6 +37,25 @@
conciergePort: original.conciergePort
}
+ const keys = Object.keys(config) as Array<keyof Concierge.Configuration>
+
+ const badKeys: string[] = []
+ for (const key of keys) {
+ const validator = validate[key]
+ if (!validator) {
+ continue
+ }
+
+ if (!validator(config[key])) {
+ badKeys.push(key)
+ }
+ }
+
+ if (badKeys.length > 0) {
+ const message = badKeys.join(', ')
+ throw new Error(`Invalid configuration, keys have invalid values: ${message}`)
+ }
+
await db
.configurations()
.update({ config: next })
@@ -44,3 +63,11 @@
return next
}
+
+const validate: { [key in keyof Concierge.Configuration]?: (value: any) => boolean } = {
+ debug: val => typeof val === 'number',
+ gitPollingIntervalSecs: val => typeof val === 'number' && val > 0,
+ statsBinSize: val => typeof val === 'number' && val > 0,
+ maxConcurrentBuilds: val => typeof val === 'number' && val > 0,
+ statsRetentionDays: val => typeof val === 'number' && val > 0
+} |
d324f57361191e0a2fe68fdc87777db4c77f9f22 | src/app/shell/formatters.ts | src/app/shell/formatters.ts | /**
* Given a value 0-1, returns a string describing it as a percentage from 0-100
*/
export function percent(val: number): string {
return `${Math.min(100, Math.floor(100 * val))}%`;
}
/**
* Given a value on (or outside) a 0-100 scale, returns a css color key and value for a react `style` attribute
*/
export function getColor(value: number, property = 'background-color') {
let color = 0;
if (value < 0) {
return { [property]: 'white' };
} else if (value <= 85) {
color = 0;
} else if (value <= 90) {
color = 20;
} else if (value <= 95) {
color = 60;
} else if (value <= 99) {
color = 120;
} else if (value >= 100) {
color = 190;
}
return {
[property]: `hsla(${color},65%,50%, 1)`,
};
}
| /**
* Given a value 0-1, returns a string describing it as a percentage from 0-100
*/
export function percent(val: number): string {
return `${Math.min(100, Math.floor(100 * val))}%`;
}
/**
* Given a value on (or outside) a 0-100 scale, returns a css color key and value for a react `style` attribute
*/
export function getColor(value: number, property = 'background-color') {
let color = 0;
if (value < 0) {
return { [property]: 'white' };
} else if (value <= 85) {
color = 0;
} else if (value <= 90) {
color = 20;
} else if (value <= 95) {
color = 60;
} else if (value < 100) {
color = 120;
} else if (value >= 100) {
color = 190;
}
return {
[property]: `hsla(${color},65%,50%, 1)`,
};
}
| Fix color grading for ]99%, 100%[ interval | Fix color grading for ]99%, 100%[ interval
| TypeScript | mit | DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM | ---
+++
@@ -18,7 +18,7 @@
color = 20;
} else if (value <= 95) {
color = 60;
- } else if (value <= 99) {
+ } else if (value < 100) {
color = 120;
} else if (value >= 100) {
color = 190; |
68d6e57870dd5ea87a03d13adcfcc72786d8348a | server/lib/activitypub/local-video-viewer.ts | server/lib/activitypub/local-video-viewer.ts | import { Transaction } from 'sequelize'
import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer'
import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section'
import { MVideo } from '@server/types/models'
import { WatchActionObject } from '@shared/models'
import { getDurationFromActivityStream } from './activity'
async function createOrUpdateLocalVideoViewer (watchAction: WatchActionObject, video: MVideo, t: Transaction) {
const stats = await LocalVideoViewerModel.loadByUrl(watchAction.id)
if (stats) await stats.destroy({ transaction: t })
const localVideoViewer = await LocalVideoViewerModel.create({
url: watchAction.id,
uuid: watchAction.uuid,
watchTime: getDurationFromActivityStream(watchAction.duration),
startDate: new Date(watchAction.startTime),
endDate: new Date(watchAction.endTime),
country: watchAction.location
? watchAction.location.addressCountry
: null,
videoId: video.id
})
await LocalVideoViewerWatchSectionModel.bulkCreateSections({
localVideoViewerId: localVideoViewer.id,
watchSections: watchAction.watchSections.map(s => ({
start: s.startTimestamp,
end: s.endTimestamp
}))
})
}
// ---------------------------------------------------------------------------
export {
createOrUpdateLocalVideoViewer
}
| import { Transaction } from 'sequelize'
import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer'
import { LocalVideoViewerWatchSectionModel } from '@server/models/view/local-video-viewer-watch-section'
import { MVideo } from '@server/types/models'
import { WatchActionObject } from '@shared/models'
import { getDurationFromActivityStream } from './activity'
async function createOrUpdateLocalVideoViewer (watchAction: WatchActionObject, video: MVideo, t: Transaction) {
const stats = await LocalVideoViewerModel.loadByUrl(watchAction.id)
if (stats) await stats.destroy({ transaction: t })
const localVideoViewer = await LocalVideoViewerModel.create({
url: watchAction.id,
uuid: watchAction.uuid,
watchTime: getDurationFromActivityStream(watchAction.duration),
startDate: new Date(watchAction.startTime),
endDate: new Date(watchAction.endTime),
country: watchAction.location
? watchAction.location.addressCountry
: null,
videoId: video.id
}, { transaction: t })
await LocalVideoViewerWatchSectionModel.bulkCreateSections({
localVideoViewerId: localVideoViewer.id,
watchSections: watchAction.watchSections.map(s => ({
start: s.startTimestamp,
end: s.endTimestamp
})),
transaction: t
})
}
// ---------------------------------------------------------------------------
export {
createOrUpdateLocalVideoViewer
}
| Fix transaction when processing local viewer | Fix transaction when processing local viewer
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -23,7 +23,7 @@
: null,
videoId: video.id
- })
+ }, { transaction: t })
await LocalVideoViewerWatchSectionModel.bulkCreateSections({
localVideoViewerId: localVideoViewer.id,
@@ -31,7 +31,9 @@
watchSections: watchAction.watchSections.map(s => ({
start: s.startTimestamp,
end: s.endTimestamp
- }))
+ })),
+
+ transaction: t
})
}
|
4ce47293e496e6aa1e4a17fbd9f49eeb3bd06ea5 | src/renderer/modules/Tracker/TrackerPage.tsx | src/renderer/modules/Tracker/TrackerPage.tsx | import { NonIdealState } from "@blueprintjs/core";
import { inject, observer } from "mobx-react";
import React from "react";
import { ICommonStoreProps } from "../../common/ICommonStoreProps";
import { WorkItemType } from "../../store/models/WorkItem";
import ActionBar from "./ActionBar";
import WorkItem from "./WorkItem";
@inject("store")
@observer
export default class TrackerPage extends React.Component<ICommonStoreProps> {
public render() {
const { store } = this.props;
return (
<div>
<h1>{store!.workDay.formattedDate}</h1>
<ActionBar onAdd={store!.workDay.addWorkItem} />
{store!.workDay.noItems ? (
<NonIdealState
title="No work items today..."
visual="pt-icon-cross"
/>
) : (
store!.workDay.allItems.map((i: WorkItemType) => (
<WorkItem workItem={i} />
))
)}
</div>
);
}
}
| import { NonIdealState } from "@blueprintjs/core";
import { inject, observer } from "mobx-react";
import React from "react";
import { ICommonStoreProps } from "../../common/ICommonStoreProps";
import { WorkItemType } from "../../store/models/WorkItem";
import ActionBar from "./ActionBar";
import WorkItem from "./WorkItem";
@inject("store")
@observer
export default class TrackerPage extends React.Component<ICommonStoreProps> {
public render() {
const { store } = this.props;
return (
<div>
<h1>{store!.workDay.formattedDate}</h1>
<ActionBar onAdd={store!.workDay.addWorkItem} />
{store!.workDay.noItems ? (
<NonIdealState
title="No work items today..."
visual="pt-icon-cross"
/>
) : (
store!.workDay.allItems.map((i: WorkItemType) => (
<WorkItem key={i.id.toString()} workItem={i} />
))
)}
</div>
);
}
}
| Fix key property in Tracker Page | Fix key property in Tracker Page
| TypeScript | mit | sgaloux/timetrack2,sgaloux/timetrack2 | ---
+++
@@ -22,7 +22,7 @@
/>
) : (
store!.workDay.allItems.map((i: WorkItemType) => (
- <WorkItem workItem={i} />
+ <WorkItem key={i.id.toString()} workItem={i} />
))
)}
</div> |
6cef96cf59e6e943b990ee3a02e562a67bde5e9b | A2/quickstart/src/app/app.custom.component.ts | A2/quickstart/src/app/app.custom.component.ts | import { Component } from '@angular/core';
@Component({
selector: "my-app-custom-component",
templateUrl: "app/app.custom.component.html",
styleUrls: [ "app/app.custom.component.css" ]
})
export class AppCustomComponent {
title = "Ultra Racing Schedule";
races = [{
"id": 1,
"name": "Daytona Thunderdome",
"date": new Date('2512-01-04T14:00:00'),
"about": "Race through the ruins of an ancient Florida battle arena.",
"entryFee": 3200
}, {
"id": 2,
"name": "San Francisco Ruins",
"date": new Date('2512-07-03T20:00:00'),
"about": "Drift down the streets of a city almost sunk under the ocean.",
"entryFee": 4700
}, {
"id": 3,
"name": "New York City Skyline",
"date": new Date('2512-07-12T21:00:00'),
"about": "Fly between buildings in the electronic sky.",
"entryFee": 0
}];
getDate(currentDate: Date) {
return currentDate;
}
};
| import { Component } from "@angular/core";
import { RacePart } from "./race-part";
import { RACE_PARTS } from "./mocks";
@Component({
selector: "my-app-custom-component",
templateUrl: "app/app.custom.component.html",
styleUrls: [ "app/app.custom.component.css" ]
})
export class AppCustomComponent {
title = "Ultra Racing Schedule";
races: RacePart[];
getDate(currentDate: Date) {
return currentDate;
}
ngOnInit() {
this.races = RACE_PARTS;
}
};
| Replace data to separated files | Replace data to separated files
| TypeScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -1,4 +1,6 @@
-import { Component } from '@angular/core';
+import { Component } from "@angular/core";
+import { RacePart } from "./race-part";
+import { RACE_PARTS } from "./mocks";
@Component({
selector: "my-app-custom-component",
@@ -8,26 +10,13 @@
export class AppCustomComponent {
title = "Ultra Racing Schedule";
- races = [{
- "id": 1,
- "name": "Daytona Thunderdome",
- "date": new Date('2512-01-04T14:00:00'),
- "about": "Race through the ruins of an ancient Florida battle arena.",
- "entryFee": 3200
- }, {
- "id": 2,
- "name": "San Francisco Ruins",
- "date": new Date('2512-07-03T20:00:00'),
- "about": "Drift down the streets of a city almost sunk under the ocean.",
- "entryFee": 4700
- }, {
- "id": 3,
- "name": "New York City Skyline",
- "date": new Date('2512-07-12T21:00:00'),
- "about": "Fly between buildings in the electronic sky.",
- "entryFee": 0
- }];
+ races: RacePart[];
+
getDate(currentDate: Date) {
return currentDate;
}
+
+ ngOnInit() {
+ this.races = RACE_PARTS;
+ }
}; |
8d6721729bcae2840545e3961bd547a26ccb2577 | src/app/dim-ui/bungie-image.tsx | src/app/dim-ui/bungie-image.tsx | import * as React from 'react';
/**
* A relative path to a Bungie.net image asset.
*/
export type BungieImagePath = string;
interface BungieImageProps {
src: BungieImagePath;
}
/**
* An image tag that links its src to bungie.net. Other props pass through to the underlying image.
*/
export function BungieImage(props: BungieImageProps) {
const { src, ...otherProps } = props;
return <img src={bungieNetPath(src)} {...otherProps} />;
}
/**
* Produce a style object that sets the background image to an image on bungie.net.
*/
export function bungieBackgroundStyle(src: BungieImagePath) {
return { backgroundImage: `url(${bungieNetPath(src)})` };
}
/**
* Expand a relative bungie.net asset path to a full path.
*/
export function bungieNetPath(src: BungieImagePath): string {
return `https://www.bungie.net${src}`;
}
| import * as React from 'react';
/**
* A relative path to a Bungie.net image asset.
*/
export type BungieImagePath = string;
interface BungieImageProps {
src: BungieImagePath;
}
/**
* An image tag that links its src to bungie.net. Other props pass through to the underlying image.
*/
export function BungieImage(props: BungieImageProps & React.ImgHTMLAttributes<HTMLImageElement>) {
const { src, ...otherProps } = props;
return <img src={bungieNetPath(src)} {...otherProps} />;
}
/**
* Produce a style object that sets the background image to an image on bungie.net.
*/
export function bungieBackgroundStyle(src: BungieImagePath) {
return { backgroundImage: `url(${bungieNetPath(src)})` };
}
/**
* Expand a relative bungie.net asset path to a full path.
*/
export function bungieNetPath(src: BungieImagePath): string {
return `https://www.bungie.net${src}`;
}
| Tweak how bungie image props types work | Tweak how bungie image props types work
| TypeScript | mit | delphiactual/DIM,DestinyItemManager/DIM,delphiactual/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,chrisfried/DIM,bhollis/DIM,bhollis/DIM,bhollis/DIM,chrisfried/DIM,DestinyItemManager/DIM,delphiactual/DIM,chrisfried/DIM,chrisfried/DIM,delphiactual/DIM,bhollis/DIM | ---
+++
@@ -12,7 +12,7 @@
/**
* An image tag that links its src to bungie.net. Other props pass through to the underlying image.
*/
-export function BungieImage(props: BungieImageProps) {
+export function BungieImage(props: BungieImageProps & React.ImgHTMLAttributes<HTMLImageElement>) {
const { src, ...otherProps } = props;
return <img src={bungieNetPath(src)} {...otherProps} />;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.