Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add test file to check Typescript types for the .js dist | // Test file to check Typescript types for the .js dist
import noUiSlider from 'dist/nouislider.js';
const element: HTMLElement|null = document.querySelector('#slider');
if (element) {
noUiSlider.create(element, {
start: [20, 50],
range: {
min: 0,
'50%': 30,
max: 100
}
});
const range = {
min: 0,
'50%': 30,
max: 100
};
noUiSlider.create(element, {
start: [20, 50],
range: range
});
}
| |
Add an example unit test | import { distance, makeDivisibleBy } from "./number";
describe("distance", () => {
it("does basic straight line distance", () => {
expect(distance(1, 1, 1, 2)).toBe(1);
});
});
describe("makeDivisibleBy", () => {
it("returns same number if already divisible", () => {
expect(makeDivisibleBy(4, 4)).toBe(4);
expect(makeDivisibleBy(16, 4)).toBe(16);
});
it("returns 0 for 0 in the numerator", () => {
expect(makeDivisibleBy(0, 4)).toBe(0);
});
it("increases number when not divisible", () => {
expect(makeDivisibleBy(1, 4)).toBe(4);
expect(makeDivisibleBy(2, 4)).toBe(4);
expect(makeDivisibleBy(3, 4)).toBe(4);
expect(makeDivisibleBy(13, 4)).toBe(16);
expect(makeDivisibleBy(14, 4)).toBe(16);
expect(makeDivisibleBy(15, 4)).toBe(16);
});
});
| |
Fix false positive test failure | jest.mock("react-redux", () => ({
connect: jest.fn()
}));
import * as React from "react";
import { mount } from "enzyme";
import { FarmwarePage } from "../index";
import { FarmwareProps } from "../../devices/interfaces";
describe("<FarmwarePage />", () => {
it("renders widgets", () => {
const props: FarmwareProps = {
farmwares: {},
syncStatus: "unknown",
env: {},
dispatch: jest.fn(),
currentImage: undefined,
images: []
};
const wrapper = mount(<FarmwarePage {...props} />);
expect(wrapper.text()).toContain("Take Photo");
expect(wrapper.text()).toContain("Farmware");
expect(wrapper.text()).toContain("Camera Calibration");
expect(wrapper.text()).toContain("Weed Detector");
});
});
| jest.mock("react-redux", () => ({
connect: jest.fn()
}));
jest.mock("../../session", () => ({
Session: {
getBool: () => true // Simulate opt-in to beta features.
}
}));
import * as React from "react";
import { mount } from "enzyme";
import { FarmwarePage } from "../index";
import { FarmwareProps } from "../../devices/interfaces";
describe("<FarmwarePage />", () => {
it("renders widgets", () => {
const props: FarmwareProps = {
farmwares: {},
syncStatus: "unknown",
env: {},
dispatch: jest.fn(),
currentImage: undefined,
images: []
};
const wrapper = mount(<FarmwarePage {...props} />);
expect(wrapper.text()).toContain("Take Photo");
expect(wrapper.text()).toContain("Farmware");
expect(wrapper.text()).toContain("Camera Calibration");
expect(wrapper.text()).toContain("Weed Detector");
});
});
|
Add passing inline document HTML test | import { expect } from 'chai'
import Up from '../../index'
import { InlineUpDocument } from '../../SyntaxNodes/InlineUpDocument'
describe('An empty inline document', () => {
it('does not produce any HTML on its own', () => {
expect(Up.toInlineHtml(new InlineUpDocument([]))).to.be.eql('')
})
})
| |
Add some basic structure for OnboardingTutorial test | import { setupOnboardingTutorialRepo } from '../helpers/repositories'
describe('OnboardingTutorial', () => {
describe('isEditorInstalled()', () => {
it('returns true if step has been skipped', async () => {
const repo = await setupOnboardingTutorialRepo()
})
it('returns true if resolved editor exists', () => {})
})
})
| |
Add test for argument named 'func' | // "Fatal error: exception Parsing.Parse_error"
/*@ foo :: (func:number) => number */
function foo(func:number) {
return func
}
// SAFE
/*@ bar :: (xunc:number) => number */
function bar(xunc:number) {
return xunc
}
| |
Add unit test for image-row | import {ImageDocument} from 'idai-components-2';
import {ImageRow} from '../../../../../app/core/images/row/image-row';
describe('ImageRow', () => {
it('first page', () => {
const imageDocuments = [
{
resource: {
type: 'Drawing', id: 'i1', identifier: 'I1', width: 100,
height: 100, relations: { depicts: []},
shortDescription: 'S1', originalFilename: 'blub'
}
}
] as unknown as Array<ImageDocument>;
const imageRow = new ImageRow(1000, 100, 100, imageDocuments);
const nextPageResult = imageRow.nextPage();
expect(nextPageResult.newImageIds).toEqual(['i1']);
expect(nextPageResult.scrollWidth).toBe(0);
});
}); | |
Add reducer for responding to CONNECT_ACCOUNT_SUCCESS | import { MaybeAccount } from '../types';
import { ConnectAccountAction } from '../actions/connectAccount';
import { CONNECT_ACCOUNT_SUCCESS } from '../constants';
export default (
state: MaybeAccount = null,
action: ConnectAccountAction
): MaybeAccount => {
switch (action.type) {
case CONNECT_ACCOUNT_SUCCESS:
return { ...state, ...action.data };
default:
return state;
}
};
| |
Create an image map to make it more configurable which Editor to which image | import {
ANDROIDSTUDIO,
ATOM,
CHROME,
ECLIPSE,
SUBLIMETEXT2,
SUBLIMETEXT3,
VIM,
VSCODE
} from "../constants/editors";
import {
androidStudio128Path,
atom128Path,
chrome128Path,
eclipse128Path,
sublimeText128Path,
vim128Path,
vsCode128Path
} from "../constants/imgPaths";
interface EditorImageMap {
[s: string]: string;
}
const imgMap: EditorImageMap = {
[ANDROIDSTUDIO]: androidStudio128Path,
[ATOM]: atom128Path,
[CHROME]: chrome128Path,
[ECLIPSE]: eclipse128Path,
[SUBLIMETEXT2]: sublimeText128Path,
[SUBLIMETEXT3]: sublimeText128Path, // Should this be a different image?
[VIM]: vim128Path,
[VSCODE]: vsCode128Path
};
export default imgMap;
| |
Add failing test for ref objects | import * as React from 'react';
import {
NavLink,
NavLinkProps,
match,
Link,
RouteComponentProps
} from 'react-router-dom';
import * as H from 'history';
const getIsActive = (extraProp: string) => (match: match, location: H.Location) => !!extraProp;
interface Props extends NavLinkProps {
extraProp: string;
}
export default function(props: Props) {
const {extraProp, ...rest} = props;
const isActive = getIsActive(extraProp);
return (
<NavLink {...rest} isActive={isActive}/>
);
}
type OtherProps = RouteComponentProps<{
id: string;
}>;
const Component: React.SFC<OtherProps> = props => {
if (!props.match) {
return null;
}
const { id } = props.match.params;
return (
<div>{id}</div>
);
};
<Link to="/url" />;
const acceptRef = (node: HTMLAnchorElement | null) => {};
<Link to="/url" replace={true} innerRef={acceptRef} />;
| import * as React from 'react';
import {
NavLink,
NavLinkProps,
match,
Link,
RouteComponentProps
} from 'react-router-dom';
import * as H from 'history';
const getIsActive = (extraProp: string) => (match: match, location: H.Location) => !!extraProp;
interface Props extends NavLinkProps {
extraProp: string;
}
export default function(props: Props) {
const {extraProp, ...rest} = props;
const isActive = getIsActive(extraProp);
return (
<NavLink {...rest} isActive={isActive}/>
);
}
type OtherProps = RouteComponentProps<{
id: string;
}>;
const Component: React.SFC<OtherProps> = props => {
if (!props.match) {
return null;
}
const { id } = props.match.params;
return (
<div>{id}</div>
);
};
<Link to="/url" />;
const refCallback: React.Ref<HTMLAnchorElement> = node => {};
<Link to="/url" replace={true} innerRef={refCallback} />;
const ref = React.createRef<HTMLAnchorElement>();
<Link to="/url" replace={true} innerRef={ref} />;
|
Add redirect from path to .../id to .../id/details | import { RouterConfig } from '@angular/router';
import { CustomerComponent } from './customer.component';
import { CustomerOrdersComponent } from './customerOrders.component';
import { CustomerDetailsComponent } from './customerDetails.component';
import { CustomerEditComponent } from './customerEdit.component';
export const CustomerRoutes: RouterConfig = [
{
path: 'customers/:id',
component: CustomerComponent,
children: [
{ path:'orders', component: CustomerOrdersComponent },
{ path:'details', component: CustomerDetailsComponent },
{ path:'edit', component: CustomerEditComponent }
]
}
];
| import { RouterConfig } from '@angular/router';
import { CustomerComponent } from './customer.component';
import { CustomerOrdersComponent } from './customerOrders.component';
import { CustomerDetailsComponent } from './customerDetails.component';
import { CustomerEditComponent } from './customerEdit.component';
export const CustomerRoutes: RouterConfig = [
{ path: 'customers/:id', terminal: true, redirectTo: '/customers/:id/details' }, //route path with only a customer id to the details route.
{
path: 'customers/:id',
component: CustomerComponent,
children: [
{ path:'orders', component: CustomerOrdersComponent },
{ path:'details', component: CustomerDetailsComponent },
{ path:'edit', component: CustomerEditComponent }
]
}
];
|
Add utility methods for extensions and copying | export function shallowCopy(target: Object, source: Object) {
for (var key in source)
if (source.hasOwnProperty(key))
target[key] = source[key];
}
export function shallowExtend(target: Object, ...sources: Object[]) {
sources.forEach(source => shallowCopy(target, source));
}
export function shallowExtendNew(target: Object, ...sources: Object[]) {
return shallowExtend({}, target, sources);
}
| |
Use async() helper instead of jasmine async | import {
ComponentFixture,
TestBed
} from '@angular/core/testing';
import {
ListState,
ListStateDispatcher,
ListStateModel
} from '../list/state';
import { SkyListToolbarModule } from './';
import {
ListToolbarTestComponent
} from './fixtures/list-toolbar.component.fixture';
import { BehaviorSubject, Subject } from 'rxjs';
describe('List Toolbar Component', () => {
let state: ListState,
dispatcher: ListStateDispatcher,
fixture: any,
element: any;
beforeEach((done) => {
dispatcher = new ListStateDispatcher();
state = new ListState(new ListStateModel(), dispatcher);
TestBed
.configureTestingModule({
declarations: [
ListToolbarTestComponent
],
imports: [
SkyListToolbarModule
],
providers: [
{ provide: ListState, useValue: state },
{ provide: ListStateDispatcher, useValue: dispatcher }
]
})
.compileComponents().then(() => {
fixture = TestBed.createComponent(ListToolbarTestComponent);
element = fixture.nativeElement as HTMLElement;
fixture.detectChanges();
// always skip the first update to ListState, when state is ready
// run detectChanges once more then begin tests
state.skip(1).take(1).subscribe((s: any) => {
fixture.detectChanges();
done();
});
});
});
it('should add search by default', () => {
expect(element.querySelector("[cmp-id='search']")).not.toBeNull();
});
});
| import {
ComponentFixture,
TestBed,
async
} from '@angular/core/testing';
import {
ListState,
ListStateDispatcher,
ListStateModel
} from '../list/state';
import { SkyListToolbarModule } from './';
import {
ListToolbarTestComponent
} from './fixtures/list-toolbar.component.fixture';
import { BehaviorSubject, Subject } from 'rxjs';
describe('List Toolbar Component', () => {
let state: ListState,
dispatcher: ListStateDispatcher,
fixture: any,
element: any;
beforeEach(async(() => {
dispatcher = new ListStateDispatcher();
state = new ListState(new ListStateModel(), dispatcher);
TestBed.configureTestingModule({
declarations: [
ListToolbarTestComponent
],
imports: [
SkyListToolbarModule
],
providers: [
{ provide: ListState, useValue: state },
{ provide: ListStateDispatcher, useValue: dispatcher }
]
});
fixture = TestBed.createComponent(ListToolbarTestComponent);
element = fixture.nativeElement as HTMLElement;
fixture.detectChanges();
// always skip the first update to ListState, when state is ready
// run detectChanges once more then begin tests
state.skip(1).take(1).subscribe(() => fixture.detectChanges());
}));
it('should add search by default', () => {
expect(element.querySelector("[cmp-id='search']")).not.toBeNull();
});
});
|
Add test for enums with members with unicode names | /// <reference path='fourslash.ts' />
////enum Foo {
//// X, Y, '☆'
////}
////var x = Foo./**/
goTo.marker();
verify.memberListContains("X");
verify.memberListContains("Y");
verify.memberListCount(2); | |
Add crumpet HTTP service which returns an Observable of Crumpet[] or throws an observable error. | /**
* Created by lthompson on 18/06/2016.
*/
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Rx";
import {Crumpet} from "../data/Crumpet";
@Injectable()
export class CrumpetService {
constructor(private http:Http) {}
listCrumpets():Observable<Crumpet[]> {
var url = 'http://wondercrumpet.com/services/crumpet/list.json';
return this
.http
.get(url)
.map(result => this.cleanData(result.json()))
.catch(this.handleErrors);
}
cleanData(json):Crumpet[] {
return json.crumpets as Crumpet[];
}
handleErrors(error: Response) {
console.log('Error calling crumpet service: ', JSON.stringify(error));
return Observable.throw(error);
}
}
| |
Add some tests for forwardContext | import * as React from 'react';
import {expect} from 'chai';
import {forwardContext} from './forwardContext';
describe('forwardContext', () => {
it('should forward value from context to props', () => {
const injector = forwardContext('myProp');
const passedDownProps = {};
injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value);
expect(passedDownProps['myProp']).to.be.equals(1);
});
it('should not forward value from context if context does not have the prop', () => {
const injector = forwardContext('myProp');
const passedDownProps = {};
injector.propInjector({}, null, (name, value) => passedDownProps[name] = value);
injector.propInjector({}, {}, (name, value) => passedDownProps[name] = value);
expect(passedDownProps).not.haveOwnPropertyDescriptor('myProp');
});
it('should forward value from context to props as aliased', () => {
const injector = forwardContext('myProp', { alias: 'yourProp' });
const passedDownProps = {};
injector.propInjector({}, { myProp: 1 }, (name, value) => passedDownProps[name] = value);
expect(passedDownProps['yourProp']).to.be.equals(1);
});
it('should properly set validator on contextType even if none is provided', () => {
const injector = forwardContext('myProp');
const contextTypes = {};
injector.contextTypeInjector((name, value) => contextTypes[name] = value);
expect(contextTypes['myProp']).to.be.equals(React.PropTypes.any);
});
it('should properly override the provided validator on contextType', () => {
const injector = forwardContext('myProp', {validator: React.PropTypes.number});
const contextTypes = {};
injector.contextTypeInjector((name, value) => contextTypes[name] = value);
expect(contextTypes['myProp']).to.be.equals(React.PropTypes.number);
});
});
| |
Create SorceryService and method to get all Sorceries | import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
import {Card} from '../card/card';
import {CardService} from '../card/card.service';
import {Sorcery} from './sorcery';
@Injectable()
export class SorceryService {
constructor(private cardService: CardService) { }
private getSorceries(): Observable<Sorcery[]> {
return this.cardService.getCards()
.map((cards: Card[]) => {
return _.filter(cards, (card: Card) => {
return _.includes(card.types, 'Sorcery');
});
});
}
}
| |
Add component for Persistent Character Library | import * as React from "react";
import { PersistentCharacter } from "../../../common/PersistentCharacter";
import { LibrariesCommander } from "../../Commands/LibrariesCommander";
import { Button } from "../../Components/Button";
import { TextEnricher } from "../../TextEnricher/TextEnricher";
import { FilterCache } from "../FilterCache";
import { Listing } from "../Listing";
import { PersistentCharacterLibrary } from "../PersistentCharacterLibrary";
import { BuildListingTree } from "./BuildListingTree";
import { LibraryFilter } from "./LibraryFilter";
import { ListingViewModel } from "./Listing";
export type PersistentCharacterLibraryViewModelProps = {
librariesCommander: LibrariesCommander;
library: PersistentCharacterLibrary;
statBlockTextEnricher: TextEnricher;
};
interface State {
filter: string;
}
export class PersistentCharacterLibraryViewModel extends React.Component<PersistentCharacterLibraryViewModelProps, State> {
constructor(props: PersistentCharacterLibraryViewModelProps) {
super(props);
this.state = {
filter: "",
};
this.filterCache = new FilterCache(this.props.library.GetListings());
}
public componentDidMount() {
//TODO: Update component when adding and removing listings from library
}
public componentWillUnmount() {
//this.librarySubscription.dispose();
}
private filterCache: FilterCache<Listing<PersistentCharacter>>;
private librarySubscription: KnockoutSubscription;
private loadSavedStatBlock = (listing: Listing<PersistentCharacter>, hideOnAdd: boolean) => {
this.props.librariesCommander.AddPersistentCharacterFromListing(listing, hideOnAdd);
}
private editStatBlock = (l: Listing<PersistentCharacter>) => {
l.CurrentName.subscribe(_ => this.forceUpdate());
this.props.librariesCommander.EditPersistentCharacterStatBlock(l.Id);
}
private buildListingComponent = (l: Listing<PersistentCharacter>) => <ListingViewModel
key={l.Id}
name={l.CurrentName()}
onAdd={this.loadSavedStatBlock}
onEdit={this.editStatBlock}
listing={l} />
public render() {
const filteredListings = this.filterCache.GetFilteredEntries(this.state.filter);
const listingAndFolderComponents = BuildListingTree(this.buildListingComponent, filteredListings);
return (<div className="library">
<LibraryFilter applyFilterFn={filter => this.setState({ filter })} />
<ul className="listings">
{listingAndFolderComponents}
</ul>
<div className="buttons">
<Button additionalClassNames="hide" fontAwesomeIcon="chevron-up" onClick={() => this.props.librariesCommander.HideLibraries()} />
<Button additionalClassNames="new" fontAwesomeIcon="plus" onClick={() => alert("TODO")} />
</div>
</div>);
}
}
| |
Add issue types from OpenNeuro | const warning = Symbol('warning')
const error = Symbol('error')
const ignore = Symbol('ignore')
type Severity = typeof warning | typeof error | typeof ignore
export interface IssueFileDetail {
name: string
path: string
relativePath: string
}
export interface IssueFile {
key: string
code: number
file: IssueFileDetail
evidence: String
line: number
character: number
severity: Severity
reason: string
helpUrl: string
}
/**
* Dataset issue, derived from OpenNeuro schema and existing validator implementation
*/
export interface Issue {
severity: Severity
key: string
code: number
reason: string
files: [IssueFile?]
additionalFileCount: number
helpUrl: string
}
| |
Define bas class of threejs pushers | import { EventDispatcher } from "../util/eventdispatcher";
export abstract class Pipeline extends EventDispatcher {
constructor() {
super();
}
abstract pipe(event: any): void;
destroy(): void {
this.removeAllListeners();
}
} | |
Create root saga and reducer | import { combineReducers } from "redux";
import { all } from "redux-saga/effects";
import * as signIn from "./sign-in";
export const reducer = combineReducers({ signIn: signIn.reducer });
export function* saga() {
yield all([...signIn.sagas]);
}
| |
Create hack for RXJS subject | // TODO: Remove this when RxJS releases a stable version with a correct declaration of `Subject`.
// https://github.com/ReactiveX/rxjs/issues/2539#issuecomment-312683629
import { Operator } from 'rxjs/Operator'
import { Observable } from 'rxjs/Observable';
declare module 'rxjs/Subject' {
interface Subject<T> {
lift<R>(operator: Operator<T, R>): Observable<R>
}
}
| |
Add unit tests for max decorator | import { Max } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (less than max value)', () => {
class TestClassMaxValue {
@Max(10)
myNumber: number;
}
let testClass = new TestClassMaxValue();
let valueToAssign = 10;
testClass.myNumber = valueToAssign;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMaxValue {
@Max(10)
myNumber: number;
}
let testClass = new TestClassMaxValue();
testClass.myNumber = 20;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (greater than max value)', () => {
class TestClassMaxValue {
@Max(10, true)
myNumber: number;
}
let testClass = new TestClassMaxValue();
let valueToAssign = 10;
testClass.myNumber = valueToAssign;
testClass.myNumber = 20;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMaxValue {
@Max(10, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMaxValue();
expect(() => testClass.myNumber = 20).toThrowError(exceptionMsg);
});
}); | |
Move `IResult`, `ISearchProvider`, and `ISearchProviderDesc` | /*********************************************************
* Copyright (c) 2018 datavisyn GmbH, http://datavisyn.io
*
* This file is property of datavisyn.
* Code and any other files associated with this project
* may not be copied and/or distributed without permission.
*
* Proprietary and confidential. No warranty.
*
*********************************************************/
import {IPluginDesc} from 'phovea_core/src/plugin';
import {IDType} from 'phovea_core/src/idtype';
/**
* a search result
*/
export interface IResult {
/**
* id of this result
*/
readonly _id: number;
/**
* the name for _id
*/
readonly id: string;
/**
* label of this result
*/
readonly text: string;
readonly idType?: IDType;
}
/**
* a search provider extension provides
*/
export interface ISearchProvider {
/**
* performs the search
* @param {string} query the query to search can be ''
* @param {number} page the page starting with 0 = first page
* @param {number} pageSize the size of a page
* @returns {Promise<{ more: boolean, items: IResult[] }>} list of results along with a hint whether more are available
*/
search(query: string, page: number, pageSize: number): Promise<{ more: boolean, items: IResult[] }>;
/**
* validates the given fully queries and returns the matching result subsets
* @param {string[]} query the list of tokens to validate
* @returns {Promise<IResult[]>} a list of valid results
*/
validate(query: string[]): Promise<IResult[]>;
/**
* returns the html to be used for showing this result
* @param {IResult} item
* @param {HTMLElement} node
* @param {string} mode the kind of formatting that should be done for a result in the dropdown or for an selected item
* @param {string} currentSearchQuery optional the current search query as a regular expression in which the first group is the matched subset
* @returns {string} the formatted html text
*/
format?(item: IResult, node: HTMLElement, mode: 'result'|'selection', currentSearchQuery?: RegExp): string;
produces?(idType: IDType): boolean;
}
/**
* additional plugin description fields as defined in phovea.js
*/
export interface ISearchProviderDesc extends IPluginDesc {
/**
* id type this provider returns
*/
idType: string;
/**
* name of this search provider (used for the checkbox)
*/
name: string;
}
| |
Add tests for import component | import {ComponentFixture, TestBed, async} from "@angular/core/testing";
import { Observable } from "rxjs";
import {FormsModule} from "@angular/forms";
import {AdminService} from "./admin.service";
import {RouterTestingModule} from "@angular/router/testing";
import {NavbarComponent} from "../navbar/navbar.component";
import {ImportComponent} from "./import.component";
import {FileUploadComponent} from "./file-upload.component";
import { Http } from '@angular/http';
describe("Import Component", () => {
let importComponent: ImportComponent;
let fixture: ComponentFixture<ImportComponent>;
let mockHttp: {post: (string, any) => Observable<any>};
beforeEach(() => {
mockHttp = {
post: (str: string, a: any) => {
return Observable.of({json:() => "mockFileName"});
}
};
TestBed.configureTestingModule({
imports: [FormsModule, RouterTestingModule],
declarations: [ImportComponent, NavbarComponent, FileUploadComponent],
providers: [{provide: Http, useValue: mockHttp}]
});
});
beforeEach(
async(() => {
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(ImportComponent);
importComponent = fixture.componentInstance;
fixture.detectChanges();
});
}));
it("can be initialized", () => {
expect(importComponent).toBeDefined();
});
it("can import a file", () => {
importComponent.fu.inputEl = {nativeElement: {files: {length: 1, item: (x) => "eh"}}};
importComponent.handleUpload();
expect(importComponent.filename).toEqual("mockFileName");
expect(importComponent.uploadAttempted).toEqual(true);
});
});
| |
Move generating ResourceList.Item props to separate utility file. | import { Hit, Requester } from '../types';
import { calculateAllBadges } from './badges';
import { truncate } from './formatting';
type ExceptionStatus = 'neutral' | 'warning' | 'critical';
export interface ExceptionDescriptor {
status?: ExceptionStatus;
title?: string;
description?: string;
}
const generateExceptions = (groupId: string): ExceptionDescriptor[] => {
return groupId.startsWith('[Error:groupId]-')
? [ { status: 'warning', title: 'You are not qualified.' } ]
: [];
};
export const generateItemProps = (hit: Hit, requester: Requester | undefined) => {
const { requesterName, reward, groupId, title } = hit;
const badges = requester ? calculateAllBadges(requester) : [];
const actions = [
{
content: 'Preview',
external: true,
url: `https://www.mturk.com/mturk/preview?groupId=${groupId}`
},
{
content: 'Accept',
primary: true,
external: true,
url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}`
}
];
return {
attributeOne: truncate(title, 80),
attributeTwo: truncate(requesterName, 45),
attributeThree: reward,
badges,
actions,
exceptions: generateExceptions(groupId)
};
};
| |
Test branch grouping and filtering | import * as chai from 'chai'
const expect = chai.expect
import { groupedAndFilteredBranches } from '../src/ui/branches/grouped-and-filtered-branches'
import { Branch } from '../src/lib/local-git-operations'
describe('Branches grouping', () => {
const currentBranch = new Branch('master', null)
const defaultBranch = new Branch('master', null)
const recentBranches = [
new Branch('some-recent-branch', null),
]
const otherBranch = new Branch('other-branch', null)
const allBranches = [
currentBranch,
...recentBranches,
otherBranch,
]
it('should return all branches when the filter is empty', () => {
const results = groupedAndFilteredBranches(defaultBranch, currentBranch, allBranches, recentBranches, '')
expect(results.length).to.equal(6)
let i = 0
expect(results[i].kind).to.equal('label')
i++
expect(results[i].kind).to.equal('branch')
expect((results[i] as any).branch).to.equal(defaultBranch)
i++
expect(results[i].kind).to.equal('label')
i++
expect(results[i].kind).to.equal('branch')
expect((results[i] as any).branch).to.equal(recentBranches[0])
i++
expect(results[i].kind).to.equal('label')
i++
expect(results[i].kind).to.equal('branch')
expect((results[i] as any).branch).to.equal(otherBranch)
})
it('should only return branches that include the filter text', () => {
const results = groupedAndFilteredBranches(defaultBranch, currentBranch, allBranches, recentBranches, 'ot')
expect(results.length).to.equal(2)
let i = 0
expect(results[i].kind).to.equal('label')
i++
expect(results[i].kind).to.equal('branch')
expect((results[i] as any).branch).to.equal(otherBranch)
})
})
| |
Add more test for 10426 | /// <reference path="../fourslash.ts"/>
// @allowNonTsExtensions: true
// @Filename: a.js
//// /**
//// * Modify the parameter
//// * @param {string} p1
//// */
//// var foo = function (p1) { }
//// module.exports.foo = foo;
//// fo/*1*/
// @Filename: b.ts
//// import a = require("./a");
//// a.fo/*2*/
goTo.marker('1');
verify.completionEntryDetailIs("foo", "var foo: (p1: string) => void", "Modify the parameter");
goTo.marker('2');
verify.completionEntryDetailIs("foo", "(property) a.foo: (p1: string) => void", "Modify the parameter");
| |
Update conflict marker formatting test. We now no longer format the second branch of hte merge. | /// <reference path='fourslash.ts' />
////class C {
////<<<<<<< HEAD
//// v = 1;
////=======
////v = 2;
////>>>>>>> Branch - a
////}
format.document();
verify.currentFileContentIs("class C {\r\n\
<<<<<<< HEAD\r\n\
v = 1;\r\n\
=======\r\n\
v = 2;\r\n\
>>>>>>> Branch - a\r\n\
}"); | /// <reference path='fourslash.ts' />
////class C {
////<<<<<<< HEAD
////v = 1;
////=======
////v = 2;
////>>>>>>> Branch - a
////}
format.document();
verify.currentFileContentIs("class C {\r\n\
<<<<<<< HEAD\r\n\
v = 1;\r\n\
=======\r\n\
v = 2;\r\n\
>>>>>>> Branch - a\r\n\
}"); |
Update NodeDOMTreeConstruction to match arg signature of `insertHTMLBefore`. | import * as SimpleDOM from 'simple-dom';
import { DOMTreeConstruction, Bounds, Simple, ConcreteBounds } from '@glimmer/runtime';
export default class NodeDOMTreeConstruction extends DOMTreeConstruction {
protected document: SimpleDOM.Document;
constructor(doc: Simple.Document) {
super(doc);
}
// override to prevent usage of `this.document` until after the constructor
protected setupUselessElement() { }
insertHTMLBefore(parent: Simple.Element, html: string, reference: Simple.Node): Bounds {
let prev = reference ? reference.previousSibling : parent.lastChild;
let raw = this.document.createRawHTMLSection(html);
parent.insertBefore(raw, reference);
let first = prev ? prev.nextSibling : parent.firstChild;
let last = reference ? reference.previousSibling : parent.lastChild;
return new ConcreteBounds(parent, first, last);
}
// override to avoid SVG detection/work when in node (this is not needed in SSR)
createElement(tag: string) {
return this.document.createElement(tag);
}
// override to avoid namespace shenanigans when in node (this is not needed in SSR)
setAttribute(element: Element, name: string, value: string) {
element.setAttribute(name, value);
}
}
| import * as SimpleDOM from 'simple-dom';
import { DOMTreeConstruction, Bounds, Simple, ConcreteBounds } from '@glimmer/runtime';
export default class NodeDOMTreeConstruction extends DOMTreeConstruction {
protected document: SimpleDOM.Document;
constructor(doc: Simple.Document) {
super(doc);
}
// override to prevent usage of `this.document` until after the constructor
protected setupUselessElement() { }
insertHTMLBefore(parent: Simple.Element, reference: Simple.Node, html: string): Bounds {
let prev = reference ? reference.previousSibling : parent.lastChild;
let raw = this.document.createRawHTMLSection(html);
parent.insertBefore(raw, reference);
let first = prev ? prev.nextSibling : parent.firstChild;
let last = reference ? reference.previousSibling : parent.lastChild;
return new ConcreteBounds(parent, first, last);
}
// override to avoid SVG detection/work when in node (this is not needed in SSR)
createElement(tag: string) {
return this.document.createElement(tag);
}
// override to avoid namespace shenanigans when in node (this is not needed in SSR)
setAttribute(element: Element, name: string, value: string) {
element.setAttribute(name, value);
}
}
|
Add unit test for commans component | /// <reference path="./../../../typings/index.d.ts" />
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { CommandsComponent } from './commands.component';
let comp: CommandsComponent;
let fixture: ComponentFixture<CommandsComponent>;
let el: DebugElement;
describe('CommandsComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ CommandsComponent ]
});
fixture = TestBed.createComponent(CommandsComponent);
comp = fixture.componentInstance;
el = fixture.debugElement.query(By.css('div'));
});
it('should display "What can I do?"', () => {
expect(el.nativeElement.textContent).toContain('What can I do?');
});
});
| |
Add ProductService, which contains all logic for formatting products from the Drupal database. | import { Injectable } from '@angular/core';
import {Subject} from "rxjs/Rx";
import 'marked';
import * as marked from 'marked';
import {DrupalService} from "./app.drupal.service";
@Injectable()
export class ProductService {
private taxonomyTerms;
constructor(private drupalService:DrupalService)
{
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
this.loadTaxonomies();
}
isEducation(product)
{
return product.type == "education";
}
isService(product)
{
return product.type == "service";
}
loadTaxonomies()
{
this.drupalService.getAllTaxonomies().subscribe(
data => {
this.taxonomyTerms = data;
}
);
}
getFormattedArrayField(arrayField)
{
let formatted = "";
for(let i = 0; i < arrayField.length; i++)
{
formatted += arrayField[0];
if((i + 1) < arrayField.length)
formatted += ", "
}
return formatted;
}
getTermNames(terms)
{
let termNames = "";
if(this.taxonomyTerms) {
for(let i = 0; i < terms.length; i++)
{
termNames += this.getTermName(terms[i]);
if((i + 1) < terms.length)
termNames += ", "
}
}
return termNames;
}
getTermName(term)
{
if(this.taxonomyTerms) {
return this.taxonomyTerms[term.id].name;
}
return "";
}
getBodyHtml(product)
{
return marked(product.body.value);
}
getLogoUrl(product)
{
if(product.field_logo && product.field_logo.alt)
return "https://researchit.cer.auckland.ac.nz:8080/sites/default/files/" + product.field_logo.alt;
return "assets/service.png";
}
}
| |
Move oauth-callback to its own folder | import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AuthService } from '../shared/auth.service';
import { SessionService } from '../shared/session.service';
import { Paths } from '../shared/paths';
/* Component for handling OAuth callback routes */
@Component({
selector: 'auth-callback',
template: '',
})
export class OAuthCallbackComponent implements OnInit, OnDestroy {
param_sub: any;
constructor(
private route: ActivatedRoute,
private sessionService: SessionService,
private authService: AuthService,
) { }
/* Takes a route, provided by the routing module which requires an oauth token
* as a route parameter. This then fires the auth service, prompting a request
* for an API key from the Alveo server. Once the session service is ready,
* the sessionService will navigate the user to the last stored route, if one
* is available. Else it will redirect them to the most relevant place to be.
*/
ngOnInit() {
this.param_sub = this.route.queryParams.subscribe(params => {
if (params['code'] !== undefined) {
this.authService.login(params['code']).then(
() => {
this.sessionService.onReady().then(
() => {
this.sessionService.navigateToStoredRoute();
}
);
}
);
}
});
}
ngOnDestroy() {
this.param_sub.unsubscribe();
}
}
| |
Comment out (now) unused variable | import Logger from './logger';
let alreadyWarned = false;
export function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || "assertion failure");
}
}
export function prodAssert() {}
export default debugAssert;
| import Logger from './logger';
// let alreadyWarned = false;
export function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || "assertion failure");
}
}
export function prodAssert() {}
export default debugAssert;
|
Fix the example dangerfile to not crash if no JSON files are in the PR | // This dangerfile is for running as an integration test on CI
import { DangerDSLType } from "../../../dsl/DangerDSL"
declare var danger: DangerDSLType
declare function markdown(params: string): void
const showArray = (array: any[], mapFunc?: (any) => any) => {
const defaultMap = (a: any) => a
const mapper = mapFunc || defaultMap
return `\n - ${array.map(mapper).join("\n - ")}\n`
}
const git = danger.git
const goAsync = async () => {
const firstFileDiff = await git.diffForFile(git.modified_files[0])
const firstJSONFile = git.modified_files.find(f => f.endsWith("json"))
const jsonDiff = firstJSONFile && (await git.JSONDiffForFile(firstJSONFile))
markdown(`
created: ${showArray(git.created_files)}
modified: ${showArray(git.modified_files)}
deleted: ${showArray(git.deleted_files)}
commits: ${git.commits.length}
messages: ${showArray(git.commits, c => c.message)}
diffForFile keys:${showArray(Object.keys(firstFileDiff))}
jsonDiff keys:${showArray(Object.keys(jsonDiff))}
`)
}
goAsync()
| // This dangerfile is for running as an integration test on CI
import { DangerDSLType } from "../../../dsl/DangerDSL"
declare var danger: DangerDSLType
declare function markdown(params: string): void
const showArray = (array: any[], mapFunc?: (any) => any) => {
const defaultMap = (a: any) => a
const mapper = mapFunc || defaultMap
return `\n - ${array.map(mapper).join("\n - ")}\n`
}
const git = danger.git
const goAsync = async () => {
const firstFileDiff = await git.diffForFile(git.modified_files[0])
const firstJSONFile = git.modified_files.find(f => f.endsWith("json"))
const jsonDiff = firstJSONFile && (await git.JSONDiffForFile(firstJSONFile))
const jsonDiffKeys = jsonDiff && showArray(Object.keys(jsonDiff))
markdown(`
created: ${showArray(git.created_files)}
modified: ${showArray(git.modified_files)}
deleted: ${showArray(git.deleted_files)}
commits: ${git.commits.length}
messages: ${showArray(git.commits, c => c.message)}
diffForFile keys:${showArray(Object.keys(firstFileDiff))}
jsonDiff keys:${jsonDiffKeys || "no JSON files in the diff"}
`)
}
goAsync()
|
Add tests for BaseContext as well as Context | import Koa = require("koa");
declare module 'koa' {
export interface Context {
db(): void;
}
}
const app = new Koa();
app.context.db = () => {};
app.use(async ctx => {
console.log(ctx.db);
});
app.use((ctx, next) => {
const start: any = new Date();
return next().then(() => {
const end: any = new Date();
const ms = end - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
ctx.assert(true, 404, "Yep!");
});
});
// response
app.use(ctx => {
ctx.body = "Hello World";
ctx.body = ctx.URL.toString();
});
app.listen(3000);
const server = app.listen();
| import Koa = require("koa");
declare module 'koa' {
export interface BaseContext {
db(): void;
}
export interface Context {
user: {};
}
}
const app = new Koa();
app.context.db = () => {};
app.use(async ctx => {
console.log(ctx.db);
ctx.user = {};
});
app.use((ctx, next) => {
const start: any = new Date();
return next().then(() => {
const end: any = new Date();
const ms = end - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
ctx.assert(true, 404, "Yep!");
});
});
// response
app.use(ctx => {
ctx.body = "Hello World";
ctx.body = ctx.URL.toString();
});
app.listen(3000);
const server = app.listen();
|
Revert "Alphasort ci-source providers for easier additions" | import { BuddyBuild } from "./BuddyBuild"
import { Buildkite } from "./Buildkite"
import { Circle } from "./Circle"
import { Codeship } from "./Codeship"
import { DockerCloud } from "./DockerCloud"
import { Drone } from "./Drone"
import { FakeCI } from "./Fake"
import { Jenkins } from "./Jenkins"
import { Nevercode } from "./Nevercode"
import { Semaphore } from "./Semaphore"
import { Surf } from "./Surf"
import { Travis } from "./Travis"
import { VSTS } from "./VSTS"
const providers = [
BuddyBuild,
Buildkite,
Circle,
Codeship,
DockerCloud,
Drone,
FakeCI,
Jenkins,
Nevercode,
Semaphore,
Surf,
Travis,
VSTS,
]
// Mainly used for Dangerfile linting
const realProviders = [
BuddyBuild,
Buildkite,
Circle,
Codeship,
DockerCloud,
Drone,
Jenkins,
Nevercode,
Semaphore,
Surf,
Travis,
VSTS,
]
export { providers, realProviders }
| import { BuddyBuild } from "./BuddyBuild"
import { Buildkite } from "./Buildkite"
import { Circle } from "./Circle"
import { Codeship } from "./Codeship"
import { DockerCloud } from "./DockerCloud"
import { Drone } from "./Drone"
import { FakeCI } from "./Fake"
import { Jenkins } from "./Jenkins"
import { Nevercode } from "./Nevercode"
import { Semaphore } from "./Semaphore"
import { Surf } from "./Surf"
import { Travis } from "./Travis"
import { VSTS } from "./VSTS"
const providers = [
Travis,
Circle,
Semaphore,
Nevercode,
Jenkins,
FakeCI,
Surf,
DockerCloud,
Codeship,
Drone,
Buildkite,
BuddyBuild,
VSTS,
]
// Mainly used for Dangerfile linting
const realProviders = [
Travis,
Circle,
Semaphore,
Nevercode,
Jenkins,
Surf,
DockerCloud,
Codeship,
Drone,
Buildkite,
BuddyBuild,
VSTS,
]
export { providers, realProviders }
|
Bring back redirecting dev.w3.org to drafts.csswg.org and so on. | 'use strict'; // XXX
import { Url } from 'url';
import { RedirectInfo, ExtendedRedirectInfo } from '../';
//
// Entry Point
//
export function rewrite(url: Url): ExtendedRedirectInfo {
const host = '.w3.org';
if (('.' + url.host).endsWith(host)) {
if (url.protocol === 'http:') {
const reason = 'Prefer https: over http:';
const redirectInfo: RedirectInfo = {
protocol: 'https:',
};
return {
type: 'rewrite',
reason: reason,
redirectInfo: redirectInfo,
};
}
}
return null;
}
| 'use strict'; // XXX
import { Url } from 'url';
import { RedirectInfo, ExtendedRedirectInfo } from '../';
//
// dev.w3.org
//
const REDIRECT_MAP: Map<string, string> = new Map([
['/csswg/', 'drafts.csswg.org'],
['/fxtf/', 'drafts.fxtf.org'],
['/houdini/', 'drafts.css-houdini.org'],
]);
function rewriteDevW3Org(url: Url): ExtendedRedirectInfo {
const pathname = url.pathname;
for (const pair of REDIRECT_MAP) {
const knownPathname = pair[0];
const host = pair[1];
if (pathname.startsWith(knownPathname)) {
const newPathname = pathname.substring(knownPathname.length - 1);
const reason = 'dev.w3.org has retired';
const redirectInfo: RedirectInfo = {
protocol: 'https:',
host: host,
pathname: newPathname,
}
return {
type: 'rewrite',
reason: reason,
redirectInfo: redirectInfo,
};
}
}
return null;
}
//
// Entry Point
//
export function rewrite(url: Url): ExtendedRedirectInfo {
if (url.host === 'dev.w3.org') {
return rewriteDevW3Org(url);
}
return null;
}
|
Add spacing to table float | // Example of how you would create a table with float positions
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import {
Document,
OverlapType,
Packer,
Paragraph,
RelativeHorizontalPosition,
RelativeVerticalPosition,
Table,
TableAnchorType,
TableCell,
TableLayoutType,
TableRow,
WidthType,
} from "../build";
const doc = new Document();
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Hello")],
columnSpan: 2,
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
],
float: {
horizontalAnchor: TableAnchorType.MARGIN,
verticalAnchor: TableAnchorType.MARGIN,
relativeHorizontalPosition: RelativeHorizontalPosition.RIGHT,
relativeVerticalPosition: RelativeVerticalPosition.BOTTOM,
overlap: OverlapType.NEVER,
},
width: {
size: 4535,
type: WidthType.DXA,
},
layout: TableLayoutType.FIXED,
});
doc.addSection({
children: [table],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
| // Example of how you would create a table with float positions
// Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs";
import {
Document,
OverlapType,
Packer,
Paragraph,
RelativeHorizontalPosition,
RelativeVerticalPosition,
Table,
TableAnchorType,
TableCell,
TableLayoutType,
TableRow,
WidthType,
} from "../build";
const doc = new Document();
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Hello")],
columnSpan: 2,
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
],
float: {
horizontalAnchor: TableAnchorType.MARGIN,
verticalAnchor: TableAnchorType.MARGIN,
relativeHorizontalPosition: RelativeHorizontalPosition.RIGHT,
relativeVerticalPosition: RelativeVerticalPosition.BOTTOM,
overlap: OverlapType.NEVER,
leftFromText: 1000,
rightFromText: 2000,
topFromText: 1500,
bottomFromText: 30,
},
width: {
size: 4535,
type: WidthType.DXA,
},
layout: TableLayoutType.FIXED,
});
doc.addSection({
children: [table],
});
Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer);
});
|
Fix white flash when navigating to /settings | import React from 'react';
import { Outlet, useMatch } from 'react-router';
import { Navigate } from 'react-router-dom';
import * as Nav from '../../elements/Nav/Nav';
import appStyles from '../../App.module.css';
import styles from './Settings.module.css';
const Settings: React.FC = () => {
const match = useMatch('/settings');
if (match) {
return <Navigate to='/settings/library' />;
}
return (
<div className={`${appStyles.view} ${styles.viewSettings}`}>
<div className={styles.settings__nav}>
<Nav.Wrap vertical>
<Nav.Link to='/settings/library'>Library</Nav.Link>
<Nav.Link to='/settings/audio'>Audio</Nav.Link>
<Nav.Link to='/settings/interface'>Interface</Nav.Link>
<Nav.Link to='/settings/about'>About</Nav.Link>
</Nav.Wrap>
</div>
<div className={styles.settings__content}>
<Outlet />
</div>
</div>
);
};
export default Settings;
| import React from 'react';
import { Outlet, useMatch } from 'react-router';
import { Navigate } from 'react-router-dom';
import * as Nav from '../../elements/Nav/Nav';
import appStyles from '../../App.module.css';
import styles from './Settings.module.css';
const Settings: React.FC = () => {
const match = useMatch('/settings');
return (
<div className={`${appStyles.view} ${styles.viewSettings}`}>
<div className={styles.settings__nav}>
<Nav.Wrap vertical>
<Nav.Link to='/settings/library'>Library</Nav.Link>
<Nav.Link to='/settings/audio'>Audio</Nav.Link>
<Nav.Link to='/settings/interface'>Interface</Nav.Link>
<Nav.Link to='/settings/about'>About</Nav.Link>
</Nav.Wrap>
</div>
<div className={styles.settings__content}>
<Outlet />
</div>
{match && <Navigate to='/settings/library' />}
</div>
);
};
export default Settings;
|
Use version abbrevation for a language's default version. | import Language from '../models/language';
import Version from '../models/version';
import * as mongoose from 'mongoose';
import { log } from '../helpers/logger';
import { readFileSync } from 'fs';
const connect = () => {
mongoose.connect('mongodb://localhost:27017/db', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {
return log('info', 0, 'connected to db');
}).catch((err) => {
log('err', 0, `error connecting to database: ${err}`);
return process.exit(1);
});
};
connect();
mongoose.connection.on('disconnected', connect);
const importLanguages = () => {
const _default = JSON.parse(readFileSync(`${__dirname}/../../../i18n/default/default.json`, 'utf-8'));
const def = new Language({
name: 'Default',
objectName: 'default',
rawObject: _default,
defaultVersion: Version.find({ abbv: 'RSV' }).exec()
});
def.save((err, language) => {
if (err) {
log('err', 0, `unable to save ${def['name']}`);
log('err', 0, err);
} else {
log('info', 0, `saved ${language.name}`);
}
});
};
importLanguages(); | import Language from '../models/language';
import Version from '../models/version';
import * as mongoose from 'mongoose';
import { log } from '../helpers/logger';
import { readFileSync } from 'fs';
const connect = () => {
mongoose.connect('mongodb://localhost:27017/db', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {
return log('info', 0, 'connected to db');
}).catch((err) => {
log('err', 0, `error connecting to database: ${err}`);
return process.exit(1);
});
};
connect();
mongoose.connection.on('disconnected', connect);
const defaultVersion = 'RSV';
const importLanguages = () => {
const _default = JSON.parse(readFileSync(`${__dirname}/../../../i18n/default/default.json`, 'utf-8'));
const def = new Language({
name: 'Default',
objectName: 'default',
rawObject: _default,
defaultVersion
});
def.save((err, language) => {
if (err) {
log('err', 0, `unable to save ${def['name']}`);
log('err', 0, err);
} else {
log('info', 0, `saved ${language.name}`);
}
});
};
importLanguages(); |
Add pageName default to avoid "Loading undefined..." | import React, { FC } from 'react';
interface Props {
pageName?: string;
}
const PageLoader: FC<Props> = ({ pageName }) => {
const loadingText = `Loading ${pageName}...`;
return (
<div className="page-loader-wrapper">
<i className="page-loader-wrapper__spinner fa fa-spinner fa-spin" />
<div className="page-loader-wrapper__text">{loadingText}</div>
</div>
);
};
export default PageLoader;
| import React, { FC } from 'react';
interface Props {
pageName?: string;
}
const PageLoader: FC<Props> = ({ pageName = '' }) => {
const loadingText = `Loading ${pageName}...`;
return (
<div className="page-loader-wrapper">
<i className="page-loader-wrapper__spinner fa fa-spinner fa-spin" />
<div className="page-loader-wrapper__text">{loadingText}</div>
</div>
);
};
export default PageLoader;
|
Add stub table for members | import * as React from 'react';
import { RouteComponentProps } from '@reach/router';
import { Title } from '../../../components/title/index';
export const Members = (props: RouteComponentProps) => (
<Title>Members list</Title>
);
| import * as React from 'react';
import { RouteComponentProps } from '@reach/router';
import { Title } from '../../../components/title/index';
export const Members = (props: RouteComponentProps) => (
<>
<Title>Members list</Title>
<table>
<thead>
<tr>
<th>Nome</th>
<th>Stato</th>
<th>Scadenza</th>
<th />
</tr>
</thead>
<tbody>
<tr>
<td>Patrick Arminio</td>
<td>Attivo</td>
<td>20 aprile 2019</td>
</tr>
</tbody>
</table>
</>
);
|
Truncate requester names to 40 characters. | import { Hit, Requester } from '../types';
import { generateBadges } from './badges';
import { truncate } from './formatting';
type ExceptionStatus = 'neutral' | 'warning' | 'critical';
export interface ExceptionDescriptor {
status?: ExceptionStatus;
title?: string;
description?: string;
}
const generateExceptions = (groupId: string): ExceptionDescriptor[] => {
return groupId.startsWith('[Error:groupId]-')
? [ { status: 'warning', title: 'You are not qualified.' } ]
: [];
};
export const generateItemProps = (hit: Hit, requester: Requester | undefined) => {
const { requesterName, groupId, title } = hit;
const actions = [
// {
// icon: 'view',
// external: true,
// url: `https://www.mturk.com/mturk/preview?groupId=${groupId}`
// },
{
primary: true,
external: true,
content: 'Accept',
accessibilityLabel: 'Accept',
icon: 'add',
url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}`
}
];
return {
attributeOne: requesterName,
attributeTwo: truncate(title, 80),
badges: generateBadges(requester),
actions,
exceptions: generateExceptions(groupId)
};
};
| import { Hit, Requester } from '../types';
import { generateBadges } from './badges';
import { truncate } from './formatting';
type ExceptionStatus = 'neutral' | 'warning' | 'critical';
export interface ExceptionDescriptor {
status?: ExceptionStatus;
title?: string;
description?: string;
}
const generateExceptions = (groupId: string): ExceptionDescriptor[] => {
return groupId.startsWith('[Error:groupId]-')
? [ { status: 'warning', title: 'You are not qualified.' } ]
: [];
};
export const generateItemProps = (hit: Hit, requester: Requester | undefined) => {
const { requesterName, groupId, title } = hit;
const actions = [
// {
// icon: 'view',
// external: true,
// url: `https://www.mturk.com/mturk/preview?groupId=${groupId}`
// },
{
primary: true,
external: true,
content: 'Accept',
accessibilityLabel: 'Accept',
icon: 'add',
url: `https://www.mturk.com/mturk/previewandaccept?groupId=${groupId}`
}
];
return {
attributeOne: truncate(requesterName, 40),
attributeTwo: truncate(title, 80),
badges: generateBadges(requester),
actions,
exceptions: generateExceptions(groupId)
};
};
|
Fix TypeScript compilation error in BreadcrumbsService. | export default class BreadcrumbsService {
constructor() {
this._handlers = [];
this._items = [];
this._activeItem = '';
}
listen(handler) {
this._handlers.push(handler);
return () => {
this._handlers.splice(this._handlers.indexOf(handler), 1);
};
}
_notify() {
this._handlers.forEach(handler => handler());
}
get items() {
return this._items;
}
set items(items) {
this._items = items;
this._notify();
}
get activeItem() {
return this._activeItem;
}
set activeItem(item) {
this._activeItem = item;
this._notify();
}
}
| export default class BreadcrumbsService {
private _handlers = [];
private _items = [];
private _activeItem = '';
listen(handler) {
this._handlers.push(handler);
return () => {
this._handlers.splice(this._handlers.indexOf(handler), 1);
};
}
_notify() {
this._handlers.forEach(handler => handler());
}
get items() {
return this._items;
}
set items(items) {
this._items = items;
this._notify();
}
get activeItem() {
return this._activeItem;
}
set activeItem(item) {
this._activeItem = item;
this._notify();
}
}
|
Add just a bit more context to the prop name | import * as React from 'react'
import { ButtonGroup } from '../lib/button-group'
import { Button } from '../lib/button'
import { Ref } from '../lib/ref'
import { Octicon, OcticonSymbol } from '../octicons'
import { Branch } from '../../models/branch'
interface INewCommitsBannerProps {
/**
* The number of commits behind `branch`
*/
readonly commitsBehind: number
/**
* The target branch that will accept commits
* from the current branch
*/
readonly baseBranch: Branch
readonly onCompareClicked: () => void
readonly onMergeClicked: () => void
}
/**
* Banner used to notify user that there branch is _commitsBehind_
* commits behind `branch`
*/
export class NewCommitsBanner extends React.Component<
INewCommitsBannerProps,
{}
> {
public render() {
return (
<div className="notification-banner diverge-banner">
<div className="notification-banner-content">
<p>
Your branch is <strong>{this.props.commitsBehind} commits</strong>{' '}
behind <Ref>{this.props.baseBranch.name}</Ref>
</p>
<a className="close" aria-label="Dismiss banner">
<Octicon symbol={OcticonSymbol.x} />
</a>
</div>
<ButtonGroup>
<Button type="submit" onClick={this.props.onCompareClicked}>
Compare
</Button>
<Button onClick={this.props.onMergeClicked}>Merge...</Button>
</ButtonGroup>
</div>
)
}
}
| import * as React from 'react'
import { ButtonGroup } from '../lib/button-group'
import { Button } from '../lib/button'
import { Ref } from '../lib/ref'
import { Octicon, OcticonSymbol } from '../octicons'
import { Branch } from '../../models/branch'
interface INewCommitsBannerProps {
/**
* The number of commits behind `branch`
*/
readonly commitsBehindBaseBranch: number
/**
* The target branch that will accept commits
* from the current branch
*/
readonly baseBranch: Branch
readonly onCompareClicked: () => void
readonly onMergeClicked: () => void
}
/**
* Banner used to notify user that there branch is _commitsBehind_
* commits behind `branch`
*/
export class NewCommitsBanner extends React.Component<
INewCommitsBannerProps,
{}
> {
public render() {
return (
<div className="notification-banner diverge-banner">
<div className="notification-banner-content">
<p>
Your branch is <strong>{this.props.commitsBehindBaseBranch} commits</strong>{' '}
behind <Ref>{this.props.baseBranch.name}</Ref>
</p>
<a className="close" aria-label="Dismiss banner">
<Octicon symbol={OcticonSymbol.x} />
</a>
</div>
<ButtonGroup>
<Button type="submit" onClick={this.props.onCompareClicked}>
Compare
</Button>
<Button onClick={this.props.onMergeClicked}>Merge...</Button>
</ButtonGroup>
</div>
)
}
}
|
Change Card component to cool ui | import * as React from 'react';
interface Props {
userName: string;
text: string;
channelName: string;
}
export default class Post extends React.Component < any, any > {
constructor(props) {
super(props);
this.props = props;
}
render() {
return <div style={{ margin: '20px', border: '5px solid' }}>{this.props.text}</div>;
}
}
| import * as React from 'react';
import Card from 'material-ui/Card';
import { withStyles } from 'material-ui/styles';
interface Props {
userName: string;
text: string;
channelName: string;
}
const styles = theme => ({
card: {
minWidth: 275,
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
marginBottom: 16,
fontSize: 14,
color: theme.palette.text.secondary,
},
pos: {
marginBottom: 12,
color: theme.palette.text.secondary,
},
});
class Post extends React.Component < any, any > {
constructor(props) {
super(props);
this.props = props;
}
render() {
return (
<div style={{ margin: '20px' }}>
<Card>
{this.props.text}
</Card>
</div>
);
}
}
export default withStyles(styles)(Post);
|
Add ability to select a particular avd for $appbuilder emulate android | ///<reference path="../.d.ts"/>
import path = require("path");
import helpers = require("./../common/helpers");
var knownOpts:any = {
"log" : String,
"verbose" : Boolean,
"path" : String,
"version": Boolean,
"help": Boolean,
"json": Boolean,
"watch": Boolean
},
shorthands = {
"v" : "verbose",
"p" : "path"
};
var parsed = helpers.getParsedOptions(knownOpts, shorthands);
Object.keys(parsed).forEach((opt) => exports[opt] = parsed[opt]);
exports.knownOpts = knownOpts;
declare var exports:any;
export = exports; | ///<reference path="../.d.ts"/>
"use strict";
import path = require("path");
import helpers = require("./../common/helpers");
var knownOpts:any = {
"log" : String,
"verbose" : Boolean,
"path" : String,
"version": Boolean,
"help": Boolean,
"json": Boolean,
"watch": Boolean,
"avd": String
},
shorthands = {
"v" : "verbose",
"p" : "path"
};
var parsed = helpers.getParsedOptions(knownOpts, shorthands);
Object.keys(parsed).forEach((opt) => exports[opt] = parsed[opt]);
exports.knownOpts = knownOpts;
declare var exports:any;
export = exports; |
Fix host attribute not assigned | import { Directive, Input, OnInit, Optional } from '@angular/core';
import { DialogRef } from './dialog-ref';
let uniqueId = 0;
@Directive({
selector: '[gdDialogTitle]',
host: {
'class': 'DialogTitle',
},
})
export class DialogTitleDirective implements OnInit {
@Input() id = `gd-dialog-title-${uniqueId++}`;
constructor(@Optional() private dialogRef: DialogRef<any>) {
}
ngOnInit(): void {
if (this.dialogRef && this.dialogRef.componentInstance) {
Promise.resolve().then(() => {
const container = this.dialogRef._containerInstance;
if (container && !container._ariaLabelledBy) {
container._ariaLabelledBy = this.id;
}
});
}
}
}
| import { Directive, Input, OnInit, Optional } from '@angular/core';
import { DialogRef } from './dialog-ref';
let uniqueId = 0;
@Directive({
selector: '[gdDialogTitle]',
host: {
'class': 'DialogTitle',
'[id]': 'id',
},
})
export class DialogTitleDirective implements OnInit {
@Input() id = `gd-dialog-title-${uniqueId++}`;
constructor(@Optional() private dialogRef: DialogRef<any>) {
}
ngOnInit(): void {
if (this.dialogRef && this.dialogRef.componentInstance) {
Promise.resolve().then(() => {
const container = this.dialogRef._containerInstance;
if (container && !container._ariaLabelledBy) {
container._ariaLabelledBy = this.id;
}
});
}
}
}
|
Add inline prop for money component | import Typography, { TypographyProps } from "@material-ui/core/Typography";
import * as React from "react";
import { LocaleConsumer } from "../Locale";
export interface MoneyProp {
amount: number;
currency: string;
}
interface MoneyProps {
moneyDetalis: MoneyProp;
typographyProps?: TypographyProps;
}
export const Money: React.StatelessComponent<MoneyProps> = ({
moneyDetalis,
typographyProps
}) => (
<LocaleConsumer>
{locale => {
const money = moneyDetalis.amount.toLocaleString(locale, {
currency: moneyDetalis.currency,
style: "currency"
});
if (typographyProps) {
return <Typography {...typographyProps}>{money}</Typography>;
}
return <>{money}</>;
}}
</LocaleConsumer>
);
export default Money;
| import Typography, { TypographyProps } from "@material-ui/core/Typography";
import * as React from "react";
import { LocaleConsumer } from "../Locale";
export interface MoneyProp {
amount: number;
currency: string;
}
interface MoneyProps {
moneyDetalis: MoneyProp;
typographyProps?: TypographyProps;
inline?;
}
export const Money: React.StatelessComponent<MoneyProps> = ({
moneyDetalis,
typographyProps,
inline
}) => (
<LocaleConsumer>
{locale => {
const money = moneyDetalis.amount.toLocaleString(locale, {
currency: moneyDetalis.currency,
style: "currency"
});
if (typographyProps) {
return <Typography {...typographyProps}>{money}</Typography>;
}
if (inline) {
return <span>{money}</span>;
}
return <>{money}</>;
}}
</LocaleConsumer>
);
export default Money;
|
Add more known values so their names show up alongside call expressions | export default class KnownValues {
_knownValues: any = {};
_knownValuesMap = new Map();
constructor() {
Object.assign(this._knownValues, {
"String.prototype.slice": String.prototype.slice,
"String.prototype.substr": String.prototype.substr,
"String.prototype.replace": String.prototype.replace,
"String.prototype.trim": String.prototype.trim,
"Array.prototype.push": Array.prototype.push,
"Array.prototype.join": Array.prototype.join,
"JSON.parse": JSON.parse,
"Object.keys": Object.keys,
undefined: undefined,
null: null
});
var global = Function("return this")();
if (global["localStorage"]) {
Object.assign(this._knownValues, {
localStorage: global.localStorage,
"localStorage.getItem": global.localStorage.getItem
});
}
Object.keys(this._knownValues).forEach(key => {
this._knownValuesMap.set(this._knownValues[key], key);
});
}
getName(value) {
let knownValue = this._knownValuesMap.get(value);
if (!knownValue) {
knownValue = null;
}
return knownValue;
}
getValue(name: string) {
return this._knownValues[name];
}
}
| export default class KnownValues {
_knownValues: any = {};
_knownValuesMap = new Map();
constructor() {
Object.assign(this._knownValues, {
"String.prototype.slice": String.prototype.slice,
"String.prototype.substr": String.prototype.substr,
"String.prototype.replace": String.prototype.replace,
"String.prototype.trim": String.prototype.trim,
"Array.prototype.push": Array.prototype.push,
"Array.prototype.join": Array.prototype.join,
"JSON.parse": JSON.parse,
"Object.keys": Object.keys,
"Number.prototype.toString": Number.prototype.toString,
"Boolean.prototype.toString": Boolean.prototype.toString,
"Object.prototype.toString": Object.prototype.toString,
"String.prototype.toString": String.prototype.toString,
"Date.prototype.getMinutes": Date.prototype.getMinutes,
"Date.prototype.getHours": Date.prototype.getHours,
undefined: undefined,
null: null
});
var global = Function("return this")();
if (global["localStorage"]) {
Object.assign(this._knownValues, {
localStorage: global.localStorage,
"localStorage.getItem": global.localStorage.getItem
});
}
Object.keys(this._knownValues).forEach(key => {
this._knownValuesMap.set(this._knownValues[key], key);
});
}
getName(value) {
let knownValue = this._knownValuesMap.get(value);
if (!knownValue) {
knownValue = null;
}
return knownValue;
}
getValue(name: string) {
return this._knownValues[name];
}
}
|
Remove old version project migration support | import * as _ from 'lodash'
export default {
isMigratable: (project: ProjectScheme) => {
return false
},
migrate: (project: ProjectScheme) => {
return project
}
}
| import * as _ from 'lodash'
export default {
isMigratable: (project: any) => {
return false
},
migrate: (project: any) => {
return project
}
}
|
Return device id in device service | import winston from 'winston';
import DeviceModel from '@/models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(platform: string, mail: string, token: string) {
let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
platform,
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
await device.save();
}
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
return [];
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
| import winston from 'winston';
import DeviceModel from '@/models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(platform: string, mail: string, token: string): Promise<string> {
let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
platform,
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
const savedDevice = await device.save();
return savedDevice.id;
}
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
return [];
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
|
Change the export case to be more semantically correct | // Type definitions for gulp-jsonmin 1.1
// Project: https://github.com/englercj/gulp-jsonmin
// Definitions by: Romain Faust <https://github.com/romain-faust>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Transform } from 'stream';
declare function GulpJsonmin(options?: GulpJsonmin.Options): Transform;
declare namespace GulpJsonmin {
interface Options {
verbose?: boolean;
}
}
export = GulpJsonmin;
| // Type definitions for gulp-jsonmin 1.1
// Project: https://github.com/englercj/gulp-jsonmin
// Definitions by: Romain Faust <https://github.com/romain-faust>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Transform } from 'stream';
declare function gulpJsonmin(options?: gulpJsonmin.Options): Transform;
declare namespace gulpJsonmin {
interface Options {
verbose?: boolean;
}
}
export = gulpJsonmin;
|
Add sameSite attribute for cookies | export type Cookie = any;
export interface CookieGetOptions {
doNotParse?: boolean;
}
export interface CookieSetOptions {
path?: string;
expires?: Date;
maxAge?: number;
domain?: string;
secure?: boolean;
httpOnly?: boolean;
}
export interface CookieChangeOptions {
name: string;
value?: any,
options?: CookieSetOptions
}
export type CookieChangeListener = (options: CookieChangeOptions) => void; | export type Cookie = any;
export interface CookieGetOptions {
doNotParse?: boolean;
}
export interface CookieSetOptions {
path?: string;
expires?: Date;
maxAge?: number;
domain?: string;
secure?: boolean;
httpOnly?: boolean;
sameSite?: boolean | string;
}
export interface CookieChangeOptions {
name: string;
value?: any,
options?: CookieSetOptions
}
export type CookieChangeListener = (options: CookieChangeOptions) => void;
|
Add cache to prevent multiple server requests | import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../index';
@Injectable()
export class HttpService {
protected headers: Headers = new Headers();
constructor(private http: Http) {
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
get(url: string) {
return this.http.get(environment.endpoint + url, {headers: this.headers, withCredentials: true}).map(res => res.json())
}
post(url: string, object: any) {
return this.http.post(environment.endpoint + url, JSON.stringify(object), {headers: this.headers, withCredentials: true}).map(res => res.json());
}
}
| import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { environment } from '../index';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class HttpService {
protected headers: Headers = new Headers();
protected $observables: {[id: string]: Observable<any>} = {};
protected data: {[id: string]: Observable<any>} = {};
constructor(private http: Http) {
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
get(url: string) {
if (this.data.hasOwnProperty(url)) {
return Observable.of(this.data[url]);
} else if (this.$observables.hasOwnProperty(url)) {
return this.$observables[url];
} else {
this.$observables[url] = this.http.get(environment.endpoint + url, {
headers: this.headers,
withCredentials: true
})
.map(res => res.json())
.do(val => {
this.data[url] = val;
delete this.$observables[url];
})
// .catch(() => {
// delete this.data[url];
// delete this.$observables[url];
// })
.share();
return this.$observables[url];
}
}
post(url: string, object: any) {
return this.http.post(environment.endpoint + url, JSON.stringify(object), {
headers: this.headers,
withCredentials: true
}).map(res => res.json());
}
}
|
Add project in firestub test | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { RouterService } from './router.service';
import { Router } from '@angular/router';
import { AngularFireModule } from '@angular/fire';
describe('RouterService', () => {
let service: RouterService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AngularFireModule.initializeApp({})],
providers: [{ provide: Router, useValue: {} }],
});
service = TestBed.inject(RouterService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
| /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TestBed } from '@angular/core/testing';
import { RouterService } from './router.service';
import { Router } from '@angular/router';
import { AngularFireModule } from '@angular/fire';
describe('RouterService', () => {
let service: RouterService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AngularFireModule.initializeApp({ projectId: '' })],
providers: [{ provide: Router, useValue: {} }],
});
service = TestBed.inject(RouterService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
|
Make code somewhat more idiomatic. | "use strict";
import gLong = require('./gLong');
// default module: logging
function debug_var(e: any): string {
if (e === null) {
return '!';
}
if (e === void 0) {
return 'undef';
}
if (e.ref != null) {
return "*" + e.ref;
}
if (e instanceof gLong) {
return "" + e + "L";
}
return e;
}
// used for debugging the stack and local variables
export function debug_vars(arr: Array): string[] {
return arr.map(debug_var);
}
// log levels
// TODO: turn this into an enum, if possible
export var VTRACE = 10;
export var TRACE = 9;
export var DEBUG = 5;
export var ERROR = 1;
export var log_level = ERROR;
function log(level: number, msgs: any[]): void {
if (level <= log_level) {
var msg = msgs.join(' ');
if (level == 1) {
console.error(msg);
} else {
console.log(msg);
}
}
};
export function vtrace(...msgs: any[]): void {
log(VTRACE, msgs);
}
export function trace(...msgs: any[]): void {
log(TRACE, msgs);
}
export function debug(...msgs: any[]): void {
log(DEBUG, msgs);
}
export function error(...msgs: any[]): void {
log(ERROR, msgs);
}
| "use strict";
import gLong = require('./gLong');
// default module: logging
function debug_var(e: any): string {
if (e === null) {
return '!';
} else if (e === void 0) {
return 'undef';
} else if (e.ref != null) {
return "*" + e.ref;
} else if (e instanceof gLong) {
return e + "L";
}
return e;
}
// used for debugging the stack and local variables
export function debug_vars(arr: Array): string[] {
return arr.map(debug_var);
}
// log levels
// TODO: turn this into an enum, if possible
export var VTRACE = 10;
export var TRACE = 9;
export var DEBUG = 5;
export var ERROR = 1;
export var log_level = ERROR;
function log(level: number, msgs: any[]): void {
if (level <= log_level) {
var msg = msgs.join(' ');
if (level == 1) {
console.error(msg);
} else {
console.log(msg);
}
}
}
export function vtrace(...msgs: any[]): void {
log(VTRACE, msgs);
}
export function trace(...msgs: any[]): void {
log(TRACE, msgs);
}
export function debug(...msgs: any[]): void {
log(DEBUG, msgs);
}
export function error(...msgs: any[]): void {
log(ERROR, msgs);
}
|
Fix e2e tests for Uri | import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(6);
});
});
| import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(7);
});
});
|
Add reference to angular type definition | import { NG2_BOOLEAN_PIPES } from './boolean';
import { NG2_MATH_PIPES } from './math';
import { NG2_ARRAY_PIPES } from './array';
import { NG2_STRING_PIPES } from './string';
export * from './boolean';
export * from './math';
export * from './array';
export * from './string';
export const NG2_PIPES = [
...NG2_BOOLEAN_PIPES,
...NG2_MATH_PIPES,
...NG2_ARRAY_PIPES,
...NG2_STRING_PIPES
]; | /// <reference path="node_modules/angular2/typings/browser.d.ts" />
import { NG2_BOOLEAN_PIPES } from './boolean';
import { NG2_MATH_PIPES } from './math';
import { NG2_ARRAY_PIPES } from './array';
import { NG2_STRING_PIPES } from './string';
export * from './boolean';
export * from './math';
export * from './array';
export * from './string';
export const NG2_PIPES = [
...NG2_BOOLEAN_PIPES,
...NG2_MATH_PIPES,
...NG2_ARRAY_PIPES,
...NG2_STRING_PIPES
]; |
Add price case to util.ts test | import 'mocha'
import { expect } from 'chai'
import { parsePrice } from '../src/util'
describe('util functions', () => {
it('should parse price', () => {
const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
const result = testInput.map(val => parsePrice(val))
const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 5.5, 1256000, 1213.12, 0.25, 0.0025]
expect(result).to.eql(spected)
})
})
| import 'mocha'
import { expect } from 'chai'
import { parsePrice } from '../src/util'
describe('util functions', () => {
it('should parse price', () => {
const testInput = ['5', '25', '1.2', '1,2', '-12,25€', '-12,25 €', '144,50 € ', '$5.5', '1.256.000', '1,213.12', '.25', ',0025']
const result = testInput.map(val => parsePrice(val))
const spected = [5, 25, 1.2, 1.2, -12.25, -12.25, 144.50, 5.5, 1256000, 1213.12, 0.25, 0.0025]
expect(result).to.eql(spected)
})
})
|
Fix tabIndex not being set correctly | import { isSameDay, isSameMonth } from 'date-fns';
import { DayPickerProps, ModifiersStatus } from '../../../types';
export function createTabIndex(
day: Date,
modifiers: ModifiersStatus,
props: DayPickerProps
): number | undefined {
if (!modifiers.interactive) return;
let tabIndex: number;
if (props.focusedDay && isSameDay(day, props.focusedDay)) {
tabIndex = 0;
} else if (isSameDay(day, new Date())) {
tabIndex = 0;
} else if (
!isSameDay(day, new Date()) &&
!isSameMonth(day, new Date()) &&
day.getDate() === 1
) {
tabIndex = 0;
} else {
tabIndex = -1;
}
return tabIndex;
}
| import { isSameDay, isSameMonth } from 'date-fns';
import { DayPickerProps, ModifiersStatus } from '../../../types';
export function createTabIndex(
day: Date,
modifiers: ModifiersStatus,
props: DayPickerProps
): number | undefined {
let tabIndex: number;
if (props.focusedDay && isSameDay(day, props.focusedDay)) {
tabIndex = 0;
} else if (isSameMonth(day, props.month) && day.getDate() === 1) {
tabIndex = 0;
} else {
tabIndex = -1;
}
return tabIndex;
}
|
Fix ref forwarding in useRenderLink | import React from "react";
import {Link, useRouteMatch} from "react-router-dom";
import {ListItem, ListItemText} from "@material-ui/core";
export function useRenderLink(to: string) {
return React.useMemo(
() => React.forwardRef(itemProps => <Link to={to} {...itemProps} />),
[to],
);
}
interface ListItemLinkProps {
to: string
primary: string
}
export function ListItemLink({to, primary}: ListItemLinkProps) {
const match = useRouteMatch(to)?.isExact;
const renderLink = useRenderLink(to);
return (
<ListItem button component={renderLink} selected={match}>
<ListItemText primary={primary} />
</ListItem>
);
}
| import React from "react";
import {Link, useRouteMatch} from "react-router-dom";
import {ListItem, ListItemText} from "@material-ui/core";
export function useRenderLink(to: string) {
return React.useMemo(
() => React.forwardRef<HTMLAnchorElement, React.ComponentPropsWithoutRef<"a">>((props, ref) => (
<Link to={to} ref={ref} {...props} />)
), [to]
);
}
interface ListItemLinkProps {
to: string
primary: string
}
export function ListItemLink({to, primary}: ListItemLinkProps) {
const match = useRouteMatch(to)?.isExact;
const renderLink = useRenderLink(to);
return (
<ListItem button component={renderLink} selected={match}>
<ListItemText primary={primary} />
</ListItem>
);
}
|
Fix multi-progress reference to progress | // Type definitions for multi-progress 2.0
// Project: https://github.com/pitaj/multi-progress
// Definitions by: David Brett <https://github.com/DHBrett>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
import ProgressBar, { ProgressBarOptions } from '../progress';
import { Stream } from 'stream';
export default class MultiProgress {
/**
* Create a new @see MultiProgress with the given stream, or stderr by default
* @param stream A stream to write the progress bars to
*/
constructor(stream?: Stream)
/**
* Add a new bar
*/
newBar: (format: string, options: ProgressBarOptions) => ProgressBar;
/**
* Close all bars
*/
terminate: () => void;
/**
* Render the given progress bar
*/
move: (index: number) => void;
/**
* Move the bar indicated by index forward the number of steps indicated by value
*/
tick: (index: number, value: number, options?: any) => void;
/**
* Update the bar indicated by index to the value given
*/
update: (index: number, value: number, options?: any) => void;
}
| // Type definitions for multi-progress 2.0
// Project: https://github.com/pitaj/multi-progress
// Definitions by: David Brett <https://github.com/DHBrett>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
import ProgressBar, { ProgressBarOptions } from 'progress';
import { Stream } from 'stream';
export default class MultiProgress {
/**
* Create a new @see MultiProgress with the given stream, or stderr by default
* @param stream A stream to write the progress bars to
*/
constructor(stream?: Stream)
/**
* Add a new bar
*/
newBar: (format: string, options: ProgressBarOptions) => ProgressBar;
/**
* Close all bars
*/
terminate: () => void;
/**
* Render the given progress bar
*/
move: (index: number) => void;
/**
* Move the bar indicated by index forward the number of steps indicated by value
*/
tick: (index: number, value: number, options?: any) => void;
/**
* Update the bar indicated by index to the value given
*/
update: (index: number, value: number, options?: any) => void;
}
|
Disable chromatic for broken story | import React from 'react';
import Button from '../components/TsButton';
export default {
title: 'Addons/Controls',
component: Button,
argTypes: {
children: { control: 'text', name: 'Children' },
type: { control: 'text', name: 'Type' },
somethingElse: { control: 'object', name: 'Something Else' },
},
};
const Template = (args) => <Button {...args} />;
export const Basic = Template.bind({});
Basic.args = {
children: 'basic',
somethingElse: { a: 2 },
};
export const Action = Template.bind({});
Action.args = {
children: 'hmmm',
type: 'action',
somethingElse: { a: 4 },
};
export const CustomControls = Template.bind({});
CustomControls.argTypes = {
children: { table: { disable: true } },
type: { control: { disable: true } },
};
export const NoArgs = () => <Button>no args</Button>;
const hasCycle: any = {};
hasCycle.cycle = hasCycle;
export const CyclicArgs = Template.bind({});
CyclicArgs.args = {
hasCycle,
};
| import React from 'react';
import Button from '../components/TsButton';
export default {
title: 'Addons/Controls',
component: Button,
argTypes: {
children: { control: 'text', name: 'Children' },
type: { control: 'text', name: 'Type' },
somethingElse: { control: 'object', name: 'Something Else' },
},
};
const Template = (args) => <Button {...args} />;
export const Basic = Template.bind({});
Basic.args = {
children: 'basic',
somethingElse: { a: 2 },
};
export const Action = Template.bind({});
Action.args = {
children: 'hmmm',
type: 'action',
somethingElse: { a: 4 },
};
export const CustomControls = Template.bind({});
CustomControls.argTypes = {
children: { table: { disable: true } },
type: { control: { disable: true } },
};
export const NoArgs = () => <Button>no args</Button>;
const hasCycle: any = {};
hasCycle.cycle = hasCycle;
export const CyclicArgs = Template.bind({});
CyclicArgs.args = {
hasCycle,
};
CyclicArgs.parameters = {
chromatic: { disable: true },
};
|
Replace BrowserModule with CommonModule in calendar | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CalendarComponent } from './calendar.component';
@NgModule({
declarations: [CalendarComponent],
exports: [CalendarComponent],
imports: [BrowserModule, FormsModule]
})
export class CalendarModule { }
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CalendarComponent } from './calendar.component';
@NgModule({
declarations: [CalendarComponent],
exports: [CalendarComponent],
imports: [CommonModule, FormsModule]
})
export class CalendarModule { }
|
Add new methods to StreamBuilders | import { IStream } from "../../src/stream/stream.i";
export class StreamBuilder {
public build(): IStream {
return <IStream> {
writeLine: (message: string) => { }
};
}
}
| import { IStream } from "../../src/stream/stream.i";
export class StreamBuilder {
public build(): IStream {
return <IStream> {
writeLine: (message: string) => { },
write: (message: string) => { },
moveCursor: (x: number, y: number) => { },
cursorTo: (x: number, y: number) => { },
clearLine: () => { }
};
}
}
|
Correct expected promise type in fast-ratelimit test comments. | import { FastRateLimit } from 'fast-ratelimit';
const limit = new FastRateLimit({ // $type: FastRateLimit
threshold: 20,
ttl: 60,
});
const someNamespace = 'some-namespace';
const consume = limit.consume(someNamespace); // $type: Promise<any>
consume.then(() => {}); // User can send message.
consume.catch(() => {}); // Use cannot send message.
const hasToken = limit.hasToken(someNamespace); // $type: Promise<any>
consume.then(() => {}); // User has remaining token.
consume.catch(() => {}); // User does not have remaining token.
// Synchronously check if user is allowed to send message.
const consumeSync = limit.consumeSync(someNamespace); // $type: boolean
// Synchronously check if user has remaining token.
const hasTokenSync = limit.hasTokenSync(someNamespace); // $type: boolean | import { FastRateLimit } from 'fast-ratelimit';
const limit = new FastRateLimit({ // $type: FastRateLimit
threshold: 20,
ttl: 60,
});
const someNamespace = 'some-namespace';
const consume = limit.consume(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User can send message.
consume.catch(() => {}); // Use cannot send message.
const hasToken = limit.hasToken(someNamespace); // $type: Promise<void>
consume.then(() => {}); // User has remaining token.
consume.catch(() => {}); // User does not have remaining token.
// Synchronously check if user is allowed to send message.
const consumeSync = limit.consumeSync(someNamespace); // $type: boolean
// Synchronously check if user has remaining token.
const hasTokenSync = limit.hasTokenSync(someNamespace); // $type: boolean |
Add terminate process implemntation note | 'use strict';
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { join } from 'path';
const isWindows = process.platform === 'win32';
const isMacintosh = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
export function terminate(process: ChildProcess, cwd?: string): boolean {
if (isWindows) {
try {
// This we run in Atom execFileSync is available.
// Ignore stderr since this is otherwise piped to parent.stderr
// which might be already closed.
const options: any = {
stdio: ['pipe', 'pipe', 'ignore']
};
if (cwd) {
options.cwd = cwd;
}
cp.execFileSync(
'taskkill',
['/T', '/F', '/PID', process.pid.toString()],
options
);
return true;
} catch (err) {
return false;
}
} else if (isLinux || isMacintosh) {
try {
const cmd = join(__dirname, 'terminateProcess.sh');
const result = cp.spawnSync(cmd, [process.pid.toString()]);
return result.error ? false : true;
} catch (err) {
return false;
}
} else {
process.kill('SIGKILL');
return true;
}
}
| 'use strict';
import * as cp from 'child_process';
import ChildProcess = cp.ChildProcess;
import { join } from 'path';
const isWindows = process.platform === 'win32';
const isMacintosh = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
// this is very complex, but is basically copy-pased from VSCode implementation here:
// https://github.com/Microsoft/vscode-languageserver-node/blob/dbfd37e35953ad0ee14c4eeced8cfbc41697b47e/client/src/utils/processes.ts#L15
// And see discussion at
// https://github.com/rust-analyzer/rust-analyzer/pull/1079#issuecomment-478908109
export function terminate(process: ChildProcess, cwd?: string): boolean {
if (isWindows) {
try {
// This we run in Atom execFileSync is available.
// Ignore stderr since this is otherwise piped to parent.stderr
// which might be already closed.
const options: any = {
stdio: ['pipe', 'pipe', 'ignore']
};
if (cwd) {
options.cwd = cwd;
}
cp.execFileSync(
'taskkill',
['/T', '/F', '/PID', process.pid.toString()],
options
);
return true;
} catch (err) {
return false;
}
} else if (isLinux || isMacintosh) {
try {
const cmd = join(__dirname, 'terminateProcess.sh');
const result = cp.spawnSync(cmd, [process.pid.toString()]);
return result.error ? false : true;
} catch (err) {
return false;
}
} else {
process.kill('SIGKILL');
return true;
}
}
|
Create CSV export unit test | import { TestBed, inject } from '@angular/core/testing';
import { AnnotationExporterService } from './annotation-exporter.service';
describe('AnnotationExporterService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AnnotationExporterService]
});
});
it('should be created', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
expect(service).toBeTruthy();
}));
});
| import { TestBed, inject } from '@angular/core/testing';
import { Annotation } from './annotation';
import { AnnotationExporterService } from './annotation-exporter.service';
describe('AnnotationExporterService', () => {
function generateAnnotations(): Array<Annotation> {
let annotations = new Array<Annotation>();
for (let i=0; i<5; i++) {
annotations.push(new Annotation(i.toString(), 0, 0, 'Speaker', 'caption', "unittest"))
}
return annotations;
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AnnotationExporterService]
});
});
it('should be created', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
expect(service).toBeTruthy();
}));
it('should create a valid csv download', inject([AnnotationExporterService], (service: AnnotationExporterService) => {
const annotations = generateAnnotations();
let urlCreateObjectSpy = spyOn(URL, 'createObjectURL').and.callFake(
(blob) => {
expect(blob.type).toBe("text/csv");
let reader = new FileReader();
reader.onload = () => {
const csv = reader.result.split("\n");
expect(csv[0]).toBe('"id","start","end","speaker","caption","cap_type"');
for (const annotation in annotations) {
expect(csv[+annotation+1]).toBe("\"" + annotations[annotation].id + "\","
+ annotations[annotation].start.toString() + ","
+ annotations[annotation].end.toString() + ","
+ "\"" + annotations[annotation].speaker + "\","
+ "\"" + annotations[annotation].caption + "\","
+ "\"" + annotations[annotation].cap_type + "\""
);
}
}
reader.readAsText(blob);
}
);
// TODO filename?
let a = service.asCSV("test.csv", annotations);
}));
//JSON.parse
});
|
Adjust the test-file according to tslint | //
// PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string, clb: (error:Error) => void) that the extension
// host can call to run the tests. The test runner is expected to use console.log
// to report the results back to the caller. When the tests are finished, return
// a possible error to the callback or null if none.
import * as testRunner from "vscode/lib/testrunner";
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // colored output from test results
});
module.exports = testRunner; | /**
* PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
*
* This file is providing the test runner to use when running extension tests.
* By default the test runner in use is Mocha based.
*
* You can provide your own test runner if you want to override it by exporting
* a function run(testRoot: string, clb: (error:Error) => void) that the extension
* host can call to run the tests. The test runner is expected to use console.log
* to report the results back to the caller. When the tests are finished, return
* a possible error to the callback or null if none.
*/
import * as testRunner from "vscode/lib/testrunner";
// You can directly control Mocha options by uncommenting the following lines
// See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info
testRunner.configure({
ui: "tdd", // The TDD UI is being used in extension.test.ts (suite, test, etc.)
useColors: true // Colored output from test results
});
module.exports = testRunner; |
Fix hover state for return label (closes ARE-466) | import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { mixin as boxMixin } from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
const Container = styled(Link).attrs({
mr: 5,
py: 1,
px: 2,
})`
${boxMixin}
display: flex;
align-items: center;
justify-content: center;
background-color: ${p => p.theme.colors.background};
border-radius: ${p => p.theme.radii.regular};
`
const Label = styled(Text).attrs({
color: 'gray.medium',
})`
display: inline;
&:hover {
color: ${p => p.theme.colors.gray.bold};
}
`
interface AdvancedSearchReturnLabelProps {
label?: string
url?: string
}
export const AdvancedSearchReturnLabel: React.FC<AdvancedSearchReturnLabelProps> = ({
label = 'See all results',
url,
}) => {
return (
<Container to={url}>
<Label f={0} mr={4}>
⮐{' '}
</Label>
<Label f={1}>{label}</Label>
</Container>
)
}
export default AdvancedSearchReturnLabel
| import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import { mixin as boxMixin } from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
const Label = styled(Text).attrs({
color: 'gray.medium',
})`
display: inline;
`
const Container = styled(Link).attrs({
mr: 5,
py: 1,
px: 2,
})`
${boxMixin}
display: flex;
align-items: center;
justify-content: center;
background-color: ${p => p.theme.colors.background};
border-radius: ${p => p.theme.radii.regular};
&:hover ${Label} {
color: ${p => p.theme.colors.gray.bold};
}
`
interface AdvancedSearchReturnLabelProps {
label?: string
url?: string
}
export const AdvancedSearchReturnLabel: React.FC<AdvancedSearchReturnLabelProps> = ({
label = 'See all results',
url,
}) => {
return (
<Container to={url}>
<Label f={0} mr={4}>
⮐{' '}
</Label>
<Label f={1}>{label}</Label>
</Container>
)
}
export default AdvancedSearchReturnLabel
|
Make the prefix/namespaceURI of Element/Attr nullable | /**
* @public
*/
export type Node = {
nodeType: number;
};
/**
* @public
*/
export type Attr = Node & {
localName: string;
name: string;
namespaceURI: string;
nodeName: string;
prefix: string;
value: string;
};
/**
* @public
*/
export type CharacterData = Node & { data: string };
/**
* @public
*/
export type CDATASection = CharacterData;
/**
* @public
*/
export type Comment = CharacterData;
/**
* @public
*/
export type Document = Node & {
implementation: {
createDocument(namespaceURI: null, qualifiedNameStr: null, documentType: null): Document;
};
createAttributeNS(namespaceURI: string, name: string): Attr;
createCDATASection(contents: string): CDATASection;
createComment(data: string): Comment;
createElementNS(namespaceURI: string, qualifiedName: string): Element;
createProcessingInstruction(target: string, data: string): ProcessingInstruction;
createTextNode(data: string): Text;
};
/**
* @public
*/
export type Element = Node & {
localName: string;
namespaceURI: string;
nodeName: string;
prefix: string;
};
/**
* @public
*/
export type ProcessingInstruction = CharacterData & {
nodeName: string;
target: string;
};
/**
* @public
*/
export type Text = CharacterData;
| /**
* @public
*/
export type Node = {
nodeType: number;
};
/**
* @public
*/
export type Attr = Node & {
localName: string;
name: string;
namespaceURI: string | null;
nodeName: string;
prefix: string | null;
value: string;
};
/**
* @public
*/
export type CharacterData = Node & { data: string };
/**
* @public
*/
export type CDATASection = CharacterData;
/**
* @public
*/
export type Comment = CharacterData;
/**
* @public
*/
export type Document = Node & {
implementation: {
createDocument(namespaceURI: null, qualifiedNameStr: null, documentType: null): Document;
};
createAttributeNS(namespaceURI: string, name: string): Attr;
createCDATASection(contents: string): CDATASection;
createComment(data: string): Comment;
createElementNS(namespaceURI: string, qualifiedName: string): Element;
createProcessingInstruction(target: string, data: string): ProcessingInstruction;
createTextNode(data: string): Text;
};
/**
* @public
*/
export type Element = Node & {
localName: string;
namespaceURI: string | null;
nodeName: string;
prefix: string | null;
};
/**
* @public
*/
export type ProcessingInstruction = CharacterData & {
nodeName: string;
target: string;
};
/**
* @public
*/
export type Text = CharacterData;
|
Make use of es6 import | /// <reference path="jade.d.ts"/>
import jade = require('jade');
jade.compile("b")();
jade.compileFile("foo.jade", {})();
jade.compileClient("a")({ a: 1 });
jade.compileClientWithDependenciesTracked("test").body();
jade.render("h1",{});
jade.renderFile("foo.jade"); | /// <reference path="jade.d.ts"/>
import * as jade from 'jade';
jade.compile("b")();
jade.compileFile("foo.jade", {})();
jade.compileClient("a")({ a: 1 });
jade.compileClientWithDependenciesTracked("test").body();
jade.render("h1",{});
jade.renderFile("foo.jade");
|
Change default state to invisible | import { Injectable } from '@angular/core';
@Injectable()
export class ProgressBarService {
protected visible = true;
constructor() { }
setVisible() {
this.visible = true;
}
setHidden() {
this.visible = false;
}
}
| import { Injectable } from '@angular/core';
@Injectable()
export class ProgressBarService {
protected visible = false;
constructor() { }
setVisible() {
this.visible = true;
}
setHidden() {
this.visible = false;
}
}
|
Add empty line at eof | export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const imageUrl = getImageUrl(project, `${id}.jp2`, maxWidth, maxHeight, token);
const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
export const getImageUrl = (project: string, path: string, maxWidth: number,
maxHeight: number, token: string, format = 'jpg'): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${encodeURIComponent(path)}/`
+ `${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
};
export const makeUrl = (project: string, id: string, token?: string): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${id}.jp2/${token_}/info.json`;
}; | export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const imageUrl = getImageUrl(project, `${id}.jp2`, maxWidth, maxHeight, token);
const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
export const getImageUrl = (project: string, path: string, maxWidth: number,
maxHeight: number, token: string, format = 'jpg'): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${encodeURIComponent(path)}/`
+ `${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
};
export const makeUrl = (project: string, id: string, token?: string): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${id}.jp2/${token_}/info.json`;
};
|
Fix credentials loading from json | const data = require('../data/users.json').users;
import { ElementFinder } from 'protractor';
export class User {
alias: string;
description: string;
username: string;
password: string;
constructor(alias: string, description: string) {
this.alias = alias;
this.description = description;
const envUsername = process.env[`IPAAS_${alias.toUpperCase()}_USERNAME`] || null;
const envPassword = process.env[`IPAAS_${alias.toUpperCase()}_PASSWORD`] || null;
if (envUsername === null || envPassword === null) {
this.username = data[alias].username;
this.password = data[alias].password;
} else {
this.username = envUsername;
this.password = envPassword;
}
}
toString(): string {
return `User{alias=${this.alias}, login=${this.username}}`;
}
}
/**
* Represents ui component that has it's angular selector.
*/
export interface IPaaSComponent {
rootElement(): ElementFinder;
}
| import { ElementFinder } from 'protractor';
export class User {
alias: string;
description: string;
username: string;
password: string;
constructor(alias: string, description: string) {
this.alias = alias;
this.description = description;
const envUsername = process.env[`IPAAS_${alias.toUpperCase()}_USERNAME`] || null;
const envPassword = process.env[`IPAAS_${alias.toUpperCase()}_PASSWORD`] || null;
if (envUsername === null || envPassword === null) {
const data = require('../data/users.json').users;
this.username = data[alias].username;
this.password = data[alias].password;
} else {
this.username = envUsername;
this.password = envPassword;
}
}
toString(): string {
return `User{alias=${this.alias}, login=${this.username}}`;
}
}
/**
* Represents ui component that has it's angular selector.
*/
export interface IPaaSComponent {
rootElement(): ElementFinder;
}
|
Correct visibility of variables in Item view-model | import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HackerNewsApi } from '../../services/api';
@inject(Router, HackerNewsApi)
export class Item {
private readonly router: Router;
private readonly api: HackerNewsApi;
private id: number;
private item: any;
private comments: any[];
constructor(router: Router, api: HackerNewsApi) {
this.router = router;
this.api = api;
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.id === undefined || isNaN(params.id) || params.id < 0) {
this.router.navigateToRoute('news');
return;
}
this.id = params.id;
this.comments = [];
this.item = await this.api.fetchItem(this.id);
if (this.item.kids !== undefined && this.item.kids.length >= 1) {
this.comments = await this.api.fetchItems(this.item.kids);
}
}
}
| import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HackerNewsApi } from '../../services/api';
@inject(Router, HackerNewsApi)
export class Item {
id: number;
item: any;
comments: any[];
private readonly router: Router;
private readonly api: HackerNewsApi;
constructor(router: Router, api: HackerNewsApi) {
this.router = router;
this.api = api;
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.id === undefined || isNaN(params.id) || params.id < 0) {
this.router.navigateToRoute('news');
return;
}
this.id = params.id;
this.comments = [];
this.item = await this.api.fetchItem(this.id);
if (this.item.kids !== undefined && this.item.kids.length >= 1) {
this.comments = await this.api.fetchItems(this.item.kids);
}
}
}
|
Fix path parsing with valid \n | import * as path from 'path';
declare var atom: any;
function parseFilepath(s: string): string {
if (s) {
// remove newlines
s = s.replace('\\n', '');
// sanitize with path.parse first
const parsed = path.parse(s);
// join it back and replace Windows' stupid backslash with slash
let joined = path.join(parsed.dir, parsed.base).split(path.sep).join('/');
// fuck Windows Bidi control character
if (joined.charCodeAt(0) === 8234)
joined = joined.substr(1);
return joined.trim();
} else {
return '';
}
}
function parseInputContent(data: string): string {
let expr = data.toString()
.replace(/\\/g, '\\\\')
.replace(/\\/g, '\\\\') // \ => \\
.replace(/\"/g, '\"') // " => \"
.replace(/\n/g, '\\n'); // newline => \\n
// trim spaces
if (atom.config.get('agda-mode.trimSpaces'))
return expr.trim();
else
return expr;
}
export {
parseInputContent,
parseFilepath
}
| import * as path from 'path';
declare var atom: any;
function parseFilepath(s: string): string {
if (s) {
// remove newlines
s = s.replace('\n', '');
// sanitize with path.parse first
const parsed = path.parse(s);
// join it back and replace Windows' stupid backslash with slash
let joined = path.join(parsed.dir, parsed.base).split(path.sep).join('/');
// fuck Windows Bidi control character
if (joined.charCodeAt(0) === 8234)
joined = joined.substr(1);
return joined.trim();
} else {
return '';
}
}
function parseInputContent(data: string): string {
let expr = data.toString()
.replace(/\\/g, '\\\\')
.replace(/\\/g, '\\\\') // \ => \\
.replace(/\"/g, '\"') // " => \"
.replace(/\n/g, '\\n'); // newline => \\n
// trim spaces
if (atom.config.get('agda-mode.trimSpaces'))
return expr.trim();
else
return expr;
}
export {
parseInputContent,
parseFilepath
}
|
Add shortcut key to edit current file | ///<reference path='user_settings_dialog.ts'/>
var remote = require('remote');
var fs = require('fs');
var path = require('path');
var settings = require('../browser/user_settings')
var MainController = require('./main_controller');
var NavigatorController = require('./navigator_controller');
var ngModule = angular.module('adversaria', []);
ngModule.controller('MainController', ['$scope', MainController]);
ngModule.controller('NavigatorController', ['$scope', NavigatorController]);
ngModule.directive('mdPreview', () => {
return ($scope, $elem, $attrs) => {
$scope.$watch($attrs.mdPreview, (source) => {
$elem.html(source);
});
};
});
window.onload = () => {
var document_path = settings.loadDocumentPath();
if (!document_path) {
UserSettingsDialog.show();
}
var scope: any = angular.element(document.getElementById('navigator')).scope();
scope.setRootDirectory(document_path);
}
| ///<reference path='user_settings_dialog.ts'/>
var remote = require('remote');
var fs = require('fs');
var path = require('path');
var settings = require('../browser/user_settings')
var externalEditor = require('./../browser/external_editor');
var MainController = require('./main_controller');
var NavigatorController = require('./navigator_controller');
var ngModule = angular.module('adversaria', []);
ngModule.controller('MainController', ['$scope', MainController]);
ngModule.controller('NavigatorController', ['$scope', NavigatorController]);
ngModule.directive('mdPreview', () => {
return ($scope, $elem, $attrs) => {
$scope.$watch($attrs.mdPreview, (source) => {
$elem.html(source);
});
};
});
window.onload = () => {
var document_path = settings.loadDocumentPath();
if (!document_path) {
UserSettingsDialog.show();
}
var scope: any = angular.element(document.getElementById('navigator')).scope();
scope.setRootDirectory(document_path);
}
window.onkeypress = (e) => {
if (e.keyCode == 101) { // e
var scope = <any>angular.element(document.body).scope();
var path = scope.current_note.path;
console.debug(scope.current_note);
if (scope.current_note.path.length == 0) {
return true;
}
externalEditor.open(path)
}
}
|
Include error reason for failed test run | import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The paths are relative from the `/out/test` folder.
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
const extensionTestsPath = path.resolve(__dirname, './suite');
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [
// This disables all extensions except the one being tested.
'--disable-extensions'
],
});
} catch (err) {
console.error('Failed to run tests');
process.exit(1);
}
}
main(); | import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The paths are relative from the `/out/test` folder.
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
const extensionTestsPath = path.resolve(__dirname, './suite');
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [
// This disables all extensions except the one being tested.
'--disable-extensions'
],
});
} catch (err) {
console.error('Failed to run tests. Reason: ' + err);
process.exit(1);
}
}
main(); |
Add comment about the sanitization regex | /** Sanitize a proposed branch name by replacing illegal characters. */
export function sanitizedBranchName(name: string): string {
return name.replace(/[\x00-\x20\x7F~^:?*\[\\|""<>]|@{|\.\.+|^\.|\.$|\.lock$|\/$/g, '-')
.replace(/--+/g, '-')
.replace(/^-/g, '')
}
| /** Sanitize a proposed branch name by replacing illegal characters. */
export function sanitizedBranchName(name: string): string {
// See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
// ASCII Control chars and space, DEL, ~ ^ : ? * [ \
// | " < and > is technically a valid refname but not on Windows
// the magic sequence @{, consecutive dots, leading and trailing dot, ref ending in .lock
return name.replace(/[\x00-\x20\x7F~^:?*\[\\|""<>]|@{|\.\.+|^\.|\.$|\.lock$|\/$/g, '-')
.replace(/--+/g, '-')
.replace(/^-/g, '')
}
|
Allow only one playwright worker to avoid errors | /**
* Configuration for Playwright using default from @jupyterlab/galata
*/
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: './nbgrader/tests/labextension_ui-tests',
testMatch: '**/*.spec.ts',
testIgnore: '**/node_modules/**/*',
timeout: 30000,
reporter: [[process.env.CI ? 'dot' : 'list'], ['html']],
use: {
// Browser options
// headless: false,
// slowMo: 500,
// Context options
viewport: { width: 1024, height: 768 },
// Artifacts
video: 'retain-on-failure'
},
webServer: {
command: 'jlpm start:test',
url: 'http://localhost:8888/lab',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
};
export default config;
| /**
* Configuration for Playwright using default from @jupyterlab/galata
*/
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
testDir: './nbgrader/tests/labextension_ui-tests',
testMatch: '**/*.spec.ts',
testIgnore: '**/node_modules/**/*',
timeout: 30000,
reporter: [[process.env.CI ? 'dot' : 'list'], ['html']],
workers: 1,
use: {
// Browser options
// headless: false,
// slowMo: 500,
// Context options
viewport: { width: 1024, height: 768 },
// Artifacts
video: 'retain-on-failure'
},
webServer: {
command: 'jlpm start:test',
url: 'http://localhost:8888/lab',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
};
export default config;
|
Fix a broken RSS link (missing slash) | import { siteUrlSetting } from './instanceSettings';
export const rssTermsToUrl = (terms) => {
const siteUrl = siteUrlSetting.get();
const terms_as_GET_params = Object.keys(terms).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(terms[k])).join('&')
return siteUrl+"feed.xml?"+terms_as_GET_params;
}
| import { getSiteUrl } from './vulcan-lib/utils';
export const rssTermsToUrl = (terms) => {
const siteUrl = getSiteUrl();
const terms_as_GET_params = Object.keys(terms).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(terms[k])).join('&')
return siteUrl+"feed.xml?"+terms_as_GET_params;
}
|
Improve rendering for SAML2 registration method. | import { duration } from 'moment';
import { titleCase } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const formatUserStatus = user => {
if (user.is_staff && !user.is_support) {
return translate('Staff');
} else if (user.is_staff && user.is_support) {
return translate('Staff and Support user');
} else if (!user.is_staff && user.is_support) {
return translate('Support user');
} else {
return translate('Regular user');
}
};
export const formatRegistrationMethod = user => {
if (!user.registration_method) {
return translate('Default');
} else if (user.registration_method === 'openid') {
return translate('Estonian ID');
} else {
return titleCase(user.registration_method);
}
};
export const formatLifetime = input => {
const time = duration(input, 'seconds');
const hours = time.hours();
const minutes = time.minutes();
const seconds = time.seconds();
if (input === null || input === 0) {
return translate('token will not timeout');
}
if (hours === 0 && minutes === 0) {
return `${seconds} sec`;
}
if (hours === 0 && minutes !== 0) {
return `${minutes} min`;
}
if (hours !== 0) {
return minutes !== 0 ? `${hours} h ${minutes} min` : `${hours} h`;
}
};
| import { duration } from 'moment';
import { titleCase } from '@waldur/core/utils';
import { translate } from '@waldur/i18n';
export const formatUserStatus = user => {
if (user.is_staff && !user.is_support) {
return translate('Staff');
} else if (user.is_staff && user.is_support) {
return translate('Staff and Support user');
} else if (!user.is_staff && user.is_support) {
return translate('Support user');
} else {
return translate('Regular user');
}
};
export const formatRegistrationMethod = user => {
if (!user.registration_method) {
return translate('Default');
} else if (user.registration_method === 'openid') {
return translate('Estonian ID');
} else if (user.registration_method === 'saml2') {
return 'SAML2';
} else {
return titleCase(user.registration_method);
}
};
export const formatLifetime = input => {
const time = duration(input, 'seconds');
const hours = time.hours();
const minutes = time.minutes();
const seconds = time.seconds();
if (input === null || input === 0) {
return translate('token will not timeout');
}
if (hours === 0 && minutes === 0) {
return `${seconds} sec`;
}
if (hours === 0 && minutes !== 0) {
return `${minutes} min`;
}
if (hours !== 0) {
return minutes !== 0 ? `${hours} h ${minutes} min` : `${hours} h`;
}
};
|
Break long variant names into new lines | import {Checkbox, Heading, Stack} from '@chakra-ui/core'
import message from 'lib/message'
export default function Variants({activeVariants, allVariants, setVariant}) {
return (
<Stack spacing={4}>
<Heading size='md'>{message('variant.activeIn')}</Heading>
<Stack spacing={2}>
{allVariants.map((v, i) => (
<Checkbox
fontWeight='normal'
isChecked={activeVariants[i]}
key={`${i}-${v}`}
name={v}
onChange={(e) => setVariant(i, e.target.checked)}
value={i}
>
{i + 1}. {v}
</Checkbox>
))}
</Stack>
</Stack>
)
}
| import {Checkbox, Heading, Stack} from '@chakra-ui/core'
import message from 'lib/message'
export default function Variants({activeVariants, allVariants, setVariant}) {
return (
<Stack spacing={4}>
<Heading size='md'>{message('variant.activeIn')}</Heading>
<Stack spacing={2}>
{allVariants.map((v, i) => (
<Checkbox
fontWeight='normal'
isChecked={activeVariants[i]}
key={`${i}-${v}`}
name={v}
onChange={(e) => setVariant(i, e.target.checked)}
value={i}
wordBreak='break-all'
>
{i + 1}. {v}
</Checkbox>
))}
</Stack>
</Stack>
)
}
|
Remove object property shorthand for typescript bug | import { ClearMessage, DisplayMessage } from '../messages'
import { State } from './state'
import { charToCodePoint, stringToUtf8ByteArray } from '../util'
export function sendClear() {
const message: ClearMessage = {
action: 'clear'
}
postMessage(message)
}
export function sendCharacter(input?: string) {
if (input === undefined) {
// TODO sendDone()
return
}
const codePoint = charToCodePoint(input)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block,
bytes,
character,
codePoint,
name
}
postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16).toUpperCase())
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
| import { ClearMessage, DisplayMessage } from '../messages'
import { State } from './state'
import { charToCodePoint, stringToUtf8ByteArray } from '../util'
export function sendClear() {
const message: ClearMessage = {
action: 'clear'
}
postMessage(message)
}
export function sendCharacter(input?: string) {
if (input === undefined) {
// TODO sendDone()
return
}
const codePoint = charToCodePoint(input)
const block = getBlock(codePoint)
const bytes = getBytes(input)
const character = input
const name = (State.names) ? State.names[codePoint] || 'Unknown' : 'Loading…'
const message: DisplayMessage = {
action: 'display',
block: block,
bytes: bytes,
character: character,
codePoint: codePoint,
name: name
}
postMessage(message)
}
function getBlock(codePoint: number): string {
if (!State.blocks) return 'Loading…'
for (const block of State.blocks) {
if (codePoint >= Number(block.start) && codePoint <= Number(block.end)) return block.name
}
return 'Unknown'
}
function getBytes(input: string): string {
return stringToUtf8ByteArray(input)
.map(byte => byte.toString(16).toUpperCase())
.map(byte => byte.length < 2 ? '0' + byte : byte)
.join(' ')
}
|
Change invoice state write-off to cancelled | import { c } from 'ttag';
import { INVOICE_STATE } from '@proton/shared/lib/constants';
import { Badge } from '../../components';
import { Invoice } from './interface';
const TYPES = {
[INVOICE_STATE.UNPAID]: 'error',
[INVOICE_STATE.PAID]: 'success',
[INVOICE_STATE.VOID]: 'default',
[INVOICE_STATE.BILLED]: 'default',
[INVOICE_STATE.WRITEOFF]: 'default',
} as const;
const getStatesI18N = (invoiceState: INVOICE_STATE) => {
switch (invoiceState) {
case INVOICE_STATE.UNPAID:
return c('Invoice state display as badge').t`Unpaid`;
case INVOICE_STATE.PAID:
return c('Invoice state display as badge').t`Paid`;
case INVOICE_STATE.VOID:
return c('Invoice state display as badge').t`Void`;
case INVOICE_STATE.BILLED:
return c('Invoice state display as badge').t`Billed`;
case INVOICE_STATE.WRITEOFF:
return c('Invoice state display as badge').t`Writeoff`;
default:
return '';
}
};
interface Props {
invoice: Invoice;
}
const InvoiceState = ({ invoice }: Props) => {
return <Badge type={TYPES[invoice.State] || 'default'}>{getStatesI18N(invoice.State)}</Badge>;
};
export default InvoiceState;
| import { c } from 'ttag';
import { INVOICE_STATE } from '@proton/shared/lib/constants';
import { Badge } from '../../components';
import { Invoice } from './interface';
const TYPES = {
[INVOICE_STATE.UNPAID]: 'error',
[INVOICE_STATE.PAID]: 'success',
[INVOICE_STATE.VOID]: 'default',
[INVOICE_STATE.BILLED]: 'default',
[INVOICE_STATE.WRITEOFF]: 'default',
} as const;
const getStatesI18N = (invoiceState: INVOICE_STATE) => {
switch (invoiceState) {
case INVOICE_STATE.UNPAID:
return c('Invoice state display as badge').t`Unpaid`;
case INVOICE_STATE.PAID:
return c('Invoice state display as badge').t`Paid`;
case INVOICE_STATE.VOID:
return c('Invoice state display as badge').t`Void`;
case INVOICE_STATE.BILLED:
return c('Invoice state display as badge').t`Billed`;
case INVOICE_STATE.WRITEOFF:
return c('Invoice state display as badge').t`Cancelled`;
default:
return '';
}
};
interface Props {
invoice: Invoice;
}
const InvoiceState = ({ invoice }: Props) => {
return <Badge type={TYPES[invoice.State] || 'default'}>{getStatesI18N(invoice.State)}</Badge>;
};
export default InvoiceState;
|
Disable all permissions requests by default | import { ipcMain, app, Menu } from 'electron';
import { resolve } from 'path';
import { platform, homedir } from 'os';
import { AppWindow } from './app-window';
ipcMain.setMaxListeners(0);
app.setPath('userData', resolve(homedir(), '.wexond'));
export const appWindow = new AppWindow();
app.on('ready', () => {
// Create our menu entries so that we can use macOS shortcuts
Menu.setApplicationMenu(
Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' },
{ role: 'quit' },
],
},
]),
);
appWindow.createWindow();
});
app.on('window-all-closed', () => {
if (platform() !== 'darwin') {
app.quit();
}
});
| import { ipcMain, app, Menu, session } from 'electron';
import { resolve } from 'path';
import { platform, homedir } from 'os';
import { AppWindow } from './app-window';
ipcMain.setMaxListeners(0);
app.setPath('userData', resolve(homedir(), '.wexond'));
export const appWindow = new AppWindow();
session.defaultSession.setPermissionRequestHandler(
(webContents, permission, callback) => {
if (permission === 'notifications' || permission === 'fullscreen') {
callback(true);
} else {
callback(false);
}
},
);
app.on('ready', () => {
// Create our menu entries so that we can use macOS shortcuts
Menu.setApplicationMenu(
Menu.buildFromTemplate([
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' },
{ role: 'quit' },
],
},
]),
);
appWindow.createWindow();
});
app.on('window-all-closed', () => {
if (platform() !== 'darwin') {
app.quit();
}
});
|
Remove launcher item for now as well. It may be unnecessary. | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ILauncher } from '@jupyterlab/launcher';
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
/**
* The command IDs used by the debugger plugin.
*/
namespace CommandIDs {
export const open = 'debugger:open';
}
/**
* A plugin providing a UI for code debugging and environment inspection.
*/
const plugin: JupyterFrontEndPlugin<IDebugger> = {
id: '@jupyterlab/debugger:plugin',
optional: [ILauncher, ILayoutRestorer],
provides: IDebugger,
autoStart: true,
activate: (
app: JupyterFrontEnd,
launcher: ILauncher | null,
restorer: ILayoutRestorer | null
): IDebugger => {
console.log(plugin.id, 'Hello, world.');
const { shell } = app;
const command = CommandIDs.open;
const label = 'Environment';
const widget = new Debugger();
widget.id = 'jp-debugger';
widget.title.label = label;
shell.add(widget, 'right', { activate: false });
if (launcher) {
launcher.add({ command, args: { isLauncher: true } });
}
if (restorer) {
restorer.add(widget, widget.id);
}
return widget;
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [plugin];
export default plugins;
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { Debugger } from './debugger';
import { IDebugger } from './tokens';
/**
* A plugin providing a UI for code debugging and environment inspection.
*/
const plugin: JupyterFrontEndPlugin<IDebugger> = {
id: '@jupyterlab/debugger:plugin',
optional: [ILayoutRestorer],
provides: IDebugger,
autoStart: true,
activate: (
app: JupyterFrontEnd,
restorer: ILayoutRestorer | null
): IDebugger => {
console.log(plugin.id, 'Hello, world.');
const { shell } = app;
const label = 'Environment';
const widget = new Debugger();
widget.id = 'jp-debugger';
widget.title.label = label;
shell.add(widget, 'right', { activate: false });
if (restorer) {
restorer.add(widget, widget.id);
}
return widget;
}
};
/**
* Export the plugins as default.
*/
const plugins: JupyterFrontEndPlugin<any>[] = [plugin];
export default plugins;
|
Update ActiveLink to use redux | import * as _ from 'lodash';
import * as Reflux from 'reflux';
import * as React from 'react';
import { RouteStore } from '../../stores/route-store';
import { ActiveLinkProps } from './props';
const Route = require('react-router');
export const ActiveLink = React.createClass<ActiveLinkProps, any>({
mixins: [Reflux.connect(RouteStore, 'route')],
render: function(){
var path:string = _.get(this.state.route, 'location.pathname', '');
var active:string = path === this.props.to ? 'active' : '';
return (
<Route.Link className={`item ${active}`} to={this.props.to}>
{this.props.children}
</Route.Link>
);
}
});
| import * as _ from 'lodash';
import * as React from 'react';
import { connect } from 'react-redux';
import { ActiveLinkProps } from './props';
const Route = require('react-router');
export const ActiveLink = connect(state => ({router: state.router}))(React.createClass<ActiveLinkProps, any>({
render: function(){
var path:string = _.get(this.props.router, 'location.pathname', '');
var active:string = path === this.props.to ? 'active' : '';
return (
<Route.Link className={`item ${active}`} to={this.props.to}>
{this.props.children}
</Route.Link>
);
}
}));
|
Add `<`as end of colors | const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\})`;
const DOT_VALUE = `(?:\\.\\d+)`; // ['.x', '']
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x']
const HEXA_VALUE = '[\\da-f]'; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
export { EOL, ALPHA, DOT_VALUE, HEXA_VALUE };
| const EOL = `(?:$|"|'|,| |;|\\)|\\r|\\n|\}|<)`;
const DOT_VALUE = `(?:\\.\\d+)`; // ['.x', '']
const ALPHA = `(?:1(:?\\.0+)?|0${DOT_VALUE}?|${DOT_VALUE})`; // ['0', '1', '0.x', '1.0', '.x']
const HEXA_VALUE = '[\\da-f]'; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
export { EOL, ALPHA, DOT_VALUE, HEXA_VALUE };
|
Rename fit -> it in functional tests | import { browser } from 'protractor';
import * as support from '../specs/support';
import { LandingPage } from '../specs/page_objects';
describe('Landing Page', () => {
beforeEach( async () => {
await support.desktopTestSetup();
let landingPage = new LandingPage();
await landingPage.open();
});
fit('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
});
});
| import { browser } from 'protractor';
import * as support from '../specs/support';
import { LandingPage } from '../specs/page_objects';
describe('Landing Page', () => {
beforeEach( async () => {
await support.desktopTestSetup();
let landingPage = new LandingPage();
await landingPage.open();
});
it('writes the screenshot of landing page', async () => {
await expect(await browser.getTitle()).toEqual('OpenShift.io');
await support.writeScreenshot('page.png');
});
});
|
Update console message if fullMathjaxUrl is missing | /* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
/**
* @packageDocumentation
* @module mathjax2-extension
*/
import { JupyterFrontEndPlugin } from '@jupyterlab/application';
import { PageConfig } from '@jupyterlab/coreutils';
import { ILatexTypesetter } from '@jupyterlab/rendermime';
import { MathJaxTypesetter } from '@jupyterlab/mathjax2';
/**
* The MathJax latexTypesetter plugin.
*/
const plugin: JupyterFrontEndPlugin<ILatexTypesetter> = {
id: '@jupyterlab/mathjax2-extension:plugin',
autoStart: true,
provides: ILatexTypesetter,
activate: () => {
const url = PageConfig.getOption('fullMathjaxUrl');
const config = PageConfig.getOption('mathjaxConfig');
if (!url) {
const message =
`${plugin.id} uses 'mathJaxUrl' and 'mathjaxConfig' in PageConfig ` +
`to operate but 'mathJaxUrl' was not found.`;
throw new Error(message);
}
return new MathJaxTypesetter({ url, config });
}
};
/**
* Export the plugin as default.
*/
export default plugin;
| /* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
/**
* @packageDocumentation
* @module mathjax2-extension
*/
import { JupyterFrontEndPlugin } from '@jupyterlab/application';
import { PageConfig } from '@jupyterlab/coreutils';
import { ILatexTypesetter } from '@jupyterlab/rendermime';
import { MathJaxTypesetter } from '@jupyterlab/mathjax2';
/**
* The MathJax latexTypesetter plugin.
*/
const plugin: JupyterFrontEndPlugin<ILatexTypesetter> = {
id: '@jupyterlab/mathjax2-extension:plugin',
autoStart: true,
provides: ILatexTypesetter,
activate: () => {
const [urlParam, configParam] = ['fullMathjaxUrl', 'mathjaxConfig'];
const url = PageConfig.getOption(urlParam);
const config = PageConfig.getOption(configParam);
if (!url) {
const message =
`${plugin.id} uses '${urlParam}' and '${configParam}' in PageConfig ` +
`to operate but '${urlParam}' was not found.`;
throw new Error(message);
}
return new MathJaxTypesetter({ url, config });
}
};
/**
* Export the plugin as default.
*/
export default plugin;
|
Allow this.passthrough for repsonse param | import FakeXMLHttpRequest from "fake-xml-http-request";
import { Params, QueryParams } from "route-recognizer";
type SetupCallback = (this: Server) => void;
interface SetupConfig {
forcePassthrough: boolean;
}
export type Config = SetupCallback | SetupConfig;
export class Server {
// HTTP request verbs
public get: RequestHandler;
public put: RequestHandler;
public post: RequestHandler;
public patch: RequestHandler;
public delete: RequestHandler;
public options: RequestHandler;
public head: RequestHandler;
constructor(setup?: SetupCallback);
public shutdown(): void;
}
export type RequestHandler = (
urlExpression: string,
response: ResponseHandler,
async?: boolean | number
) => void;
export type ResponseData = [number, { [k: string]: string }, string];
interface ExtraRequestData {
params: Params;
queryParams: QueryParams;
}
export type ResponseHandler = (
request: FakeXMLHttpRequest | ExtraRequestData
) => ResponseData | PromiseLike<ResponseData>;
export default Server;
| import FakeXMLHttpRequest from 'fake-xml-http-request';
import { Params, QueryParams } from 'route-recognizer';
type SetupCallback = (this: Server) => void;
interface SetupConfig {
forcePassthrough: boolean;
}
export type Config = SetupCallback | SetupConfig;
export class Server {
public passthrough: RequestHandler;
constructor(config?: Config);
// HTTP request verbs
public get: RequestHandler;
public put: RequestHandler;
public post: RequestHandler;
public patch: RequestHandler;
public delete: RequestHandler;
public options: RequestHandler;
public head: RequestHandler;
public shutdown(): void;
}
export type RequestHandler = (
urlExpression: string,
response: ResponseHandler,
asyncOrDelay?: boolean | number
) => void;
export type ResponseData = [number, { [k: string]: string }, string];
interface ExtraRequestData {
params: Params;
queryParams: QueryParams;
}
export type ResponseHandler = (
request: FakeXMLHttpRequest | ExtraRequestData
) => ResponseData | PromiseLike<ResponseData>;
export default Server;
|
Use replace activation strategy for StoryList view models | import { observable } from 'aurelia-framework';
import { activationStrategy } from 'aurelia-router';
import {
HackerNewsApi,
STORIES_PER_PAGE
} from '../services/api';
export abstract class StoryList {
stories: any[];
offset: number;
@observable() currentPage: number;
totalPages: number;
readonly api: HackerNewsApi;
private allStories: number[] = [];
constructor(api: HackerNewsApi) {
this.api = api;
}
abstract fetchIds(): Promise<number[]>;
determineActivationStrategy(): string {
// don't forcefully refresh the page, just invoke our activate method
return activationStrategy.invokeLifecycle;
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.page === undefined || isNaN(params.page) || params.page < 1) {
this.currentPage = 1;
} else {
this.currentPage = Number(params.page);
}
this.allStories = await this.fetchIds();
this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage);
this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE);
}
currentPageChanged(newValue: number, oldValue: number): void {
if (newValue === oldValue) {
return;
}
this.offset = STORIES_PER_PAGE * (newValue - 1);
}
}
| import { observable } from 'aurelia-framework';
import {
HackerNewsApi,
STORIES_PER_PAGE
} from '../services/api';
export abstract class StoryList {
stories: any[];
offset: number;
@observable() currentPage: number;
totalPages: number;
readonly api: HackerNewsApi;
private allStories: number[] = [];
constructor(api: HackerNewsApi) {
this.api = api;
}
abstract fetchIds(): Promise<number[]>;
determineActivationStrategy(): string {
return 'replace';
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.page === undefined || isNaN(params.page) || params.page < 1) {
this.currentPage = 1;
} else {
this.currentPage = Number(params.page);
}
this.allStories = await this.fetchIds();
this.stories = await this.api.fetchItemsOnPage(this.allStories, this.currentPage);
this.totalPages = Math.ceil(this.allStories.length / STORIES_PER_PAGE);
}
currentPageChanged(newValue: number, oldValue: number): void {
if (newValue === oldValue) {
return;
}
this.offset = STORIES_PER_PAGE * (newValue - 1);
}
}
|
Add number of reviews and TOS violations to TO tooltip. | import * as React from 'react';
import { Button } from '@shopify/polaris';
import { Tooltip } from '@blueprintjs/core';
import { TOpticonData, RequesterScores } from '../../types';
import { turkopticonBaseUrl } from '../../constants/urls';
export interface Props {
readonly requesterId: string;
readonly turkopticon?: TOpticonData;
}
class TOpticonButton extends React.PureComponent<Props, never> {
static generateTooltipContent = (scores: RequesterScores) =>
`Pay: ${scores.pay}.
Comm: ${scores.comm}.
Fair: ${scores.fair}.
Fast: ${scores.fast}.`;
public render() {
const { requesterId, turkopticon } = this.props;
return turkopticon ? (
<Tooltip
content={TOpticonButton.generateTooltipContent(turkopticon.attrs)}
>
<Button plain external url={turkopticonBaseUrl + requesterId}>
T.O. Page
</Button>
</Tooltip>
) : (
<Button plain disabled external url={turkopticonBaseUrl + requesterId}>
No T.O. data.
</Button>
);
}
}
export default TOpticonButton;
| import * as React from 'react';
import { Button, Stack, TextContainer } from '@shopify/polaris';
import { Tooltip } from '@blueprintjs/core';
import { TOpticonData } from '../../types';
import { turkopticonBaseUrl } from '../../constants/urls';
export interface Props {
readonly requesterId: string;
readonly turkopticon?: TOpticonData;
}
class TOpticonButton extends React.PureComponent<Props, never> {
static generateTooltipContent = (data: TOpticonData) => {
const { attrs: { pay, comm, fair, fast }, reviews, tos_flags } = data;
return (
<Stack vertical>
<TextContainer>
Pay: {pay}. Comm: {comm}. Fair: {fair}. Fast: {fast}.
</TextContainer>
<TextContainer>Calculated from {reviews} reviews.</TextContainer>
<TextContainer>{tos_flags} reported TOS violations.</TextContainer>
</Stack>
);
};
public render() {
const { requesterId, turkopticon } = this.props;
return turkopticon ? (
<Tooltip content={TOpticonButton.generateTooltipContent(turkopticon)}>
<Button plain external url={turkopticonBaseUrl + requesterId}>
T.O. Page
</Button>
</Tooltip>
) : (
<Button plain disabled external url={turkopticonBaseUrl + requesterId}>
No T.O. data.
</Button>
);
}
}
export default TOpticonButton;
|
Add support in reducer for login action | import CeraonState from '../../State/CeraonState';
import CeraonAction from '../../Actions/CeraonAction';
export default function ceraonReducer(state: CeraonState, action: CeraonAction) : CeraonState {
return state;
}
| import CeraonState from '../../State/CeraonState';
import CeraonAction from '../../Actions/CeraonAction';
import CeraonActionType from '../../Actions/CeraonActionType';
import CeraonPage from '../../State/CeraonPage';
export default function ceraonReducer(state: CeraonState, action: CeraonAction) : CeraonState {
if (action.type == CeraonActionType.Login) {
state.activePage = CeraonPage.Loading;
state.loadingPageState.loadingStatusMessage = 'Logging you in...';
}
return state;
}
|
Add some sensible default values | import { Zone } from './../zones/zone';
export class Program {
id: number;
name: string;
scheduleItems: ProgramScheduleItem[];
programScheduleType: ProgramScheduleType;
startTimeHours: number;
startTimeMinutes: number;
monday: boolean;
tuesday: boolean;
wednesday: boolean;
thursday: boolean;
friday: boolean;
saturday: boolean;
sunday: boolean;
constructor() {
this.scheduleItems = [];
}
getRunningTime(): number {
return this.scheduleItems
.map(item => item.minutes)
.reduce((prev, curr) => prev + curr, 0);
}
}
export class ProgramScheduleItem {
zone: Zone;
minutes: number;
}
export enum ProgramScheduleType {
ManualOnly = 0,
AllDays = 1,
OddDays = 2,
EvenDays = 3,
DaysOfWeek = 4
}
| import { Zone } from './../zones/zone';
export class Program {
id: number = 0;
name: string;
scheduleItems: ProgramScheduleItem[] = [];
programScheduleType: ProgramScheduleType = ProgramScheduleType.ManualOnly;
startTimeHours: number = 0;
startTimeMinutes: number = 0;
monday: boolean;
tuesday: boolean;
wednesday: boolean;
thursday: boolean;
friday: boolean;
saturday: boolean;
sunday: boolean;
getRunningTime(): number {
return this.scheduleItems
.map(item => item.minutes)
.reduce((prev, curr) => prev + curr, 0);
}
}
export class ProgramScheduleItem {
zone: Zone;
minutes: number;
}
export enum ProgramScheduleType {
ManualOnly = 0,
AllDays = 1,
OddDays = 2,
EvenDays = 3,
DaysOfWeek = 4
}
|
Add remaining levels into build settings | %YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1045 &1
EditorBuildSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Scenes:
- enabled: 1
path: Assets/Scenes/Levels/Level01.unity
- enabled: 1
path: Assets/Scenes/Levels/Level02.unity
| %YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1045 &1
EditorBuildSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Scenes:
- enabled: 1
path: Assets/Scenes/Levels/Level01.unity
- enabled: 1
path: Assets/Scenes/Levels/Level02.unity
- enabled: 1
path: Assets/Scenes/Levels/Level03.unity
- enabled: 1
path: Assets/Scenes/Levels/Level04.unity
- enabled: 1
path: Assets/Scenes/Levels/Level05.unity
- enabled: 1
path: Assets/Scenes/Levels/Level06.unity
- enabled: 1
path: Assets/Scenes/Levels/Level07.unity
- enabled: 1
path: Assets/Scenes/Levels/Level08.unity
- enabled: 1
path: Assets/Scenes/Levels/Level09.unity
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.