Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove reference to Infviz Toolkit |
/// <reference path="Reference.d.ts"/>
module Orange.Modularity {
export class RegionManager {
constructor(public container: Orange.Modularity.Container) { }
public disposeRegions(root: HTMLElement) {
var attr = root.getAttribute("data-view");
if (attr == null || attr == "") {
if (typeof root.children !== "undefined") {
for (var i = 0; i < root.children.length; i++)
this.disposeRegions(<HTMLElement>root.children[i]);
}
}
else {
var view = <Infviz.Controls.Control>root["instance"];
view.dispose();
}
}
public initializeRegions(root: HTMLElement): void {
var attr = root.getAttribute("data-view");
if (attr == null || attr == "") {
if (typeof root.children !== "undefined") {
for (var i = 0; i < root.children.length; i++)
this.initializeRegions(<HTMLElement>root.children[i]);
}
}
else {
var viewType = eval(attr);
var view = this.container.resolve(viewType);
if (typeof view.element !== "undefined")
view.element = root;
var idAttr = root.getAttribute("data-view-id");
if (idAttr != null && attr != "") {
if (view.setViewId !== "undefined") {
view.setViewId(idAttr);
}
}
root["instance"] = view;
}
}
}
} |
/// <reference path="Reference.d.ts"/>
module Orange.Modularity {
export class RegionManager {
constructor(public container: Orange.Modularity.Container) { }
public disposeRegions(root: HTMLElement) {
var attr = root.getAttribute("data-view");
if (attr == null || attr == "") {
if (typeof root.children !== "undefined") {
for (var i = 0; i < root.children.length; i++)
this.disposeRegions(<HTMLElement>root.children[i]);
}
}
else {
var view = <any>root["instance"];
if (typeof view.dispose === 'function')
view.dispose();
}
}
public initializeRegions(root: HTMLElement): void {
var attr = root.getAttribute("data-view");
if (attr == null || attr == "") {
if (typeof root.children !== "undefined") {
for (var i = 0; i < root.children.length; i++)
this.initializeRegions(<HTMLElement>root.children[i]);
}
}
else {
var viewType = eval(attr);
var view = this.container.resolve(viewType);
if (typeof view.element !== "undefined")
view.element = root;
var idAttr = root.getAttribute("data-view-id");
if (idAttr != null && attr != "") {
if (view.setViewId !== "undefined") {
view.setViewId(idAttr);
}
}
root["instance"] = view;
}
}
}
} |
Revert "docs(demo): remove unnecessary window declaration" | import Panzoom from '../src/panzoom'
console.log('This is a demo version of Panzoom for testing.')
console.log('It exposes a global (window.Panzoom) and should not be used in production.')
window.Panzoom = Panzoom
| import Panzoom from '../src/panzoom'
console.log('This is a demo version of Panzoom for testing.')
console.log('It exposes a global (window.Panzoom) and should not be used in production.')
declare global {
interface Window {
Panzoom: typeof Panzoom
}
}
window.Panzoom = Panzoom
|
Remove `as const` from article sorts export constant | import { GraphQLEnumType } from "graphql"
export const ARTICLE_SORTS = {
PUBLISHED_AT_ASC: {
value: "published_at",
},
PUBLISHED_AT_DESC: {
value: "-published_at",
},
} as const
const ArticleSorts = {
type: new GraphQLEnumType({
name: "ArticleSorts",
values: ARTICLE_SORTS,
}),
}
export type ArticleSort = typeof ARTICLE_SORTS[keyof typeof ARTICLE_SORTS]["value"]
export default ArticleSorts
| import { GraphQLEnumType } from "graphql"
export const ARTICLE_SORTS = {
PUBLISHED_AT_ASC: {
value: "published_at",
},
PUBLISHED_AT_DESC: {
value: "-published_at",
},
}
const ArticleSorts = {
type: new GraphQLEnumType({
name: "ArticleSorts",
values: ARTICLE_SORTS,
}),
}
export type ArticleSort = typeof ARTICLE_SORTS[keyof typeof ARTICLE_SORTS]["value"]
export default ArticleSorts
|
Correct string for the IOption interface | /**
* Option model interface
* @author Islam Attrash
*/
export interface IOption {
/**
* Text for the option
*/
text: string;
/**
* The option value
*/
value: any;
//Any other dynamic user selection
[key: string]: any;
}
| /**
* Option model interface
* @author Islam Attrash
*/
export interface IOption {
/**
* Text for the option
*/
text: string;
/**
* The option value
*/
value: any;
/**
* Any other OPTIONAL dynamic user properties
*/
[key: string]: any;
}
|
Disable minification temporaly (Fuck Webkit) | const StringReplacePlugin = require('string-replace-webpack-plugin');
import constant from './const';
import minify from './minify';
import banner from './banner';
const env = process.env.NODE_ENV;
const isProduction = env === 'production';
export default version => {
const plugins = [
constant(),
new StringReplacePlugin()
];
if (isProduction) {
plugins.push(minify());
}
plugins.push(banner(version));
return plugins;
};
| const StringReplacePlugin = require('string-replace-webpack-plugin');
import constant from './const';
import minify from './minify';
import banner from './banner';
const env = process.env.NODE_ENV;
const isProduction = env === 'production';
export default version => {
const plugins = [
constant(),
new StringReplacePlugin()
];
/*
if (isProduction) {
plugins.push(minify());
}
*/
plugins.push(banner(version));
return plugins;
};
|
Fix off by one, include all lines in range | import { DiffSelection } from '../../../models/diff'
import { ISelectionStrategy } from './selection-strategy'
import { DiffLineGutter } from '../diff-line-gutter'
import { range } from '../../../lib/range'
/** apply hunk selection to the current diff */
export class RangeSelection implements ISelectionStrategy {
private readonly _start: number
private readonly _end: number
private readonly _desiredSelection: boolean
private readonly _snapshot: DiffSelection
public constructor(
start: number,
end: number,
desiredSelection: boolean,
snapshot: DiffSelection
) {
this._start = start
this._end = end
this._desiredSelection = desiredSelection
this._snapshot = snapshot
}
public update(index: number) {
// no-op
}
public paint(elements: Map<number, DiffLineGutter>) {
range(this._start, this._end).forEach(row => {
const element = elements.get(row)
if (!element) {
// if the element has not been rendered, it's not visible to the user
return
}
if (!element.isIncluded()) {
return
}
const selected = this._desiredSelection
element.setSelected(selected)
})
}
public done(): DiffSelection {
const length = this._end - this._start + 1
const newSelection = this._snapshot.withRangeSelection(
this._start,
length,
this._desiredSelection
)
return newSelection
}
}
| import { DiffSelection } from '../../../models/diff'
import { ISelectionStrategy } from './selection-strategy'
import { DiffLineGutter } from '../diff-line-gutter'
import { range } from '../../../lib/range'
/** apply hunk selection to the current diff */
export class RangeSelection implements ISelectionStrategy {
private readonly _start: number
private readonly _end: number
private readonly _desiredSelection: boolean
private readonly _snapshot: DiffSelection
public constructor(
start: number,
end: number,
desiredSelection: boolean,
snapshot: DiffSelection
) {
this._start = start
this._end = end
this._desiredSelection = desiredSelection
this._snapshot = snapshot
}
public update(index: number) {
// no-op
}
public paint(elements: Map<number, DiffLineGutter>) {
range(this._start, this._end + 1).forEach(row => {
const element = elements.get(row)
if (!element) {
// if the element has not been rendered, it's not visible to the user
return
}
if (!element.isIncluded()) {
return
}
const selected = this._desiredSelection
element.setSelected(selected)
})
}
public done(): DiffSelection {
const length = this._end - this._start + 1
const newSelection = this._snapshot.withRangeSelection(
this._start,
length,
this._desiredSelection
)
return newSelection
}
}
|
Add router testing module to Error Component tests | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TitleService } from '../shared/title.service';
import { MockTitleService } from '../shared/mocks/mock-title.service';
import { PageHeroComponent } from '../shared/page-hero/page-hero.component';
import { ErrorComponent } from './error.component';
describe('ErrorComponent', () => {
const mockTitleService = new MockTitleService();
let component: ErrorComponent;
let fixture: ComponentFixture<ErrorComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
PageHeroComponent,
ErrorComponent
],
providers: [
{ provide: TitleService, useValue: mockTitleService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ErrorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create and show 404 text', () => {
expect(component).toBeTruthy();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.basic-card > h2').textContent)
.toContain('You’re looking a little lost there.');
});
it('should reset title', () => {
expect(mockTitleService.mockTitle).toBe('');
});
});
| import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { TitleService } from '../shared/title.service';
import { MockTitleService } from '../shared/mocks/mock-title.service';
import { PageHeroComponent } from '../shared/page-hero/page-hero.component';
import { ErrorComponent } from './error.component';
describe('ErrorComponent', () => {
const mockTitleService = new MockTitleService();
let component: ErrorComponent;
let fixture: ComponentFixture<ErrorComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [
PageHeroComponent,
ErrorComponent
],
providers: [
{ provide: TitleService, useValue: mockTitleService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ErrorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create and show 404 text', () => {
expect(component).toBeTruthy();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.basic-card > h2').textContent)
.toContain('You’re looking a little lost there.');
});
it('should reset title', () => {
expect(mockTitleService.mockTitle).toBe('');
});
});
|
Fix whitespace above header image | import { Flex } from "@artsy/palette"
import { ArtistSeriesHeader_artistSeries } from "__generated__/ArtistSeriesHeader_artistSeries.graphql"
import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
interface ArtistSeriesHeaderProps {
artistSeries: ArtistSeriesHeader_artistSeries
}
export const ArtistSeriesHeader: React.SFC<ArtistSeriesHeaderProps> = ({ artistSeries }) => {
const url = artistSeries.image?.url!
return (
<Flex flexDirection="row" justifyContent="center">
<OpaqueImageView width={180} height={180} imageURL={url} style={{ borderRadius: 2 }} />
</Flex>
)
}
export const ArtistSeriesHeaderFragmentContainer = createFragmentContainer(ArtistSeriesHeader, {
artistSeries: graphql`
fragment ArtistSeriesHeader_artistSeries on ArtistSeries {
image {
url
}
}
`,
})
| import { Flex } from "@artsy/palette"
import { ArtistSeriesHeader_artistSeries } from "__generated__/ArtistSeriesHeader_artistSeries.graphql"
import OpaqueImageView from "lib/Components/OpaqueImageView/OpaqueImageView"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
interface ArtistSeriesHeaderProps {
artistSeries: ArtistSeriesHeader_artistSeries
}
export const ArtistSeriesHeader: React.SFC<ArtistSeriesHeaderProps> = ({ artistSeries }) => {
const url = artistSeries.image?.url!
return (
<Flex flexDirection="row" justifyContent="center" pt={1}>
<OpaqueImageView width={180} height={180} imageURL={url} style={{ borderRadius: 2 }} />
</Flex>
)
}
export const ArtistSeriesHeaderFragmentContainer = createFragmentContainer(ArtistSeriesHeader, {
artistSeries: graphql`
fragment ArtistSeriesHeader_artistSeries on ArtistSeries {
image {
url
}
}
`,
})
|
Return true if we can make all the units | import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
units = {
"Probe": 1,
"Zealot": 2,
"Sentry": 2,
"Stalker": 2,
"HighTemplar": 2,
"DarkTemplar": 2,
"Immortal": 4,
"Colossus": 6,
"Archon": 4,
"Observer": 1,
"WarpPrism": 2,
"Phoenix": 2,
"MothershipCore": 2,
"VoidRay": 4,
"Oracle": 3,
"Tempest": 4,
"Carrier": 6,
"Mothership": 8
};
solve(input: string): string {
let supply = parseInt(input.split(' ')[0]) * 8;
let units = input.split(' ').slice(1);
for (let u of units) {
supply -= this.units[u];
}
return units.join(' ');
}
}
| import {ISolution} from '../solution.interface';
export class Solution implements ISolution<string, string> {
units = {
"Probe": 1,
"Zealot": 2,
"Sentry": 2,
"Stalker": 2,
"HighTemplar": 2,
"DarkTemplar": 2,
"Immortal": 4,
"Colossus": 6,
"Archon": 4,
"Observer": 1,
"WarpPrism": 2,
"Phoenix": 2,
"MothershipCore": 2,
"VoidRay": 4,
"Oracle": 3,
"Tempest": 4,
"Carrier": 6,
"Mothership": 8
};
solve(input: string): string {
let supply = parseInt(input.split(' ')[0]) * 8;
let units = input.split(' ').slice(1);
for (let u of units) {
supply -= this.units[u];
}
if (supply >= 0) {
return "true";
}
return units.join(' ');
}
}
|
Change display size to full screen | import { app, BrowserWindow } from 'electron';
import * as electronReload from 'electron-reload';
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 400,
height: 380,
webPreferences: { webSecurity: false },
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
electronReload(__dirname, {
electron: 'npm start',
});
| import { app, BrowserWindow } from 'electron';
import * as electronReload from 'electron-reload';
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
fullscreen: true,
webPreferences: { webSecurity: false },
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
electronReload(__dirname, {
electron: 'npm start',
});
|
Fix Google Maps scroll issue | /// <reference path="../typings/browser.d.ts" />
namespace AFCC {
export function activate(selector: string) {
$(selector).addClass("active");
}
export function splashDanceParty() {
activate(".dance-party-header");
}
export function splashDancePartyBunnies() {
activate("#splash .page-background");
}
export function showDateLocationHeader() {
activate(".date-location-header");
}
export function init() {
setTimeout(splashDanceParty, Conf.DancePartyHeaderStart);
setTimeout(splashDancePartyBunnies, Conf.DancePartyHeaderBunnies);
setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader)
}
}
$(document).ready(function() {
AFCC.init();
});
| /// <reference path="../typings/browser.d.ts" />
namespace AFCC {
export function activate(selector: string) {
$(selector).addClass("active");
}
export function splashDanceParty() {
activate(".dance-party-header");
}
export function splashDancePartyBunnies() {
activate("#splash .page-background");
}
export function showDateLocationHeader() {
activate(".date-location-header");
}
// Fix Google Map scroll issue
var mapFixed = false;
export function fixMap() {
if (mapFixed) return;
$('.map-container iframe').css("pointer-events", "none");
$('.map-container').unbind().click(function() {
$(this).find('iframe').css("pointer-events", "auto");
mapFixed = false;
});
}
export function init() {
// Splash
setTimeout(splashDanceParty, Conf.DancePartyHeaderStart);
setTimeout(splashDancePartyBunnies, Conf.DancePartyHeaderBunnies);
setTimeout(showDateLocationHeader, Conf.ShowDateLocationHeader);
// Map
fixMap();
$(window).scroll(fixMap);
}
}
$(document).ready(function() {
AFCC.init();
});
|
Use import instead of require. Remove unnecessary namespace. | import {ResponseBody} from "./Common";
import {ResponseModel} from "./Handler";
let ViewsDirectory = require("../definitions/ViewsDirectory");
namespace Views {
export class View {
constructor(id: string, render: RendersResponse) {
this.id = id;
this.render = render;
ViewsDirectory[id] = this;
}
id: string;
render: RendersResponse;
}
export interface RendersResponse {
(model: ResponseModel): ResponseBody | Promise<ResponseBody>;
}
}
export = Views; | import * as ViewsDirectory from "../definitions/ViewsDirectory";
import {ResponseBody} from "./Common";
import {ResponseModel} from "./Handler";
export class View {
constructor(id: string, render: RendersResponse) {
this.id = id;
this.render = render;
ViewsDirectory[id] = this;
}
id: string;
render: RendersResponse;
}
export interface RendersResponse {
(model: ResponseModel): ResponseBody | Promise<ResponseBody>;
} |
Improve typescript support for test utils | import Vuex from 'vuex'
import {shallowMount, createLocalVue} from '@vue/test-utils'
export const mountMixin = (
component: object,
mountOptions: object = {},
template: string = '<div />'
) => {
const localVue = createLocalVue();
localVue.use(Vuex);
return shallowMount({
template,
mixins: [component]
}, {
localVue,
...mountOptions
})
};
export const mountMixinWithStore = (
component: object,
storeOptions: object = {},
mountOptions: object = {},
template: string = '<div />'
) => {
const localVue = createLocalVue();
localVue.use(Vuex);
const store = new Vuex.Store({
...storeOptions
});
return shallowMount({
template,
mixins: [component]
}, {
store,
localVue,
...mountOptions
})
};
export const createContextMock = (props = {}) => ({
// @ts-ignore
commit: jest.fn(),
// @ts-ignore
dispatch: jest.fn(),
// @ts-ignore
...props
})
| import Vuex from 'vuex'
import { shallowMount, createLocalVue, Wrapper, ThisTypedShallowMountOptions } from '@vue/test-utils';
import Vue, { ComponentOptions } from 'vue';
export const mountMixin = <V extends Vue>(
component: ComponentOptions<V>,
mountOptions: ThisTypedShallowMountOptions<V> = {},
template = '<div />'
): Wrapper<V> => {
const localVue = createLocalVue();
localVue.use(Vuex);
return shallowMount({
template,
mixins: [component]
}, {
localVue,
...mountOptions
})
};
export const mountMixinWithStore = <V extends Vue>(
component: ComponentOptions<V>,
storeOptions: object = {},
mountOptions: ThisTypedShallowMountOptions<V> = {},
template = '<div />'
): Wrapper<V> => {
const localVue = createLocalVue();
localVue.use(Vuex);
const store = new Vuex.Store({
...storeOptions
});
return shallowMount({
template,
mixins: [component]
}, {
store,
localVue,
...mountOptions
})
};
export const createContextMock = (props = {}) => ({
// @ts-ignore
commit: jest.fn(),
// @ts-ignore
dispatch: jest.fn(),
// @ts-ignore
...props
})
|
Add ability to retrieve the index of an item in the PaperMenuComponent | // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as React from 'react';
import { PolymerComponent } from './polymer';
import { omitOwnProps } from '../../../common/utils';
/**
* React component that wraps a Polymer paper-menu custom element.
*/
export class PaperMenuComponent
extends PolymerComponent<PolymerElements.PaperMenu, PaperMenuComponent.IProps> {
protected get cssVars() {
const styles = this.props.styles;
const vars: any = {};
if (styles) {
if (styles.backgroundColor) {
vars['--paper-menu-background-color'] = styles.backgroundColor;
}
if (styles.textColor) {
vars['--paper-menu-color'] = styles.textColor;
}
}
return vars;
}
protected get eventBindings(): PolymerComponent.IEventBinding[] {
return [];
}
protected renderElement(props: PaperMenuComponent.IProps) {
const elementProps = omitOwnProps(props, ['styles']);
return (
<paper-menu {...elementProps}></paper-menu>
);
}
}
export namespace PaperMenuComponent {
export interface IProps extends PolymerComponent.IProps {
/** Sets the selected element, by default the value should be the index of a menu item. */
selected?: string | number;
styles?: {
backgroundColor?: string;
textColor?: string;
};
}
}
| // Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.
import * as React from 'react';
import { PolymerComponent } from './polymer';
import { omitOwnProps } from '../../../common/utils';
/**
* React component that wraps a Polymer paper-menu custom element.
*/
export class PaperMenuComponent
extends PolymerComponent<PolymerElements.PaperMenu, PaperMenuComponent.IProps> {
/** Returns the index of the given item. */
indexOf(item: PolymerElements.PaperItem): number {
return this.element.indexOf(item);
}
protected get cssVars() {
const styles = this.props.styles;
const vars: any = {};
if (styles) {
if (styles.backgroundColor) {
vars['--paper-menu-background-color'] = styles.backgroundColor;
}
if (styles.textColor) {
vars['--paper-menu-color'] = styles.textColor;
}
}
return vars;
}
protected get eventBindings(): PolymerComponent.IEventBinding[] {
return [];
}
protected renderElement(props: PaperMenuComponent.IProps) {
const elementProps = omitOwnProps(props, ['styles']);
return (
<paper-menu {...elementProps}></paper-menu>
);
}
}
export namespace PaperMenuComponent {
export interface IProps extends PolymerComponent.IProps {
/** Sets the selected element, by default the value should be the index of a menu item. */
selected?: string | number;
styles?: {
backgroundColor?: string;
textColor?: string;
};
}
}
|
Make book have verify true again when editing an existing one | import { createCollection } from '../../vulcan-lib';
import schema from './schema';
import { makeEditable } from '../../editor/make_editable';
import { addUniversalFields, getDefaultResolvers, getDefaultMutations } from '../../collectionUtils'
export const Books: BooksCollection = createCollection({
collectionName: 'Books',
typeName: 'Book',
schema,
resolvers: getDefaultResolvers('Books'),
mutations: getDefaultMutations('Books'),
});
export const makeEditableOptions = {
order: 20,
getLocalStorageId: (book, name) => {
if (book._id) { return {id: `${book._id}_${name}`, verify: false} }
return {id: `collection: ${book.collectionId}_${name}`, verify: false}
},
}
makeEditable({
collection: Books,
options: makeEditableOptions
})
addUniversalFields({collection: Books})
export default Books;
| import { createCollection } from '../../vulcan-lib';
import schema from './schema';
import { makeEditable } from '../../editor/make_editable';
import { addUniversalFields, getDefaultResolvers, getDefaultMutations } from '../../collectionUtils'
export const Books: BooksCollection = createCollection({
collectionName: 'Books',
typeName: 'Book',
schema,
resolvers: getDefaultResolvers('Books'),
mutations: getDefaultMutations('Books'),
});
export const makeEditableOptions = {
order: 20,
getLocalStorageId: (book, name) => {
if (book._id) { return {id: `${book._id}_${name}`, verify: true} }
return {id: `collection: ${book.collectionId}_${name}`, verify: false}
},
}
makeEditable({
collection: Books,
options: makeEditableOptions
})
addUniversalFields({collection: Books})
export default Books;
|
Print iOS Simulator device logs | ///<reference path="../../../.d.ts"/>
"use strict";
import {ApplicationManagerBase} from "../../application-manager-base";
import Future = require("fibers/future");
export class IOSSimulatorApplicationManager extends ApplicationManagerBase implements Mobile.IDeviceApplicationManager {
constructor(private iosSim: any,
private identifier: string) {
super();
}
public getInstalledApplications(): IFuture<string[]> {
return Future.fromResult(this.iosSim.getInstalledApplications(this.identifier));
}
public installApplication(packageFilePath: string): IFuture<void> {
return this.iosSim.installApplication(this.identifier, packageFilePath);
}
public uninstallApplication(appIdentifier: string): IFuture<void> {
return this.iosSim.uninstallApplication(this.identifier, appIdentifier);
}
public startApplication(appIdentifier: string): IFuture<void> {
return this.iosSim.startApplication(this.identifier, appIdentifier);
}
public stopApplication(cfBundleExecutable: string): IFuture<void> {
return this.iosSim.stopApplication(this.identifier, cfBundleExecutable);
}
public canStartApplication(): boolean {
return true;
}
}
| ///<reference path="../../../.d.ts"/>
"use strict";
import {ApplicationManagerBase} from "../../application-manager-base";
import Future = require("fibers/future");
export class IOSSimulatorApplicationManager extends ApplicationManagerBase implements Mobile.IDeviceApplicationManager {
constructor(private iosSim: any,
private identifier: string,
private $options: ICommonOptions) {
super();
}
private deviceLoggingStarted = false;
public getInstalledApplications(): IFuture<string[]> {
return Future.fromResult(this.iosSim.getInstalledApplications(this.identifier));
}
public installApplication(packageFilePath: string): IFuture<void> {
return this.iosSim.installApplication(this.identifier, packageFilePath);
}
public uninstallApplication(appIdentifier: string): IFuture<void> {
return this.iosSim.uninstallApplication(this.identifier, appIdentifier);
}
public startApplication(appIdentifier: string): IFuture<void> {
return (() => {
let launchResult = this.iosSim.startApplication(this.identifier, appIdentifier).wait();
if (!this.$options.justlaunch && !this.deviceLoggingStarted) {
this.deviceLoggingStarted = true;
this.iosSim.printDeviceLog(this.identifier, launchResult);
}
}).future<void>()();
}
public stopApplication(cfBundleExecutable: string): IFuture<void> {
return this.iosSim.stopApplication(this.identifier, cfBundleExecutable);
}
public canStartApplication(): boolean {
return true;
}
}
|
Add test for register/unregister in event class map. |
import {expect} from "chai";
import {EventClassMap} from "../../../main/Apha/EventStore/EventClassMap";
import {Event, EventType} from "../../../main/Apha/Message/Event";
import {UnknownEventException} from "../../../main/Apha/EventStore/UnknownEventException";
describe("EventClassMap", () => {
describe("getTypeByClassName", () => {
it("retrieves type by event class name", () => {
const events = new Set<EventType>();
events.add(EventClassMapEvent);
const classMap = new EventClassMap(events);
const classType = classMap.getTypeByClassName("EventClassMapEvent");
expect(classType).to.equal(EventClassMapEvent);
});
it("throws exception if class cannot be found", () => {
const classMap = new EventClassMap();
expect(() => {
classMap.getTypeByClassName("foo");
}).to.throw(UnknownEventException);
});
});
});
class EventClassMapEvent extends Event {}
|
import {expect} from "chai";
import {EventClassMap} from "../../../main/Apha/EventStore/EventClassMap";
import {Event, EventType} from "../../../main/Apha/Message/Event";
import {UnknownEventException} from "../../../main/Apha/EventStore/UnknownEventException";
describe("EventClassMap", () => {
describe("getTypeByClassName", () => {
it("should retrieve type by event class name", () => {
const events = new Set<EventType>();
events.add(EventClassMapEvent);
const classMap = new EventClassMap(events);
const classType = classMap.getTypeByClassName("EventClassMapEvent");
expect(classType).to.equal(EventClassMapEvent);
});
it("should throw exception if class cannot be found", () => {
const classMap = new EventClassMap();
expect(() => {
classMap.getTypeByClassName("foo");
}).to.throw(UnknownEventException);
});
});
describe("register", () => {
it("should register an event in the map", () => {
const classMap = new EventClassMap();
classMap.register(EventClassMapEvent);
expect(classMap.getTypeByClassName("EventClassMapEvent")).to.equal(EventClassMapEvent);
});
});
describe("unregister", () => {
it("should unregister an event from the map", () => {
const classMap = new EventClassMap();
classMap.register(EventClassMapEvent);
classMap.unregister(EventClassMapEvent);
expect(() => {
classMap.getTypeByClassName("EventClassMapEvent");
}).to.throw(UnknownEventException);
});
it("should be idempotent", () => {
const classMap = new EventClassMap();
expect(() => {
classMap.unregister(EventClassMapEvent);
}).to.not.throw();
});
});
});
class EventClassMapEvent extends Event {}
|
Fix the args array where config should be added | 'use strict';
import {ChildProcess, spawn} from 'child_process';
import {ProjectWorkspace} from './project_workspace';
/**
* Spawns and returns a Jest process with specific args
*
* @param {string[]} args
* @returns {ChildProcess}
*/
export function jestChildProcessWithArgs(workspace: ProjectWorkspace, args: string[]) : ChildProcess {
// A command could look like `npm run test`, which we cannot use as a command
// as they can only be the first command, so take out the command, and add
// any other bits into the args
const runtimeExecutable = workspace.pathToJest;
const [command, ...initialArgs] = runtimeExecutable.split(" ");
const runtimeArgs = [...initialArgs, ...args];
// If a path to configuration file was defined, push it to runtimeArgs
const configPath = workspace.pathToConfig;
if (configPath !== "") {
args.push("--config");
args.push(configPath);
}
// To use our own commands in create-react, we need to tell the command that we're in a CI
// environment, or it will always append --watch
const env = process.env;
env["CI"] = true;
return spawn(command, runtimeArgs, {cwd: workspace.rootPath, env: env});
} | 'use strict';
import {ChildProcess, spawn} from 'child_process';
import {ProjectWorkspace} from './project_workspace';
/**
* Spawns and returns a Jest process with specific args
*
* @param {string[]} args
* @returns {ChildProcess}
*/
export function jestChildProcessWithArgs(workspace: ProjectWorkspace, args: string[]) : ChildProcess {
// A command could look like `npm run test`, which we cannot use as a command
// as they can only be the first command, so take out the command, and add
// any other bits into the args
const runtimeExecutable = workspace.pathToJest;
const [command, ...initialArgs] = runtimeExecutable.split(" ");
const runtimeArgs = [...initialArgs, ...args];
// If a path to configuration file was defined, push it to runtimeArgs
const configPath = workspace.pathToConfig;
if (configPath !== "") {
runtimeArgs.push("--config");
runtimeArgs.push(configPath);
}
// To use our own commands in create-react, we need to tell the command that we're in a CI
// environment, or it will always append --watch
const env = process.env;
env["CI"] = true;
return spawn(command, runtimeArgs, {cwd: workspace.rootPath, env: env});
} |
Make useMiddlewares accept logger as an argument | import { Middleware } from '../index'
import { Logger } from '../utils/logger'
import { argsParser } from './argsParser'
import { commandCaller } from './commandCaller'
import { commandFinder } from './commandFinder'
import { errorsHandler } from './errorsHandler'
import { helper } from './helper'
import { rawArgsParser } from './rawArgsParser'
import { validator } from './validator'
export function useMiddlewares(middlewares: Middleware[] = []) {
const logger = new Logger()
const argv = process.argv
return [
errorsHandler(logger),
argsParser(argv),
commandFinder,
helper(logger),
validator,
rawArgsParser(argv),
...middlewares,
commandCaller
]
}
| import { Middleware } from '../index'
import { Logger } from '../utils/logger'
import { argsParser } from './argsParser'
import { commandCaller } from './commandCaller'
import { commandFinder } from './commandFinder'
import { errorsHandler } from './errorsHandler'
import { helper } from './helper'
import { rawArgsParser } from './rawArgsParser'
import { validator } from './validator'
export function useMiddlewares(
middlewares: Middleware[] = [],
logger = new Logger()
) {
const argv = process.argv
return [
errorsHandler(logger),
argsParser(argv),
commandFinder,
helper(logger),
validator,
rawArgsParser(argv),
...middlewares,
commandCaller
]
}
|
Clarify the exact version of a file that is pulled from nteract | /* tslint:disable */
'use strict';
// THis code is from @nteract/transforms-full except without the Vega transforms
// https://github.com/nteract/nteract/blob/master/packages/transforms-full/src/index.js
// Vega transforms mess up our npm pkg install because they rely on the npm canvas module that needs
// to be built on each system.
import PlotlyTransform, {
PlotlyNullTransform
} from "@nteract/transform-plotly";
import GeoJSONTransform from "@nteract/transform-geojson";
import ModelDebug from "@nteract/transform-model-debug";
import DataResourceTransform from "@nteract/transform-dataresource";
// import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega";
import {
standardTransforms,
standardDisplayOrder,
registerTransform,
richestMimetype
} from "@nteract/transforms";
const additionalTransforms = [
DataResourceTransform,
ModelDebug,
PlotlyNullTransform,
PlotlyTransform,
GeoJSONTransform,
];
const { transforms, displayOrder } = additionalTransforms.reduce(
registerTransform,
{
transforms: standardTransforms,
displayOrder: standardDisplayOrder
}
);
export { displayOrder, transforms, richestMimetype, registerTransform };
| /* tslint:disable */
'use strict';
// This code is from @nteract/transforms-full except without the Vega transforms:
// https://github.com/nteract/nteract/blob/v0.12.2/packages/transforms-full/src/index.js .
// Vega transforms mess up our npm pkg install because they rely on the npm canvas module that needs
// to be built on each system.
import PlotlyTransform, {
PlotlyNullTransform
} from "@nteract/transform-plotly";
import GeoJSONTransform from "@nteract/transform-geojson";
import ModelDebug from "@nteract/transform-model-debug";
import DataResourceTransform from "@nteract/transform-dataresource";
// import { VegaLite1, VegaLite2, Vega2, Vega3 } from "@nteract/transform-vega";
import {
standardTransforms,
standardDisplayOrder,
registerTransform,
richestMimetype
} from "@nteract/transforms";
const additionalTransforms = [
DataResourceTransform,
ModelDebug,
PlotlyNullTransform,
PlotlyTransform,
GeoJSONTransform,
];
const { transforms, displayOrder } = additionalTransforms.reduce(
registerTransform,
{
transforms: standardTransforms,
displayOrder: standardDisplayOrder
}
);
export { displayOrder, transforms, richestMimetype, registerTransform };
|
Fix url parser warning during tests | import {UserSchema, IUserModel} from "../../src/server/data/User";
import {GameSchema, IGameModel} from "../../src/server/data/GameModel";
import mongoose from "mongoose";
import assert from "assert";
const connectionString = "mongodb://localhost/test"
const User = mongoose.model("User", UserSchema) as IUserModel;
const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel;
describe("User", () => {
beforeEach(async () => {
await mongoose.connect(connectionString);
await mongoose.connection.db.dropDatabase()
});
afterEach(async () => {
await mongoose.disconnect()
})
describe("findOrCreate", () => {
it("should create user", async () => {
await User.findOrCreate("M4T4L4");
const users = await User.find().exec();
assert.equal(1, users.length, "users");
});
});
describe("addGame", () => {
it("should add game for logged in user", async () => {
const facebookId = "M4T4L4"
let user = await User.findOrCreate(facebookId);
const doc = await GameModel.findOrCreate("P3L1")
await User.addGame(user._id, doc.title);
user = await User.findOne({facebookId}).exec();
assert.equal(user.games.length, 1, "added game");
assert.equal(user.games[0], "P3L1", "game title");
});
});
});
| import {UserSchema, IUserModel} from "../../src/server/data/User";
import {GameSchema, IGameModel} from "../../src/server/data/GameModel";
import mongoose from "mongoose";
import assert from "assert";
const connectionString = "mongodb://localhost:27017/test"
const User = mongoose.model("User", UserSchema) as IUserModel;
const GameModel = mongoose.model("GameModel", GameSchema) as IGameModel;
describe("User", () => {
beforeEach(async () => {
await mongoose.connect(connectionString, {useNewUrlParser: true});
await mongoose.connection.db.dropDatabase()
});
afterEach(async () => {
await mongoose.disconnect()
})
describe("findOrCreate", () => {
it("should create user", async () => {
await User.findOrCreate("M4T4L4");
const users = await User.find().exec();
assert.equal(1, users.length, "users");
});
});
describe("addGame", () => {
it("should add game for logged in user", async () => {
const facebookId = "M4T4L4"
let user = await User.findOrCreate(facebookId);
const doc = await GameModel.findOrCreate("P3L1")
await User.addGame(user._id, doc.title);
user = await User.findOne({facebookId}).exec();
assert.equal(user.games.length, 1, "added game");
assert.equal(user.games[0], "P3L1", "game title");
});
});
});
|
Change import * to require to align with tests | // Type definitions for fastify-static 0.14
// Project: https://github.com/fastify/fastify-static
// Definitions by: Leonhard Melzer <https://github.com/leomelzer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { Server, IncomingMessage, ServerResponse } from "http";
import * as fastify from "fastify";
declare module "fastify" {
interface FastifyReply<HttpResponse> {
sendFile(filename: string): FastifyReply<HttpResponse>;
}
}
declare function fastifyStatic(): void;
declare namespace fastifyStatic {
interface FastifyStaticOptions {
root: string;
prefix?: string;
serve?: boolean;
decorateReply?: boolean;
schemaHide?: boolean;
setHeaders?: () => void;
// Passed on to `send`
acceptRanges?: boolean;
cacheControl?: boolean;
dotfiles?: boolean;
etag?: boolean;
extensions?: string[];
immutable?: boolean;
index?: string[];
lastModified?: boolean;
maxAge?: string | number;
}
}
export = fastifyStatic;
| // Type definitions for fastify-static 0.14
// Project: https://github.com/fastify/fastify-static
// Definitions by: Leonhard Melzer <https://github.com/leomelzer>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import fastify = require("fastify");
import { Server, IncomingMessage, ServerResponse } from "http";
declare module "fastify" {
interface FastifyReply<HttpResponse> {
sendFile(filename: string): FastifyReply<HttpResponse>;
}
}
declare function fastifyStatic(): void;
declare namespace fastifyStatic {
interface FastifyStaticOptions {
root: string;
prefix?: string;
serve?: boolean;
decorateReply?: boolean;
schemaHide?: boolean;
setHeaders?: () => void;
// Passed on to `send`
acceptRanges?: boolean;
cacheControl?: boolean;
dotfiles?: boolean;
etag?: boolean;
extensions?: string[];
immutable?: boolean;
index?: string[];
lastModified?: boolean;
maxAge?: string | number;
}
}
export = fastifyStatic;
|
Change a check that caused Typescript errors | import { BaseApp, HandleRequest, Plugin, PluginConfig } from 'jovo-core';
import _merge = require('lodash.merge');
import PulseLabsRecorder = require('pulselabs-recorder');
import { InitOptions } from 'pulselabs-recorder/dist/interfaces/init-options.interface'; // tslint:disable-line
export interface Config extends PluginConfig {
apiKey: string;
options?: InitOptions;
}
export class PulseLabs implements Plugin {
config: Config = {
apiKey: '',
options: {
debug: false,
timeout: 2000,
},
};
pulse: PulseLabsRecorder;
constructor(config?: Config) {
if (config) {
this.config = _merge(this.config, config);
}
const initOptions = { ...this.config.options, integrationType: 'Jovo' };
this.pulse = PulseLabsRecorder.init(this.config.apiKey, initOptions as InitOptions);
}
install(app: BaseApp) {
app.on('after.response', this.logData.bind(this));
}
async logData(handleRequest: HandleRequest) {
if (handleRequest.jovo!.$alexaSkill) {
await this.pulse.logData(handleRequest.jovo!.$request, handleRequest.jovo!.$response);
} else if (handleRequest.jovo!.$googleAction) {
await this.pulse.logGoogleData(
handleRequest.jovo!.$request,
handleRequest.jovo!.$response,
handleRequest.jovo!.$user.getId(),
);
}
}
}
| import { BaseApp, HandleRequest, Plugin, PluginConfig } from 'jovo-core';
import _merge = require('lodash.merge');
import PulseLabsRecorder = require('pulselabs-recorder');
import { InitOptions } from 'pulselabs-recorder/dist/interfaces/init-options.interface'; // tslint:disable-line
export interface Config extends PluginConfig {
apiKey: string;
options?: InitOptions;
}
export class PulseLabs implements Plugin {
config: Config = {
apiKey: '',
options: {
debug: false,
timeout: 2000,
},
};
pulse: PulseLabsRecorder;
constructor(config?: Config) {
if (config) {
this.config = _merge(this.config, config);
}
const initOptions = { ...this.config.options, integrationType: 'Jovo' };
this.pulse = PulseLabsRecorder.init(this.config.apiKey, initOptions as InitOptions);
}
install(app: BaseApp) {
app.on('after.response', this.logData.bind(this));
}
async logData(handleRequest: HandleRequest) {
if (handleRequest.jovo.constructor.name === 'AlexaSkill') {
await this.pulse.logData(handleRequest.jovo!.$request, handleRequest.jovo!.$response);
} else if (handleRequest.jovo.constructor.name === 'GoogleAction') {
await this.pulse.logGoogleData(
handleRequest.jovo!.$request,
handleRequest.jovo!.$response,
handleRequest.jovo!.$user.getId(),
);
}
}
}
|
Fix name for service unit test | /* beautify ignore:start */
import {
it,
inject,
//injectAsync,
beforeEachProviders
//TestComponentBuilder
} from 'angular2/testing';
import {<%=servicenameClass%>Service} from './<%=servicenameFile%>.service.ts';
/* beautify ignore:end */
describe('Service: <%=servicename%>' , () => {
beforeEachProviders(() => [<%=servicenameClass %>Service]);
it('should be defined', inject([<%=servicenameClass %>Service], (service: <%=servicenameClass %>Service) => {
expect(service).toBeDefined();
}));
}); | /* beautify ignore:start */
import {
it,
inject,
//injectAsync,
beforeEachProviders
//TestComponentBuilder
} from 'angular2/testing';
import {<%=servicenameClass%>Service} from './<%=servicenameFile%>.service.ts';
/* beautify ignore:end */
describe('Service: <%=servicenameClass%>Service' , () => {
beforeEachProviders(() => [<%=servicenameClass %>Service]);
it('should be defined', inject([<%=servicenameClass %>Service], (service: <%=servicenameClass %>Service) => {
expect(service).toBeDefined();
}));
}); |
Remove get-started because we have it on the landing page | import { program } from "commander";
import { version } from "../package.json";
program.version(version);
console.log("Hello en3", version); | import { program } from "commander";
import { version } from "../package.json";
program.version(version);
console.log("Hello en5", version); |
Remove redundant method in FileContainer | import { BasicFileContainer } from "./basicFileContainer";
import * as common from "./common";
import * as utils from "../common/utils";
import * as view from "../view/common";
export class FileContainer extends BasicFileContainer {
constructor() {
super();
}
getDescriptorsAll(): view.FileStageQuickPick[] {
let descriptors: view.FileStageQuickPick[] = [];
for (let status in common.GitStatus) {
let files = this.getByType([common.GitStatus.MODIFIED]);
for (let i in files) {
descriptors.push({
label: files[i].path,
path: files[i].path,
description: status
});
}
}
return descriptors;
}
getDescriptorsByType(type: common.GitStatus[]): view.FileStageQuickPick[] {
let descriptors: view.FileStageQuickPick[] = [];
for (let status in type) {
let files = this.getByType([type[status]]);
for (let i in files) {
descriptors.push({
label: files[i].path,
path: files[i].path,
description: status
});
}
}
return descriptors;
}
isDirty(): boolean {
return this.lengthOfType([common.GitStatus.MODIFIED, common.GitStatus.DELETED]) !== 0;
}
}
| import { BasicFileContainer } from "./basicFileContainer";
import * as common from "./common";
import * as utils from "../common/utils";
import * as view from "../view/common";
export class FileContainer extends BasicFileContainer {
constructor() {
super();
}
getDescriptorsAll(): view.FileStageQuickPick[] {
let descriptors: view.FileStageQuickPick[] = [];
for (let status in common.GitStatus) {
let files = this.getByType([common.GitStatus.MODIFIED]);
for (let i in files) {
descriptors.push({
label: files[i].path,
path: files[i].path,
description: status
});
}
}
return descriptors;
}
getDescriptorsByType(type: common.GitStatus[]): view.FileStageQuickPick[] {
let descriptors: view.FileStageQuickPick[] = [];
for (let status in type) {
let files = this.getByType([type[status]]);
for (let i in files) {
descriptors.push({
label: files[i].path,
path: files[i].path,
description: status
});
}
}
return descriptors;
}
}
|
Add emoji to request for contribution in fallback tutorial | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs
} from './helpers/helpers'
import { ChallengeInstruction } from './'
export const TutorialUnavailableInstruction: ChallengeInstruction = {
name: null,
hints: [
{
text:
"😓 Sorry, this hacking challenge does not have a step-by-step tutorial (yet) ... 🧭 Can you find your own way to solve it?",
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
"Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how!",
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
"And now: 👾 **GLHF** with this challenge! ",
fixture: 'app-navbar',
resolved: waitInMs(10000)
}
]
}
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import {
waitInMs
} from './helpers/helpers'
import { ChallengeInstruction } from './'
export const TutorialUnavailableInstruction: ChallengeInstruction = {
name: null,
hints: [
{
text:
"😓 Sorry, this hacking challenge does not have a step-by-step tutorial (yet) ... 🧭 Can you find your own way to solve it?",
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
"✍️ Do you want to contribute a tutorial for this challenge? [Check out our documentation](https://pwning.owasp-juice.shop/part3/tutorials.html) to learn how! 🏫",
fixture: 'app-navbar',
resolved: waitInMs(15000)
},
{
text:
"And now: 👾 **GLHF** with this challenge! ",
fixture: 'app-navbar',
resolved: waitInMs(10000)
}
]
}
|
FIx for copy paste errors | import { Minion } from './minion.model';
///This is a repo class for the various minions that can be hired for a warband.
export class EquipmentVault {
public static items = new Array<Minion>();
constructor(){
}
static loadMinionTemplatesIntoVault(){
var minion = new Minion('War Dog');
minion.move = 8;
minion.fight = 1;
minion.shoot = 0;
minion.armor = 10;
minion.will = 2;
minion.health = 8
minion.cost = 10;
minion.notes = "Animal, Cannot carry items"
}
}
| import { Minion } from './minion.model';
///This is a repo class for the various minions that can be hired for a warband.
export class WarbandVault {
public static templates = new Array<Minion>();
constructor(){
}
static loadMinionTemplatesIntoVault(){
var minion = new Minion('War Dog');
minion.move = 8;
minion.fight = 1;
minion.shoot = 0;
minion.armor = 10;
minion.will = 2;
minion.health = 8
minion.cost = 10;
minion.notes = "Animal, Cannot carry items"
this.templates.push(minion);
}
}
|
Send usage as a notice | export class Plugin {
bot: any;
commands: any;
constructor(bot : any) {
this.bot = bot;
this.commands = {
'lmgtfy': 'onCommandLmgtfy'
};
this.querystring = require('querystring');
}
onCommandLmgtfy(from: string, to: string, message: string, args: Array<string>) {
if (args.length < 2) {
return this.usage(from, to);
}
var query = this.querystring.stringify({ q : args.splice(1).join(' ') });
this.bot.reply(from, to, 'http://lmgtfy.com/?'+query);
}
usage(from: string, to:string) {
this.bot.reply(from, to, 'Usage: .lmgtfy How is babby formed');
}
}
| export class Plugin {
bot: any;
commands: any;
constructor(bot : any) {
this.bot = bot;
this.commands = {
'lmgtfy': 'onCommandLmgtfy'
};
this.querystring = require('querystring');
}
onCommandLmgtfy(from: string, to: string, message: string, args: Array<string>) {
if (args.length < 2) {
return this.usage(from, to);
}
var query = this.querystring.stringify({ q : args.splice(1).join(' ') });
this.bot.reply(from, to, 'http://lmgtfy.com/?'+query);
}
usage(from: string, to:string) {
this.bot.reply(from, to, 'Usage: .lmgtfy <query>', 'notice');
}
}
|
Fix for showing wms layers | module csComp.Services {
'use strict';
export class WmsSource implements ILayerSource
{
title = "wms";
service : LayerService;
init(service : LayerService){
this.service = service;
}
public addLayer(layer : ProjectLayer, callback : Function)
{
var wms : any = L.tileLayer.wms(layer.url, {
layers : layer.wmsLayers,
opacity : layer.opacity/100,
format : 'image/png',
transparent: true,
attribution: layer.description
});
callback(layer);
//this.$rootScope.$apply();
}
removeLayer(layer : ProjectLayer)
{
}
}
}
| module csComp.Services {
'use strict';
export class WmsSource implements ILayerSource
{
title = "wms";
service : LayerService;
init(service : LayerService){
this.service = service;
}
public addLayer(layer : ProjectLayer, callback : Function)
{
var wms : any = L.tileLayer.wms(layer.url, {
layers : layer.wmsLayers,
opacity : layer.opacity/100,
format : 'image/png',
transparent: true,
attribution: layer.description
});
layer.layerRenderer = "wms";
callback(layer);
//this.$rootScope.$apply();
}
removeLayer(layer : ProjectLayer)
{
}
}
}
|
Handle promise rejection in ItemSwitch | export abstract class ItemSwitch<T> {
protected loadMoreItems: Function;
public setLoadMoreItemsCallback(loadMoreItems?: () => Promise<T[]>) {
this.loadMoreItems = loadMoreItems;
}
public showPreviousItem(items: T[]) {
this.showItem(items, -1);
}
public showNextItem(items: T[]) {
this.showItem(items, 1);
}
protected showItem(items: T[], modifier: number): void {
let currentItemIndex = this.getCurrentItemIndex(items);
if (currentItemIndex !== null) {
let nextItemIndex = currentItemIndex + modifier;
if (this.loadMoreItems && this.moreItemsNeeded(items, currentItemIndex,
nextItemIndex)) {
this.loadMoreItems().then(updatedItems => {
this.switchToItem(updatedItems[nextItemIndex]);
});
}
if (nextItemIndex > -1 && nextItemIndex < items.length) {
this.switchToItem(items[nextItemIndex]);
}
}
}
protected abstract getCurrentItemIndex(items: T[]): number;
protected abstract moreItemsNeeded(items: T[], currentItemIndex: number,
nextItemIndex: number): boolean;
protected abstract switchToItem(item: T): void;
}
| export abstract class ItemSwitch<T> {
protected loadMoreItems: Function;
public setLoadMoreItemsCallback(loadMoreItems?: () => Promise<T[]>) {
this.loadMoreItems = loadMoreItems;
}
public showPreviousItem(items: T[]) {
this.showItem(items, -1);
}
public showNextItem(items: T[]) {
this.showItem(items, 1);
}
protected showItem(items: T[], modifier: number): void {
let currentItemIndex = this.getCurrentItemIndex(items);
if (currentItemIndex !== null) {
let nextItemIndex = currentItemIndex + modifier;
if (this.loadMoreItems && this.moreItemsNeeded(items, currentItemIndex,
nextItemIndex)) {
this.loadMoreItems().then(updatedItems => {
this.switchToItem(updatedItems[nextItemIndex]);
}).catch(() => {});
}
if (nextItemIndex > -1 && nextItemIndex < items.length) {
this.switchToItem(items[nextItemIndex]);
}
}
}
protected abstract getCurrentItemIndex(items: T[]): number;
protected abstract moreItemsNeeded(items: T[], currentItemIndex: number,
nextItemIndex: number): boolean;
protected abstract switchToItem(item: T): void;
}
|
Replace a TODO that is now done with a doc comment instead :) | import logger from './logging/logger'
// TODO(tec27): Move this to a more common location
export class JsonLocalStorageValue<T> {
constructor(readonly name: string) {}
/**
* Retrieves the current `localStorage` value (parsed as JSON).
* @returns the parsed value, or `undefined` if it isn't set or fails to parse.
*/
getValue(): T | undefined {
const valueJson = localStorage.getItem(this.name)
if (valueJson === null) {
return undefined
}
try {
return JSON.parse(valueJson)
} catch (err) {
logger.error(`error parsing value for ${this.name}: ${(err as any).stack ?? err}`)
return undefined
}
}
/**
* Sets the current `localStorage` value, encoding it as JSON.
*/
setValue(value: T): void {
localStorage.setItem(this.name, JSON.stringify(value))
}
/**
* Clears (unsets) the current `localStorage` value.
*/
clear(): void {
localStorage.removeItem(this.name)
}
}
| import logger from './logging/logger'
/**
* A manager for a JSON value stored in local storage. Provides easy methods to set and retrieve
* the value (if any), doing the necessary parsing/encoding.
*/
export class JsonLocalStorageValue<T> {
constructor(readonly name: string) {}
/**
* Retrieves the current `localStorage` value (parsed as JSON).
* @returns the parsed value, or `undefined` if it isn't set or fails to parse.
*/
getValue(): T | undefined {
const valueJson = localStorage.getItem(this.name)
if (valueJson === null) {
return undefined
}
try {
return JSON.parse(valueJson)
} catch (err) {
logger.error(`error parsing value for ${this.name}: ${(err as any).stack ?? err}`)
return undefined
}
}
/**
* Sets the current `localStorage` value, encoding it as JSON.
*/
setValue(value: T): void {
localStorage.setItem(this.name, JSON.stringify(value))
}
/**
* Clears (unsets) the current `localStorage` value.
*/
clear(): void {
localStorage.removeItem(this.name)
}
}
|
Remove --dry-run to try for real. | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string): string {
const result: any = exec(command);
return result.stdout.trim().replace("\r\n", "\n");
}
const currentBranch = cmd("git rev-parse --abbrev-ref HEAD");
if (currentBranch !== "master") {
throw new Error("This script should only be run on master. You're on " + currentBranch);
}
const changes = cmd("git status --porcelain");
if (changes) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpilation/deploy.ts" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
const trackedFiles = cmd("git ls-files").split("\n");
const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) === -1)
toRemove.forEach(f => cmd(`git rm -rf ${f} --dry-run`));
// cmd("git rm -rf * --dry-run");
toDeploy.forEach(f => cmd(`git add ${f}`));
console.log(cmd("git status")); | import fs = require("fs");
import { exec } from "shelljs";
function cmd(command: string): string {
const result: any = exec(command);
return result.stdout.trim().replace("\r\n", "\n");
}
const currentBranch = cmd("git rev-parse --abbrev-ref HEAD");
if (currentBranch !== "master") {
throw new Error("This script should only be run on master. You're on " + currentBranch);
}
const changes = cmd("git status --porcelain");
if (changes) {
throw new Error("This script shouldn't be run when you've got working copy changes.");
}
cmd("git branch -f gh-pages");
cmd("git checkout gh-pages");
const toDeploy = [ "index.html", "dist/slime.js", ".gitignore", "transpilation/deploy.ts" ];
const gitignore = ["*"].concat(toDeploy.map(f => "!" + f)).join("\r\n");
fs.writeFileSync(".gitignore", gitignore, "utf8");
const trackedFiles = cmd("git ls-files").split("\n");
const toRemove = trackedFiles.filter(f => toDeploy.indexOf(f) === -1)
toRemove.forEach(f => cmd(`git rm -rf ${f}`));
toDeploy.forEach(f => cmd(`git add ${f}`));
console.log(cmd("git status")); |
Select default time period filter selection via RadioGroup instead of Radio | import React from "react"
import { FilterState } from "../../FilterState"
import { Radio, RadioGroup } from "@artsy/palette"
export const TimePeriodFilter: React.SFC<{
filters: FilterState
timePeriods?: string[]
}> = ({ filters, timePeriods }) => {
const periods = (timePeriods || allowedPeriods).filter(timePeriod =>
allowedPeriods.includes(timePeriod)
)
const radioButtons = periods.map((timePeriod, index) => {
const isSelected = filters.state.major_periods[0] === timePeriod
return (
<Radio
my={0.3}
selected={isSelected}
value={timePeriod}
key={index}
label={timePeriod}
/>
)
})
return (
<RadioGroup
deselectable
onSelect={selectedOption => {
filters.setFilter("major_periods", selectedOption)
}}
>
{radioButtons}
</RadioGroup>
)
}
const allowedPeriods = [
"2010",
"2000",
"1990",
"1980",
"1970",
"1960",
"1950",
"1940",
"1930",
"1920",
"1910",
"1900",
"Late 19th Century",
"Mid 19th Century",
"Early 19th Century",
]
| import React from "react"
import { FilterState } from "../../FilterState"
import { Radio, RadioGroup } from "@artsy/palette"
import { get } from "Utils/get"
export const TimePeriodFilter: React.SFC<{
filters: FilterState
timePeriods?: string[]
}> = ({ filters, timePeriods }) => {
const periods = (timePeriods || allowedPeriods).filter(timePeriod =>
allowedPeriods.includes(timePeriod)
)
const defaultValue = get(filters.state, x => x.major_periods[0], "")
const radioButtons = periods.map((timePeriod, index) => {
return <Radio my={0.3} value={timePeriod} key={index} label={timePeriod} />
})
return (
<RadioGroup
deselectable
onSelect={selectedOption => {
filters.setFilter("major_periods", selectedOption)
}}
defaultValue={defaultValue}
>
{radioButtons}
</RadioGroup>
)
}
const allowedPeriods = [
"2010",
"2000",
"1990",
"1980",
"1970",
"1960",
"1950",
"1940",
"1930",
"1920",
"1910",
"1900",
"Late 19th Century",
"Mid 19th Century",
"Early 19th Century",
]
|
Fix error when no languages given | import hljs from 'highlight.js/lib/highlight';
import { HLJSLang } from '../types';
/**
* Register Highlight.js languages.
*
* @export
* @param {Record<string, HLJSLang>} languages Highlight.js languages
*/
export default function registerLanguages(
languages: Record<string, HLJSLang>
): void {
Object.keys(languages).forEach(languageName => {
const language = languages[languageName];
hljs.registerLanguage(languageName, language);
});
}
| import hljs from 'highlight.js/lib/highlight';
import { HLJSLang } from '../types';
/**
* Register Highlight.js languages.
*
* @export
* @param {Record<string, HLJSLang>} languages Highlight.js languages
*/
export default function registerLanguages(
languages: Record<string, HLJSLang>
): void {
if (typeof languages !== 'object') {
return;
}
Object.keys(languages).forEach(languageName => {
const language = languages[languageName];
hljs.registerLanguage(languageName, language);
});
}
|
Add comment describing caveats of the Vue3 plugin | import { Client, InitConfig } from '@jovotech/client-web';
import { Plugin, reactive, ref } from 'vue';
declare global {
interface Window {
JovoWebClientVue?: typeof import('.');
}
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: InitConfig;
}
const plugin: Plugin = {
install: (app, config) => {
if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
// this is probably not working because the new reactivity system of vue is much worse in v3
app.config.globalProperties.$client = reactive(new Client(config.url, config.client));
},
};
export default plugin;
export * from '@jovotech/client-web';
| import { Client, InitConfig } from '@jovotech/client-web';
import { Plugin, reactive, ref } from 'vue';
declare global {
interface Window {
JovoWebClientVue?: typeof import('.');
}
}
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$client: Client;
}
}
export interface JovoWebClientVueConfig {
url: string;
client?: InitConfig;
}
const plugin: Plugin = {
install: (app, config) => {
if (!config?.url) {
throw new Error(
`At least the 'url' option has to be set in order to use the JovoWebClientPlugin. `,
);
}
// Issue: It seems like it is impossible to attach reactive data to jovo from a plugin.
// This means that compared to the vue2-variant, this will require workarounds to use properties of the client.
// Another solution would be to simply add the client to the data of the Root-component and provide it from there.
// This would fix the reactivity issue.
app.config.globalProperties.$client = reactive(new Client(config.url, config.client));
},
};
export default plugin;
export * from '@jovotech/client-web';
|
Add export default object literal usage | /**
* Size of the ball, in cm.
*/
enum BallSize {
ThrityEight = 0.38,
Fourty = 0.4,
FourtyPlus = 0.4025,
FourtyFour = 0.44
}
export default BallSize; | // define as object literal for demo purpose
/**
* Size of the ball, in cm.
*/
var BallSize = {
ThrityEight: 0.38,
Fourty: 0.4,
FourtyPlus: 0.4025,
FourtyFour: 0.44
}
export default BallSize; |
Add query element to make fake data a little bit more dynamic | // https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client
import {Injectable, Inject} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class MainService {
constructor(@Inject(Http) private http) { }
private _serviceUrl = 'http://www.youtubeinmp3.com/fetch/?format=JSON&video=';
getFakeElements(query: string) {
return new Observable(observer =>
observer.next(['Element 1', 'Element 2', 'Element 3'])).share();
}
getMusicLink(videoUrl: string) {
return this.http.get(this._serviceUrl + videoUrl)
.map(res => res.text())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
} | // https://angular.io/docs/ts/latest/guide/server-communication.html#!#http-client
import {Injectable, Inject} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class MainService {
constructor(@Inject(Http) private http) { }
private _serviceUrl = 'http://www.youtubeinmp3.com/fetch/?format=JSON&video=';
getFakeElements(query: string) {
return new Observable(observer =>
observer.next(['Query: ' + query, 'Element 1', 'Element 2', 'Element 3'])).share();
}
getMusicLink(videoUrl: string) {
return this.http.get(this._serviceUrl + videoUrl)
.map(res => res.text())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
} |
Use search service and analytics service | import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
categories = [
{value: 'All'},
{value: 'Data sources'},
{value: 'Facilities'},
{value: 'Guides'},
{value: 'Instrument'},
{value: 'Knowledge articles'},
{value: 'People'},
{value: 'Policies'},
{value: 'Software'},
{value: 'Training'},
{value: 'Services'}
];
searchTextValue;
categoryValue;
@Output() searchTextChange = new EventEmitter();
@Output() categoryChange = new EventEmitter();
constructor() {
}
ngOnInit() {
}
@Input()
get searchText() {
return this.searchTextValue;
}
@Input()
get category() {
return this.categoryValue;
}
set searchText(val) {
this.searchTextValue = val;
this.searchTextChange.emit(val);
}
set category(val) {
this.categoryValue = val;
this.categoryChange.emit(val);
}
}
| import {Component, EventEmitter, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {AnalyticsService} from '../app.analytics.service';
import {SearchService} from '../app.search.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
categories = [
{value: 'All'},
{value: 'Data sources'},
{value: 'Facilities'},
{value: 'Guides'},
{value: 'Instrument'},
{value: 'Knowledge articles'},
{value: 'People'},
{value: 'Policies'},
{value: 'Software'},
{value: 'Training'},
{value: 'Services'}
];
searchTextValue;
categoryValue;
@Output() searchTextChange = new EventEmitter();
@Output() categoryChange = new EventEmitter();
searchTextSubject: Subject<String> = new Subject();
constructor(private analyticsService: AnalyticsService, private searchService: SearchService) {
}
ngOnInit() {
this.searchTextSubject.debounceTime(1000).subscribe((searchText) => this.analyticsService.trackSearch(this.categoryValue, searchText));
}
@Input()
get searchText() {
return this.searchTextValue;
}
@Input()
get category() {
return this.categoryValue;
}
set searchText(val) {
this.searchTextValue = val;
this.searchTextChange.emit(val);
this.searchTextSubject.next(val);
this.searchService.setSearchText(val);
}
set category(val) {
this.categoryValue = val;
this.categoryChange.emit(val);
this.searchService.setSearchCategory(val);
}
}
|
Drop switchMap from the operators used | // import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap'; | // import 'rxjs/Rx'; // adds ALL RxJS statics & operators to Observable
// See node_module/rxjs/Rxjs.js
// Import just the rxjs statics and operators we need for THIS app.
// Statics
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
|
Fix child_process imported as default import | import { createConnection } from 'net';
import child from 'child_process';
import { NeovimClient } from './../api/client';
import { logger } from '../utils/logger';
export interface Attach {
reader?: NodeJS.ReadableStream;
writer?: NodeJS.WritableStream;
proc?: NodeJS.Process | child.ChildProcess;
socket?: string;
}
export function attach({
reader: _reader,
writer: _writer,
proc,
socket,
}: Attach) {
let writer;
let reader;
logger.debug('proc');
logger.debug(proc);
if (socket) {
const client = createConnection(socket);
writer = client;
reader = client;
} else if (_reader && _writer) {
writer = _writer;
reader = _reader;
} else if (proc) {
writer = proc.stdin;
reader = proc.stdout;
}
if (writer && reader) {
const neovim = new NeovimClient({ logger });
neovim.attachSession({
writer,
reader,
});
return neovim;
}
throw new Error('Invalid arguments, could not attach');
}
| import { createConnection } from 'net';
import * as child from 'child_process';
import { NeovimClient } from './../api/client';
import { logger } from '../utils/logger';
export interface Attach {
reader?: NodeJS.ReadableStream;
writer?: NodeJS.WritableStream;
proc?: NodeJS.Process | child.ChildProcess;
socket?: string;
}
export function attach({
reader: _reader,
writer: _writer,
proc,
socket,
}: Attach) {
let writer;
let reader;
logger.debug('proc');
logger.debug(proc);
if (socket) {
const client = createConnection(socket);
writer = client;
reader = client;
} else if (_reader && _writer) {
writer = _writer;
reader = _reader;
} else if (proc) {
writer = proc.stdin;
reader = proc.stdout;
}
if (writer && reader) {
const neovim = new NeovimClient({ logger });
neovim.attachSession({
writer,
reader,
});
return neovim;
}
throw new Error('Invalid arguments, could not attach');
}
|
Add initial test for 'childlist' event | import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import createParentMixin from 'src/mixins/createParentMixin';
registerSuite({
name: 'mixins/createParentMixin',
creation() {
const parent = createParentMixin();
assert.isFunction(parent.append);
assert.isFunction(parent.insert);
assert.isObject(parent.children);
}
});
| import * as registerSuite from 'intern!object';
import * as assert from 'intern/chai!assert';
import createParentMixin from 'src/mixins/createParentMixin';
import createRenderable from 'src/mixins/createRenderable';
import { List } from 'immutable/immutable';
registerSuite({
name: 'mixins/createParentMixin',
creation() {
const parent = createParentMixin();
assert.isFunction(parent.append);
assert.isFunction(parent.insert);
assert.isObject(parent.children);
},
'on("childlist")': {
'append()'() {
const dfd = this.async();
const parent = createParentMixin();
const child = createRenderable();
parent.on('childlist', dfd.callback((event: any) => {
assert.strictEqual(event.type, 'childlist');
assert.strictEqual(event.target, parent);
assert.strictEqual(event.children, parent.children);
assert.isTrue(event.children.equals(List([ child ])));
}));
parent.append(child);
}
}
});
|
Make sure this is numeric | import { Property } from "tns-core-modules/ui/core/properties";
import { MLKitCameraView } from "../mlkit-cameraview";
export const confidenceThresholdProperty = new Property<MLKitImageLabeling, number>({
name: "confidenceThreshold",
defaultValue: 0.5,
});
export abstract class MLKitImageLabeling extends MLKitCameraView {
static scanResultEvent: string = "scanResult";
protected confidenceThreshold: number;
[confidenceThresholdProperty.setNative](value: number) {
this.confidenceThreshold = value;
}
}
confidenceThresholdProperty.register(MLKitImageLabeling);
| import { Property } from "tns-core-modules/ui/core/properties";
import { MLKitCameraView } from "../mlkit-cameraview";
export const confidenceThresholdProperty = new Property<MLKitImageLabeling, number>({
name: "confidenceThreshold",
defaultValue: 0.5,
});
export abstract class MLKitImageLabeling extends MLKitCameraView {
static scanResultEvent: string = "scanResult";
protected confidenceThreshold: number;
[confidenceThresholdProperty.setNative](value: any) {
this.confidenceThreshold = parseFloat(value);
}
}
confidenceThresholdProperty.register(MLKitImageLabeling);
|
Fix check for authorization in getUserId util func | import * as jwt from 'jsonwebtoken';
import { Prisma } from './generated/prisma';
export interface Context {
db: Prisma;
request: any;
}
export function getUserId(ctx: Context) {
const Authorization = ctx.request.get('Authorization');
if (Authorization) {
const token = Authorization.replace('Bearer ', '');
const { userId } = jwt.verify(token, process.env.APP_SECRET) as { userId: string };
return userId;
}
throw new AuthError();
}
export class AuthError extends Error {
constructor() {
super('Not authorized');
}
}
| import * as jwt from 'jsonwebtoken';
import { Prisma } from './generated/prisma';
export interface Context {
db: Prisma;
request: any;
}
export function getUserId(ctx: Context) {
const Authorization = ctx.request.get('Authorization');
// Apollo Client sets header to the string 'null' when not logged in
if (Authorization && Authorization !== 'null') {
const token = Authorization.replace('Bearer ', '');
const { userId } = jwt.verify(token, process.env.APP_SECRET) as { userId: string };
return userId;
}
throw new AuthError();
}
export class AuthError extends Error {
constructor() {
super('Not authorized');
}
}
|
Fix missing export of IThemeManager token | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import '../style/index.css';
export * from './clientsession';
export * from './clipboard';
export * from './collapse';
export * from './commandlinker';
export * from './commandpalette';
export * from './dialog';
export * from './domutils';
export * from './hoverbox';
export * from './iframe';
export * from './inputdialog';
export * from './instancetracker';
export * from './mainareawidget';
export * from './printing';
export * from './sanitizer';
export * from './spinner';
export * from './splash';
export * from './styling';
export * from './thememanager';
export * from './toolbar';
export * from './vdom';
export * from './windowresolver';
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import '../style/index.css';
export * from './clientsession';
export * from './clipboard';
export * from './collapse';
export * from './commandlinker';
export * from './commandpalette';
export * from './dialog';
export * from './domutils';
export * from './hoverbox';
export * from './iframe';
export * from './inputdialog';
export * from './instancetracker';
export * from './mainareawidget';
export * from './printing';
export * from './sanitizer';
export * from './spinner';
export * from './splash';
export * from './styling';
export * from './thememanager';
export * from './tokens';
export * from './toolbar';
export * from './vdom';
export * from './windowresolver';
|
Add active and selected classNames to combatant | import * as React from "react";
import { CombatantState } from "../../common/CombatantState";
export function CombatantRow(props: {
combatantState: CombatantState;
isActive: boolean;
isSelected: boolean;
showIndexLabel: boolean;
}) {
const displayName = props.combatantState.Alias.length
? props.combatantState.Alias
: props.combatantState.StatBlock.Name +
" " +
props.combatantState.IndexLabel;
return (
<span className="combatant">
<span className="combatant__leftsection">
<span className="combatant__name" title={displayName}>
{displayName}
</span>
</span>
</span>
);
}
| import * as React from "react";
import { CombatantState } from "../../common/CombatantState";
export function CombatantRow(props: {
combatantState: CombatantState;
isActive: boolean;
isSelected: boolean;
showIndexLabel: boolean;
}) {
const classNames = ["combatant"];
if (props.isActive) {
classNames.push("active");
}
if (props.isSelected) {
classNames.push("selected");
}
const displayName = props.combatantState.Alias.length
? props.combatantState.Alias
: props.combatantState.StatBlock.Name +
" " +
props.combatantState.IndexLabel;
return (
<span className={classNames.join(" ")}>
<span className="combatant__leftsection">
<span className="combatant__name" title={displayName}>
{displayName}
</span>
</span>
</span>
);
}
|
Remove retry from the AsyncRetry namespace | // Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
declare namespace AsyncRetry {
function retry<A>(fn: RetryFunction<A>, opts: Options): Promise<A>;
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export = AsyncRetry;
| // Type definitions for async-retry 1.2
// Project: https://github.com/zeit/async-retry#readme
// Definitions by: Albert Wu <https://github.com/albertywu>
// Pablo Rodríguez <https://github.com/MeLlamoPablo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function AsyncRetry<A>(
fn: AsyncRetry.RetryFunction<A>,
opts: AsyncRetry.Options
): Promise<A>;
declare namespace AsyncRetry {
interface Options {
retries?: number;
factor?: number;
minTimeout?: number;
maxTimeout?: number;
randomize?: boolean;
onRetry?: (e: Error) => any;
}
type RetryFunction<A> = (bail: (e: Error) => A, attempt: number) => A|Promise<A>;
}
export = AsyncRetry;
|
Remove include README.md on home page | import { Component, OnInit } from '@angular/core';
import { AppService } from '../../shared/app.service';
import { TranslateService } from '@ngx-translate/core';
let readme = require('html-loader!markdown-loader!./../../../README.md');
@Component({
selector: 'home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
public title: string;
public readme: string = readme;
constructor(public app: AppService,
public translateService: TranslateService) {
this.title = this.translateService.instant('Home');
}
ngOnInit() {
this.init();
}
init() {
this.app.currentPageName = 'home';
this.app.currentPageTitle = this.title;
}
}
| import { Component, OnInit } from '@angular/core';
import { AppService } from '../../shared/app.service';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent implements OnInit {
public title: string;
public readme: string = '';//require('html-loader!markdown-loader!./../../../README.md');
constructor(public app: AppService,
public translateService: TranslateService) {
this.title = this.translateService.instant('Home');
}
ngOnInit() {
this.init();
}
init() {
this.app.currentPageName = 'home';
this.app.currentPageTitle = this.title;
}
}
|
Update typings on StoreSubscription to properly use StoreBase | /**
* Types.ts
* Author: David de Regt
* Copyright: Microsoft 2016
*
* Shared basic types for ReSub.
*/
export type SubscriptionCallbackFunction = { (keys?: string[]): void; }
export type SubscriptionCallbackBuildStateFunction<S> = { (keys?: string[]): S | void; }
export interface StoreSubscription<S> {
store: any; // Should be StoreBase but not a good way to do the interfaces that I could find for that to work...
callbackBuildState?: SubscriptionCallbackBuildStateFunction<S>;
callback?: SubscriptionCallbackFunction;
autoForceUpdate?: boolean;
// If we're subscribing to a specific key of a type, what's the name of the React property that we're subscribing
// against (and detecting changes to)
keyPropertyName?: string;
// To subscribe to a specific key instead of the contents of a property, use this
specificKeyValue?: string|number;
// Allow toggling of subscription based on prop
enablePropertyName?: string;
}
| /**
* Types.ts
* Author: David de Regt
* Copyright: Microsoft 2016
*
* Shared basic types for ReSub.
*/
import { StoreBase } from './StoreBase';
export type SubscriptionCallbackFunction = { (keys?: string[]): void; }
export type SubscriptionCallbackBuildStateFunction<S> = { (keys?: string[]): S | void; }
export interface StoreSubscription<S> {
store: StoreBase;
callbackBuildState?: SubscriptionCallbackBuildStateFunction<S>;
callback?: SubscriptionCallbackFunction;
autoForceUpdate?: boolean;
// If we're subscribing to a specific key of a type, what's the name of the React property that we're subscribing
// against (and detecting changes to)
keyPropertyName?: string;
// To subscribe to a specific key instead of the contents of a property, use this
specificKeyValue?: string|number;
// Allow toggling of subscription based on prop
enablePropertyName?: string;
}
|
Read should always provide a big context | import { IMessageExtend, IMessageRead, IRead } from '../accessors/index';
import { IRoom } from '../rooms/index';
import { IUser } from '../users/index';
import { IMessage } from './IMessage';
export interface IPreMessageSentHandler {
/**
* First step when a handler is executed: Enables the handler to signal
* to the Rocketlets framework whether handler shall actually execute for the message
* about to be sent.
*
* @param message The message which is being sent
* @param read An accessor to the environment
* @return true: run the pre-logic
*/
checkPreMessageSent(message: IMessage, read: IRead): boolean;
/**
* This method can be used to non-destructively modify the message
* Due to its nature, this method could be parallelized
* @param message The message about to be sent
* @param read An accessor to the environment
* @param extend An accessor for modifying the messages non-destructively
*/
extendMessage(message: IMessage, read: IMessageRead, extend: IMessageExtend): void;
/**
* This method allows for manipulation of the message to be sent
* @param message The message about to be sent
* @param read An accessor to the environment
* @return The modified message
*/
manipulateMessage(message: IMessage, read: IMessageRead): IMessage;
}
| import { IMessageExtend, IRead } from '../accessors/index';
import { IMessage } from './IMessage';
export interface IPreMessageSentHandler {
/**
* First step when a handler is executed: Enables the handler to signal
* to the Rocketlets framework whether handler shall actually execute for the message
* about to be sent.
*
* @param message The message which is being sent
* @param read An accessor to the environment
* @return true: run the pre-logic
*/
checkPreMessageSent(message: IMessage, read: IRead): boolean;
/**
* This method can be used to non-destructively modify the message
* Due to its nature, this method could be parallelized
* @param message The message about to be sent
* @param read An accessor to the environment
* @param extend An accessor for modifying the messages non-destructively
*/
extendMessage(message: IMessage, read: IRead, extend: IMessageExtend): void;
/**
* This method allows for manipulation of the message to be sent
* @param message The message about to be sent
* @param read An accessor to the environment
* @return The modified message
*/
manipulateMessage(message: IMessage, read: IRead): IMessage;
}
|
Remove swagger base path - fix curl bug | import {NestFactory} from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {ValidationPipe, INestApplication} from '@nestjs/common';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import {AppModule} from './app.module';
import {AuthGuard} from './auth/auth.guard';
import {AuthModule} from './auth/auth.module';
import {apiPath} from './api';
async function bootstrap() {
const app: INestApplication = await NestFactory.create(AppModule);
app.use(bodyParser.json());
app.useGlobalPipes(new ValidationPipe());
const authGuard = app.select(AuthModule).get(AuthGuard);
app.useGlobalGuards(authGuard);
// Allow CORS since frontend is served completely independently
app.use(cors());
const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('tsmean sample api')
.setBasePath(apiPath(1, ''))
.addTag('Animals')
.addTag('Animal lists')
.addTag('Users')
.setDescription('Sample REST API that allows to manage list of animals')
.setVersion('1.0')
.build();
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/api/swagger', app, swaggerDocument);
const port: number = process.env.PORT ? parseInt(process.env.PORT, 10) : 4242;
await app.listen(port);
}
bootstrap();
| import {NestFactory} from '@nestjs/core';
import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger';
import {ValidationPipe, INestApplication} from '@nestjs/common';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import {AppModule} from './app.module';
import {AuthGuard} from './auth/auth.guard';
import {AuthModule} from './auth/auth.module';
import {apiPath} from './api';
async function bootstrap() {
const app: INestApplication = await NestFactory.create(AppModule);
app.use(bodyParser.json());
app.useGlobalPipes(new ValidationPipe());
const authGuard = app.select(AuthModule).get(AuthGuard);
app.useGlobalGuards(authGuard);
// Allow CORS since frontend is served completely independently
app.use(cors());
const swaggerConfig = new DocumentBuilder()
.addBearerAuth()
.setTitle('tsmean sample api')
.addTag('Animals')
.addTag('Animal lists')
.addTag('Users')
.setDescription('Sample REST API that allows to manage list of animals')
.setVersion('1.0')
.build();
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('/api/swagger', app, swaggerDocument);
const port: number = process.env.PORT ? parseInt(process.env.PORT, 10) : 4242;
await app.listen(port);
}
bootstrap();
|
Remove new reply dialog experiment from KnownExperimentId | /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
TOKEN_HIGHLIGHTING = 'UiFeature__token_highlighting',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
NEW_REPLY_DIALOG = 'UiFeature__new_reply_dialog',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
}
| /**
* @license
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface FlagsService {
isEnabled(experimentId: string): boolean;
enabledExperiments: string[];
}
/**
* @desc Experiment ids used in Gerrit.
*/
export enum KnownExperimentId {
NEW_IMAGE_DIFF_UI = 'UiFeature__new_image_diff_ui',
TOKEN_HIGHLIGHTING = 'UiFeature__token_highlighting',
CHECKS_DEVELOPER = 'UiFeature__checks_developer',
SUBMIT_REQUIREMENTS_UI = 'UiFeature__submit_requirements_ui',
}
|
Fix custom matcher for new jest version | /* eslint-env jest */
import {
NodePath as NodePathConstructor,
astNodesAreEquivalent,
ASTNode,
} from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
import diff from 'jest-diff';
import utils from 'jest-matcher-utils';
const matchers = {
toEqualASTNode: function (received: NodePath, expected: NodePath | ASTNode) {
if (!expected || typeof expected !== 'object') {
throw new Error(
'Expected value must be an object representing an AST node.\n' +
'Got ' +
expected +
'(' +
typeof expected +
') instead.',
);
}
// Use value here instead of node, as node has some magic and always returns
// the next Node it finds even if value is an array
const receivedNode = received.value;
let expectedNode = expected;
if (expected instanceof NodePathConstructor) {
expectedNode = expected.value;
}
return {
pass: astNodesAreEquivalent(receivedNode, expectedNode),
message: () => {
const diffString = diff(expectedNode, receivedNode);
return (
'Expected value to be (using ast-types):\n' +
` ${utils.printExpected(expectedNode)}\n` +
'Received:\n' +
` ${utils.printReceived(receivedNode)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
},
};
},
};
expect.extend(matchers);
| /* eslint-env jest */
import {
NodePath as NodePathConstructor,
astNodesAreEquivalent,
ASTNode,
} from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
import { diff } from 'jest-diff';
import { printExpected, printReceived } from 'jest-matcher-utils';
const matchers = {
toEqualASTNode: function (received: NodePath, expected: NodePath | ASTNode) {
if (!expected || typeof expected !== 'object') {
throw new Error(
'Expected value must be an object representing an AST node.\n' +
'Got ' +
expected +
'(' +
typeof expected +
') instead.',
);
}
// Use value here instead of node, as node has some magic and always returns
// the next Node it finds even if value is an array
const receivedNode = received.value;
let expectedNode = expected;
if (expected instanceof NodePathConstructor) {
expectedNode = expected.value;
}
return {
pass: astNodesAreEquivalent(receivedNode, expectedNode),
message: () => {
const diffString = diff(expectedNode, receivedNode);
return (
'Expected value to be (using ast-types):\n' +
` ${printExpected(expectedNode)}\n` +
'Received:\n' +
` ${printReceived(receivedNode)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
},
};
},
};
expect.extend(matchers);
|
Clean up health check output to be less verbose | import { Injectable } from "@nestjs/common";
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from "@nestjs/terminus";
import { TopologyService } from "../districts/services/topology.service";
@Injectable()
export default class TopologyLoadedIndicator extends HealthIndicator {
constructor(public topologyService: TopologyService) {
super();
}
async isHealthy(key: string): Promise<HealthIndicatorResult> {
const layers = this.topologyService.layers();
if (layers === undefined) {
const result = this.getStatus(key, false, {});
throw new HealthCheckError("Topology layers not intialized", result);
}
const layerEntries = (await Promise.all(
Object.entries(layers).map(([layerId, topology]) => {
return new Promise((resolve, reject) => {
// Promise.race should return the first already resolved promise
// immediately when provided at least one, so this shouldn't block
void Promise.race([topology, Promise.resolve(undefined)]).then(topology => {
resolve([layerId, topology !== undefined]);
});
});
})
)) as [string, boolean][];
const layerStatus = Object.fromEntries(layerEntries);
const isHealthy = Object.values(layerStatus).every(status => status);
const result = this.getStatus(key, isHealthy, layerStatus);
if (isHealthy) {
return result;
}
throw new HealthCheckError("Topology not fully loaded", result);
}
}
| import { Injectable } from "@nestjs/common";
import { HealthIndicator, HealthIndicatorResult, HealthCheckError } from "@nestjs/terminus";
import { TopologyService } from "../districts/services/topology.service";
@Injectable()
export default class TopologyLoadedIndicator extends HealthIndicator {
constructor(public topologyService: TopologyService) {
super();
}
async isHealthy(key: string): Promise<HealthIndicatorResult> {
const layers = this.topologyService.layers();
if (layers === undefined) {
const result = this.getStatus(key, false, {});
throw new HealthCheckError("Topology layers not intialized", result);
}
const layerEntries = (await Promise.all(
Object.entries(layers).map(([layerId, topology]) => {
return new Promise((resolve, reject) => {
// Promise.race should return the first already resolved promise
// immediately when provided at least one, so this shouldn't block
void Promise.race([topology, Promise.resolve(undefined)]).then(topology => {
resolve([layerId, topology !== undefined]);
});
});
})
)) as [string, boolean][];
const isHealthy = layerEntries.every(([_, status]) => status);
const pendingLayers = layerEntries.filter(([_, status]) => !status).map(([layer, _]) => layer);
const result = this.getStatus(key, isHealthy, {
total: layerEntries.length,
complete: layerEntries.length - pendingLayers.length,
pendingLayers
});
if (isHealthy) {
return result;
}
throw new HealthCheckError("Topology not fully loaded", result);
}
}
|
Add Input Component to App Component | import Component from 'inferno-component'
import h from 'inferno-hyperscript'
interface Props {}
export default class App extends Component<Props, {}> {
render() {
return h('p', 'hello')
}
}
| import Component from 'inferno-component'
import h from 'inferno-hyperscript'
import Input from './input.ts'
interface Props {}
interface State {
titles: string[]
}
export default class App extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
titles: []
}
}
addTitle(title: string) {
this.state.titles.push(title)
console.log(this.state.titles)
}
render() {
return h(Input, { add: this.addTitle.bind(this) })
}
}
|
Use member reference base class from cxml. | // This file is part of cxsd, copyright (c) 2016 BusFaster Ltd.
// Released under the MIT license, see LICENSE.
import {Namespace} from './Namespace';
import {Member} from './Member';
import {Type} from './Type';
export class MemberRef {
constructor(member: Member, min: number, max: number) {
this.member = member;
this.min = min;
this.max = max;
}
member: Member;
min: number;
max: number;
safeName: string;
prefix: string;
static optionalFlag = 1;
static arrayFlag = 2;
}
| // This file is part of cxsd, copyright (c) 2016 BusFaster Ltd.
// Released under the MIT license, see LICENSE.
import * as cxml from 'cxml';
import {Member} from './Member';
export class MemberRef extends cxml.MemberRefBase<Member> {
prefix: string;
}
|
Move judges info to separate folder Judges JSON contains not only declarations | const NAVBAR = [
{
title : 'Про нас',
state : 'about'
},
{
title : 'Головна',
state : 'home'
},
{
title : 'Судді',
state : 'list'
}
];
const SOURCE = '/source';
const URLS = {
listUrl : `${SOURCE}/judges.json`,
dictionaryUrl : `${SOURCE}/dictionary.json`,
dictionaryTimeStamp : `${SOURCE}/dictionary.json.timestamp`,
textUrl : `${SOURCE}/texts.json`,
textTimeStamp : `${SOURCE}/dictionary.json.timestamp`,
details : `/declarations/:key.json`
};
export { URLS, NAVBAR };
| const NAVBAR = [
{
title : 'Про нас',
state : 'about'
},
{
title : 'Головна',
state : 'home'
},
{
title : 'Судді',
state : 'list'
}
];
const SOURCE = '/source';
const URLS = {
listUrl : `${SOURCE}/judges.json`,
dictionaryUrl : `${SOURCE}/dictionary.json`,
dictionaryTimeStamp : `${SOURCE}/dictionary.json.timestamp`,
textUrl : `${SOURCE}/texts.json`,
textTimeStamp : `${SOURCE}/dictionary.json.timestamp`,
details : `/judges/:key.json`
};
export { URLS, NAVBAR };
|
Change to error logging for EcmaScript 5. | /*
Copyright 2016 James Craig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/// <reference path="FunctionExtensions.ts" />
//Handles error logging
export class ErrorLogging {
//constructor
constructor() {
this.logError = (ex,stack) => { };
}
//Logs the error message. Includes the message and stack trace information.
public logError: (message: string, stack: any[]) => void;
//Sets the logging function that the system uses
public setLoggingFunction(logger: (message: string, stack: any[]) => void): void {
this.logError = logger;
}
//called when an error is thrown.
public onError(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void {
this.logError(message, arguments.callee.trace());
}
}
| /*
Copyright 2016 James Craig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/// <reference path="FunctionExtensions.ts" />
//Handles error logging
export class ErrorLogging {
//constructor
constructor() {
this.logError = (ex,stack) => { };
}
//Logs the error message. Includes the message and stack trace information.
public logError: (message: string, stack: string) => void;
//Sets the logging function that the system uses
public setLoggingFunction(logger: (message: string, stack: string) => void): void {
this.logError = logger;
}
//called when an error is thrown.
public onError(message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void {
this.logError(message, error.stack);
}
}
|
Remove self assigned values of the eventPhase enum | /**
* An enum for possible event phases that an event can be in
*/
const enum EventPhase {
/**
* Indicates that the event is currently not being dispatched
*/
NONE = 0,
/**
* Indicates that the event is in the capturing phase, moving down from the top-most EventDispatcher
* instance to the parent of the target EventDispatcher
*/
CAPTURING_PHASE = 1,
/**
* Indicates that we are currently calling the event listeners on the event target during dispatch.
*/
AT_TARGET = 2,
/**
* Indicates that we are currently moving back up from the parent of the target EventDispatcher to
* the top-most EventDispatcher instance.
*/
BUBBLING_PHASE = 3,
}
export default EventPhase;
| /**
* An enum for possible event phases that an event can be in
*/
const enum EventPhase {
/**
* Indicates that the event is currently not being dispatched
*/
NONE,
/**
* Indicates that the event is in the capturing phase, moving down from the top-most EventDispatcher
* instance to the parent of the target EventDispatcher
*/
CAPTURING_PHASE,
/**
* Indicates that we are currently calling the event listeners on the event target during dispatch.
*/
AT_TARGET,
/**
* Indicates that we are currently moving back up from the parent of the target EventDispatcher to
* the top-most EventDispatcher instance.
*/
BUBBLING_PHASE,
}
export default EventPhase;
|
Change name of list bullet component | import Vue from 'vue';
import { PluginObject } from 'vue';
import Component from 'vue-class-component';
import { Prop } from 'vue-property-decorator';
import WithRender from './list-bullet.html?style=./list-bullet.scss';
import { LIST_BULLET_NAME } from '../component-names';
@WithRender
@Component
export class MList extends Vue {
@Prop({ default: ['Element 1', 'Element 2', 'Element 3'] })
public values: string[];
private componentName = LIST_BULLET_NAME;
}
const ListPlugin: PluginObject<any> = {
install(v, options) {
v.component(LIST_BULLET_NAME, MList);
}
};
export default ListPlugin;
| import Vue from 'vue';
import { PluginObject } from 'vue';
import Component from 'vue-class-component';
import { Prop } from 'vue-property-decorator';
import WithRender from './list-bullet.html?style=./list-bullet.scss';
import { LIST_BULLET_NAME } from '../component-names';
@WithRender
@Component
export class MListBullet extends Vue {
@Prop({ default: ['Element 1', 'Element 2', 'Element 3'] })
public values: string[];
private componentName = LIST_BULLET_NAME;
}
const ListBulletPlugin: PluginObject<any> = {
install(v, options) {
v.component(LIST_BULLET_NAME, MListBullet);
}
};
export default ListBulletPlugin;
|
Fix PrivateRoute pass lang prop | import { Redirect } from "@reach/router";
import React, { Component } from "react";
import { useLoginState } from "../profile/hooks";
export const PrivateRoute = ({
component: PrivateComponent,
lang,
...rest
}: any) => {
const [loggedIn, _] = useLoginState(false);
const loginUrl = `${lang}/login`;
if (!loggedIn) {
return <Redirect to={loginUrl} noThrow={true} />;
}
return <PrivateComponent {...rest} />;
};
| import { Redirect } from "@reach/router";
import React, { Component } from "react";
import { useLoginState } from "../profile/hooks";
export const PrivateRoute = ({
component: PrivateComponent,
lang,
...rest
}: any) => {
const [loggedIn, _] = useLoginState(false);
const loginUrl = `${lang}/login`;
if (!loggedIn) {
return <Redirect to={loginUrl} noThrow={true} />;
}
return <PrivateComponent lang={lang} {...rest} />;
};
|
Fix links being comma seperated. | import h from '../../../lib/tsx/TsxParser';
export interface LinkProps {
href: string;
title: string;
}
function Link(props: Partial<LinkProps>): JSX.Element {
const { href, title } = props as LinkProps;
return (
<a href={href} title={title} target="_blank" rel="noopener">
{title}
</a>
);
}
interface HeaderProps {
firstName: string;
lastName: string;
links: LinkProps[];
}
export function Header(props: Partial<HeaderProps>): JSX.Element {
const { firstName, lastName, links } = props as HeaderProps;
const linkElements = links.map((link: LinkProps) => (
<Link href={link.href} title={link.title} />
));
return (
<header>
<div className="top-avatar" />
<h1>
{firstName} <strong>{lastName}</strong>
</h1>
<nav>{linkElements}</nav>
</header>
);
}
| import h from '../../../lib/tsx/TsxParser';
export interface LinkProps {
href: string;
title: string;
}
function Link(props: Partial<LinkProps>): JSX.Element {
const { href, title } = props as LinkProps;
return (
<a href={href} title={title} target="_blank" rel="noopener">
{title}
</a>
);
}
interface HeaderProps {
firstName: string;
lastName: string;
links: LinkProps[];
}
export function Header(props: Partial<HeaderProps>): JSX.Element {
const { firstName, lastName, links } = props as HeaderProps;
const linkElements = links.map((link: LinkProps) => (
<Link href={link.href} title={link.title} />
));
return (
<header>
<div className="top-avatar" />
<h1>
{firstName} <strong>{lastName}</strong>
</h1>
<nav>{linkElements.join('')}</nav>
</header>
);
}
|
Return an error code equal to the number of errors found | import chalk from 'chalk';
import { RuleToRuleApplicationResult } from './../types';
import logToConsole from './console';
import { compactProjectLogs } from './flatten';
export const consoleLogger = (projectResult: RuleToRuleApplicationResult): number => {
const projectLogs = compactProjectLogs(projectResult);
if (projectLogs.length) {
console.log(chalk.bgBlackBright('Project'));
logToConsole(projectLogs);
}
return projectLogs.length;
};
| import chalk from 'chalk';
import { RuleToRuleApplicationResult } from './../types';
import logToConsole from './console';
import { compactProjectLogs } from './flatten';
export const consoleLogger = (projectResult: RuleToRuleApplicationResult): number => {
const projectLogs = compactProjectLogs(projectResult);
if (projectLogs.length) {
console.log(chalk.bgBlackBright('Project'));
logToConsole(projectLogs);
}
const errorCount = Object.values(projectLogs).reduce(
(acc, i) => acc + ((i.errors && i.errors.length) || 0),
0,
);
return errorCount;
};
|
Comment all edge directions and remove unused. | /** Enumeration for directions
* @enum string
* @readonly
*/
export enum EdgeDirection {
/**
* Next photo in the sequence
*/
NEXT = 0,
/**
* Previous photo in the sequence
*/
PREV = 3,
/**
* Step to the photo on the left
*/
STEP_LEFT,
/**
* Step to the photo on the right
*/
STEP_RIGHT,
/**
* Step to the photo forward (equivalent of moving forward)
*/
STEP_FORWARD,
/**
* Step to the photo backward (equivalent of moving backward)
*/
STEP_BACKWARD,
/**
* Rotate ~90deg to the left from the current photo
*/
TURN_LEFT,
/**
* Rotate ~90deg to the right from the current photo
*/
TURN_RIGHT,
/**
* Turn around, relative to the dirrection of the current photo
*/
TURN_U,
ROTATE_LEFT,
ROTATE_RIGHT,
HOMOGRAPHY,
CLOSE,
PANO
};
| /**
* Enumeration for edge directions
* @enum {number}
* @readonly
* @description Directions for edges in node graph describing
* sequence, spatial and node type relations between nodes.
*/
export enum EdgeDirection {
/**
* Next node in the sequence
*/
NEXT = 0,
/**
* Previous node in the sequence
*/
PREV = 3,
/**
* Step to the left keeping viewing direction
*/
STEP_LEFT,
/**
* Step to the right keeping viewing direction
*/
STEP_RIGHT,
/**
* Step forward keeping viewing direction
*/
STEP_FORWARD,
/**
* Step backward keeping viewing direction
*/
STEP_BACKWARD,
/**
* Turn 90 degrees counter clockwise
*/
TURN_LEFT,
/**
* Turn 90 degrees clockwise
*/
TURN_RIGHT,
/**
* Turn 180 degrees
*/
TURN_U,
/**
* Rotate with small counter clockwise angle change
*/
ROTATE_LEFT,
/**
* Rotate with small clockwise angle change
*/
ROTATE_RIGHT,
/**
* Panorama in general direction
*/
PANO
};
|
Fix syntax for factorying local storage function | import { always, merge, objOf, pipe } from 'ramda';
import { Clear, Delete, Read, Write } from '../commands/local_storage';
import { constructMessage, safeParse, safeStringify } from '../util';
const get = (() => (
typeof window === 'undefined' ? always('<running outside browser context>') :
window && window.localStorage && window.localStorage.getItem.bind(window.localStorage)
)());
export default new Map([
[Read, ({ key, result }, dispatch) => pipe(
get, safeParse, objOf('value'), merge({ key }), constructMessage(result), dispatch
)(key)],
[Write, ({ key, value }) => window.localStorage.setItem(key, safeStringify(value))],
[Delete, ({ key }) => window.localStorage.removeItem(key)],
[Clear, () => window.localStorage.clear()],
]);
| import { always, merge, objOf, pipe } from 'ramda';
import { Clear, Delete, Read, Write } from '../commands/local_storage';
import { constructMessage, safeParse, safeStringify } from '../util';
const get = (() => (
typeof window === 'undefined' ? always('<running outside browser context>') :
window && window.localStorage && window.localStorage.getItem.bind(window.localStorage)
))();
export default new Map([
[Read, ({ key, result }, dispatch) => pipe(
get, safeParse, objOf('value'), merge({ key }), constructMessage(result), dispatch
)(key)],
[Write, ({ key, value }) => window.localStorage.setItem(key, safeStringify(value))],
[Delete, ({ key }) => window.localStorage.removeItem(key)],
[Clear, () => window.localStorage.clear()],
]);
|
Change default route to people/1 for dev simplification | import { Routes, RouterModule } from '@angular/router';
import { ListPageComponent } from './list-page/list-page.component';
import { DetailPageComponent } from './detail-page/detail-page.component';
const isariRoutes: Routes = [
{
path: '',
redirectTo: '/people',
pathMatch: 'full'
},
{
path: ':feature',
children: [
{
path: '',
component: ListPageComponent
},
{
path: ':id',
component: DetailPageComponent
}
]
}
];
const appRoutes: Routes = [
...isariRoutes
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(appRoutes);
| import { Routes, RouterModule } from '@angular/router';
import { ListPageComponent } from './list-page/list-page.component';
import { DetailPageComponent } from './detail-page/detail-page.component';
const isariRoutes: Routes = [
{
path: '',
redirectTo: '/people/1',
pathMatch: 'full'
},
{
path: ':feature',
children: [
{
path: '',
component: ListPageComponent
},
{
path: ':id',
component: DetailPageComponent
}
]
}
];
const appRoutes: Routes = [
...isariRoutes
];
export const appRoutingProviders: any[] = [];
export const routing = RouterModule.forRoot(appRoutes);
|
Add necessary typecast for supporting jlab 1 and 2 | // Copyright (c) {{ cookiecutter.author_name }}
// Distributed under the terms of the Modified BSD License.
import {
Application, IPlugin
} from '@phosphor/application';
import {
Widget
} from '@phosphor/widgets';
import {
IJupyterWidgetRegistry
} from '@jupyter-widgets/base';
import * as widgetExports from './widget';
import {
MODULE_NAME, MODULE_VERSION
} from './version';
const EXTENSION_ID = '{{ cookiecutter.npm_package_name }}:plugin';
/**
* The example plugin.
*/
const examplePlugin: IPlugin<Application<Widget>, void> = {
id: EXTENSION_ID,
requires: [IJupyterWidgetRegistry],
activate: activateWidgetExtension,
autoStart: true
};
export default examplePlugin;
/**
* Activate the widget extension.
*/
function activateWidgetExtension(app: Application<Widget>, registry: IJupyterWidgetRegistry): void {
registry.registerWidget({
name: MODULE_NAME,
version: MODULE_VERSION,
exports: widgetExports,
});
}
| // Copyright (c) {{ cookiecutter.author_name }}
// Distributed under the terms of the Modified BSD License.
import {
Application, IPlugin
} from '@phosphor/application';
import {
Widget
} from '@phosphor/widgets';
import {
IJupyterWidgetRegistry
} from '@jupyter-widgets/base';
import * as widgetExports from './widget';
import {
MODULE_NAME, MODULE_VERSION
} from './version';
const EXTENSION_ID = '{{ cookiecutter.npm_package_name }}:plugin';
/**
* The example plugin.
*/
const examplePlugin: IPlugin<Application<Widget>, void> = {
id: EXTENSION_ID,
requires: [IJupyterWidgetRegistry],
activate: activateWidgetExtension,
autoStart: true
} as unknown as IPlugin<Application<Widget>, void>;
// the "as unknown as ..." typecast above is solely to support JupyterLab 1
// and 2 in the same codebase and should be removed when we migrate to Lumino.
export default examplePlugin;
/**
* Activate the widget extension.
*/
function activateWidgetExtension(app: Application<Widget>, registry: IJupyterWidgetRegistry): void {
registry.registerWidget({
name: MODULE_NAME,
version: MODULE_VERSION,
exports: widgetExports,
});
}
|
Add fade in transition to tooltip | import React, { PureComponent } from 'react';
import { Manager, Popper as ReactPopper, Reference } from 'react-popper';
interface Props {
renderContent: (content: any) => any;
show: boolean;
placement?: any;
content: string | ((props: any) => JSX.Element);
refClassName?: string;
}
class Popper extends PureComponent<Props> {
render() {
const { children, renderContent, show, placement, refClassName } = this.props;
const { content } = this.props;
return (
<Manager>
<Reference>
{({ ref }) => (
<div className={`popper_ref ${refClassName || ''}`} ref={ref}>
{children}
</div>
)}
</Reference>
{show && (
<ReactPopper placement={placement}>
{({ ref, style, placement, arrowProps }) => {
return (
<div ref={ref} style={style} data-placement={placement} className="popper">
<div className="popper__background">
{renderContent(content)}
<div ref={arrowProps.ref} data-placement={placement} className="popper__arrow" />
</div>
</div>
);
}}
</ReactPopper>
)}
</Manager>
);
}
}
export default Popper;
| import React, { PureComponent } from 'react';
import { Manager, Popper as ReactPopper, Reference } from 'react-popper';
import Transition from 'react-transition-group/Transition';
const defaultTransitionStyles = {
transition: 'opacity 200ms linear',
opacity: 0,
};
const transitionStyles = {
exited: { opacity: 0 },
entering: { opacity: 0 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
};
interface Props {
renderContent: (content: any) => any;
show: boolean;
placement?: any;
content: string | ((props: any) => JSX.Element);
refClassName?: string;
}
class Popper extends PureComponent<Props> {
render() {
const { children, renderContent, show, placement, refClassName } = this.props;
const { content } = this.props;
return (
<Manager>
<Reference>
{({ ref }) => (
<div className={`popper_ref ${refClassName || ''}`} ref={ref}>
{children}
</div>
)}
</Reference>
<Transition in={show} timeout={100}>
{transitionState => (
<ReactPopper placement={placement}>
{({ ref, style, placement, arrowProps }) => {
return (
<div
ref={ref}
style={{
...style,
...defaultTransitionStyles,
...transitionStyles[transitionState],
}}
data-placement={placement}
className="popper"
>
<div className="popper__background">
{renderContent(content)}
<div ref={arrowProps.ref} data-placement={placement} className="popper__arrow" />
</div>
</div>
);
}}
</ReactPopper>
)}
</Transition>
</Manager>
);
}
}
export default Popper;
|
Make 'published' a public field on events | import { EventActions } from './EventActions'
import { Event, User, Permission } from '../models'
import { rejectIfNull } from './util'
import * as mongodb from '../mongodb/Event'
export class EventActionsImpl implements EventActions {
getEvents(auth: User): Promise<Event[]> {
if (auth) {
// All fields
return mongodb.Event.find().exec()
} else {
// Public event
return mongodb.Event.find({}, {
'id': true,
'companyName': true,
'publicDescription': true,
'date': true,
'pictures': true,
}).exec()
}
}
createEvent(auth: User, companyName: string, fields: Partial<Event>):
Promise<Event> {
if (!auth.permissions.includes(Permission.Events))
return Promise.reject('Insufficient permissions')
const event = new mongodb.Event({
companyName,
...fields,
})
return event.save()
}
updateEvent(auth: User, id: string, fields: Partial<Event>): Promise<Event> {
if (!auth.permissions.includes(Permission.Events))
return Promise.reject('Insufficient permissions')
return mongodb.Event.findOneAndUpdate(
{ _id: id },
{ ...fields },
{ new: true }
).then(rejectIfNull('No event exists for given id'))
}
removeEvent(id: string): Promise<boolean> {
return mongodb.Event.findOneAndRemove({ _id: id })
.then(event => {
return (event != undefined)
})
}
}
| import { EventActions } from './EventActions'
import { Event, User, Permission } from '../models'
import { rejectIfNull } from './util'
import * as mongodb from '../mongodb/Event'
export class EventActionsImpl implements EventActions {
getEvents(auth: User): Promise<Event[]> {
if (auth) {
// All fields
return mongodb.Event.find().exec()
} else {
// Public event
return mongodb.Event.find({}, {
'id': true,
'companyName': true,
'publicDescription': true,
'date': true,
'pictures': true,
'published': true,
}).exec()
}
}
createEvent(auth: User, companyName: string, fields: Partial<Event>):
Promise<Event> {
if (!auth.permissions.includes(Permission.Events))
return Promise.reject('Insufficient permissions')
const event = new mongodb.Event({
companyName,
...fields,
})
return event.save()
}
updateEvent(auth: User, id: string, fields: Partial<Event>): Promise<Event> {
if (!auth.permissions.includes(Permission.Events))
return Promise.reject('Insufficient permissions')
return mongodb.Event.findOneAndUpdate(
{ _id: id },
{ ...fields },
{ new: true }
).then(rejectIfNull('No event exists for given id'))
}
removeEvent(id: string): Promise<boolean> {
return mongodb.Event.findOneAndRemove({ _id: id })
.then(event => {
return (event != undefined)
})
}
}
|
Fix broken test due to direct provision of the actual service rather than a test double | /* tslint:disable:no-unused-variable */
/*!
* Suitability Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { provideStore } from '@ngrx/store';
import { LeafletMapService } from '../../leaflet';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapLayersReducer, SuitabilityLevelsReducer } from '../../store';
import { MockRouter } from '../../mocks/router';
import { SuitabilityMapPanelComponent } from './suitability-map-panel.component';
describe('Component: SuitabilityMapPanel', () => {
let mockRouter: MockRouter;
beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
SuitabilityMapService,
SuitabilityMapPanelComponent,
{ provide: Router, useValue: mockRouter },
provideStore({
mapLayers: MapLayersReducer,
suitabilityLevels: SuitabilityLevelsReducer
})
]
});
});
it('should create an instance', inject([SuitabilityMapPanelComponent], (component: SuitabilityMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
| /* tslint:disable:no-unused-variable */
/*!
* Suitability Map Panel Component Test
*
* Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
* Licensed under MIT
*/
import { Renderer } from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { Router } from '@angular/router';
import { provideStore } from '@ngrx/store';
import { LeafletMapService } from '../../leaflet';
import { SuitabilityMapService } from '../suitability-map.service';
import { MapLayersReducer, SuitabilityLevelsReducer } from '../../store';
import { MockRouter } from '../../mocks/router';
import { MockSuitabilityMapService } from '../../mocks/map';
import { SuitabilityMapPanelComponent } from './suitability-map-panel.component';
describe('Component: SuitabilityMapPanel', () => {
let mockRouter: MockRouter;
beforeEach(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
providers: [
Renderer,
LeafletMapService,
SuitabilityMapPanelComponent,
{ provide: SuitabilityMapService, useClass: MockSuitabilityMapService }
{ provide: Router, useValue: mockRouter },
provideStore({
mapLayers: MapLayersReducer,
suitabilityLevels: SuitabilityLevelsReducer
})
]
});
});
it('should create an instance', inject([SuitabilityMapPanelComponent], (component: SuitabilityMapPanelComponent) => {
expect(component).toBeTruthy();
}));
});
|
Set delay when hiding window (again) | import { IpcEmitter } from "./ipc-emitter";
import { ipcMain } from "electron";
import { IpcChannels } from "./ipc-channels";
export class ProductionIpcEmitter implements IpcEmitter {
public emitResetUserInput(): void {
ipcMain.emit(IpcChannels.resetUserInput);
}
public emitHideWindow(): void {
ipcMain.emit(IpcChannels.hideWindow);
}
}
| import { IpcEmitter } from "./ipc-emitter";
import { ipcMain } from "electron";
import { IpcChannels } from "./ipc-channels";
export class ProductionIpcEmitter implements IpcEmitter {
private windowHideDelayInMilliSeconds = 50;
public emitResetUserInput(): void {
ipcMain.emit(IpcChannels.resetUserInput);
}
public emitHideWindow(): void {
setTimeout((): void => {
ipcMain.emit(IpcChannels.hideWindow);
}, this.windowHideDelayInMilliSeconds); // set delay when hiding main window so user input can be reset properly
}
}
|
Remove debug log and fix blank suggestions bug | module ImprovedInitiative {
export class PlayerSuggestion {
constructor(
public Socket: SocketIOClient.Socket,
public EncounterId: string
) {}
SuggestionVisible = ko.observable(false);
Combatant: KnockoutObservable<StaticCombatantViewModel> = ko.observable();
Name = ko.pureComputed(() => {
if (!this.Combatant()) {
return "";
} else {
return this.Combatant().Name;
}
})
Show = (combatant: StaticCombatantViewModel) => {
this.Combatant(combatant);
this.SuggestionVisible(true);
$("input[name=suggestedDamage]").first().select();
}
Resolve = (form: HTMLFormElement) => {
const value = $(form).find("[name=suggestedDamage]").first().val();
console.log(this.Combatant().Name);
this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], parseInt(value, 10), "Player");
this.Close();
}
Close = () => {
this.SuggestionVisible(false);
}
}
} | module ImprovedInitiative {
export class PlayerSuggestion {
constructor(
public Socket: SocketIOClient.Socket,
public EncounterId: string
) {}
SuggestionVisible = ko.observable(false);
Combatant: KnockoutObservable<StaticCombatantViewModel> = ko.observable();
Name = ko.pureComputed(() => {
if (!this.Combatant()) {
return "";
} else {
return this.Combatant().Name;
}
})
Show = (combatant: StaticCombatantViewModel) => {
this.Combatant(combatant);
this.SuggestionVisible(true);
$("input[name=suggestedDamage]").first().focus();
}
Resolve = (form: HTMLFormElement) => {
const element = $(form).find("[name=suggestedDamage]").first();
const value = parseInt(element.val(), 10);
if (!isNaN(value) && value !== 0) {
this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], value, "Player");
}
element.val("");
this.Close();
}
Close = () => {
this.SuggestionVisible(false);
}
}
} |
Add docs for the typescript task | import * as gulp from 'gulp';
import * as gulpif from 'gulp-if';
import * as sourcemaps from 'gulp-sourcemaps';
import * as typescript from 'gulp-typescript';
export const DIR_TMP = '.tmp';
export const DIR_DST = 'dist';
export const DIR_SRC = 'src';
/**
* The `project` is used inside the "ts" task to compile TypeScript code using
* tsconfig.json file. The project MUST be created outside of the task to
* enable incremental compilation.
*/
const project = typescript.createProject('tsconfig.json', {
/**
* We don't use any kind of modules or <reference> tags in our project, so we
* don't need to support external modules resolving. According to the
* gulp-typescript plugin docs explicitly disabling it can improve
* compilation time.
*/
noExternalResolve: true
});
export function typescriptTask(enableSourcemaps: boolean = false) {
let files = [`${DIR_SRC}/**/*.ts`, 'typings/browser/**/*.d.ts'];
return gulp.src(files, {base: DIR_SRC})
.pipe(gulpif(enableSourcemaps, sourcemaps.init()))
.pipe(typescript(project))
.pipe(gulpif(enableSourcemaps, sourcemaps.write()))
.pipe(gulp.dest(DIR_TMP));
}
export function copyHtmlTask() {
return gulp.src(`${DIR_SRC}/**/*.html`, {base: DIR_SRC})
.pipe(gulp.dest(DIR_TMP));
}
| import * as gulp from 'gulp';
import * as gulpif from 'gulp-if';
import * as sourcemaps from 'gulp-sourcemaps';
import * as typescript from 'gulp-typescript';
export const DIR_TMP = '.tmp';
export const DIR_DST = 'dist';
export const DIR_SRC = 'src';
/**
* The `project` is used inside the "ts" task to compile TypeScript code using
* tsconfig.json file. The project MUST be created outside of the task to
* enable incremental compilation.
*/
const project = typescript.createProject('tsconfig.json', {
/**
* We don't use any kind of modules or <reference> tags in our project, so we
* don't need to support external modules resolving. According to the
* gulp-typescript plugin docs explicitly disabling it can improve
* compilation time.
*/
noExternalResolve: true
});
/**
* Compiles all TypeScript code in the project to JavaScript.
*
* @param enableSourcemaps Pass `true` to enable source maps generation
*/
export function typescriptTask(enableSourcemaps: boolean = false) {
let files = [`${DIR_SRC}/**/*.ts`, 'typings/browser/**/*.d.ts'];
return gulp.src(files, {base: DIR_SRC})
.pipe(gulpif(enableSourcemaps, sourcemaps.init()))
.pipe(typescript(project))
.pipe(gulpif(enableSourcemaps, sourcemaps.write()))
.pipe(gulp.dest(DIR_TMP));
}
export function copyHtmlTask() {
return gulp.src(`${DIR_SRC}/**/*.html`, {base: DIR_SRC})
.pipe(gulp.dest(DIR_TMP));
}
|
Add debugging message to middlewares. | /**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/
export function compose(middleware: Function[]) {
if (!Array.isArray(middleware))
throw new TypeError('Middleware stack must be an array!');
for (const fn of middleware) {
if (typeof fn !== 'function')
throw new TypeError('Middleware must be composed of functions!');
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function(context: any, next: Function) {
// last called middleware #
let index = -1;
return dispatch.call(this, 0);
function dispatch(i: number) {
if (i <= index)
return Promise.reject(new Error('next() called multiple times'));
index = i;
let fn = middleware[i];
if (i === middleware.length) fn = next;
if (!fn) return Promise.resolve();
try {
return Promise.resolve(
fn.call(this, context, dispatch.bind(this, i + 1)),
);
} catch (err) {
return Promise.reject(err);
}
}
};
}
| import * as _ from 'underscore';
import debug from 'debug';
const d = debug('sbase:utils');
/**
* Compose `middleware` returning a fully valid middleware comprised of all
* those which are passed.
*/
export function compose(middleware: Function[]) {
if (!Array.isArray(middleware)) {
throw new TypeError('Middleware stack must be an array!');
}
for (const fn of middleware) {
if (typeof fn !== 'function') {
throw new TypeError('Middleware must be composed of functions!');
}
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function(context: any, next: Function) {
// last called middleware #
let index = -1;
return dispatch.call(this, 0);
function dispatch(i: number) {
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'));
}
index = i;
const fn = i === middleware.length ? next : middleware[i];
if (!fn) return Promise.resolve();
const start = _.now();
try {
d('Begin of fn %O', fn.name);
return Promise.resolve(
fn.call(this, context, dispatch.bind(this, i + 1)),
);
} catch (err) {
return Promise.reject(err);
} finally {
const end = _.now();
d('End of fn %O, duration: %O', fn.name, end - start);
}
}
};
}
|
Update real feature level detection. | import { browser, by, ExpectedConditions as until, $, element } from 'protractor';
import { AppPage } from './app.page';
export class UserSettingsPage extends AppPage {
public async gotoFeaturesTab(): Promise<FeaturesTab> {
await browser.wait(until.presenceOf(element(by.cssContainingText('a', 'Features Opt-in'))));
await element(by.cssContainingText('a', 'Features Opt-in')).click();
return new FeaturesTab();
}
}
export class FeaturesTab {
public async getFeatureLevel(): Promise<string> {
await browser.wait(until.presenceOf(element(by.css('input:checked'))));
let checkedInput = await element(by.css('input:checked'));
return await checkedInput.getAttribute('id');
}
}
| import { browser, by, ExpectedConditions as until, $, element } from 'protractor';
import { AppPage } from './app.page';
export class UserSettingsPage extends AppPage {
public async gotoFeaturesTab(): Promise<FeaturesTab> {
await browser.wait(until.presenceOf(element(by.cssContainingText('a', 'Features Opt-in'))));
await element(by.cssContainingText('a', 'Features Opt-in')).click();
return new FeaturesTab();
}
}
export class FeaturesTab {
readonly featureInputXpath = '//input/ancestor::*[contains(@class, \'active\')]//span[contains(@class,\'icon-\')]';
public async getFeatureLevel(): Promise<string> {
await browser.wait(until.presenceOf(element(by.xpath(this.featureInputXpath))));
let checkedInput = await element(by.xpath(this.featureInputXpath));
let featureInputIconCss = await checkedInput.getAttribute('class');
let featureCss = featureInputIconCss.match('icon-(internal|experimental|beta|released)');
await expect(featureCss).not.toBeNull('feature css');
if (featureCss != null) {
return featureCss[1];
}
return 'null';
}
}
|
Fix usage of Observable of method | import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {Observable} from 'rxjs';
import * as myGlobals from '../globals';
@Injectable({providedIn: 'root'})
export class HomepageActivateService implements CanActivate {
config = myGlobals.config;
constructor(private router: Router) {
}
canActivate(): Observable<boolean> {
if (!this.config.showHomepage) {
this.router.navigate(['/user-mgmt/login']);
return Observable.of(false);
} else {
return Observable.of(true);
}
}
}
| import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {Observable} from 'rxjs';
import { of } from 'rxjs';
import * as myGlobals from '../globals';
@Injectable({providedIn: 'root'})
export class HomepageActivateService implements CanActivate {
config = myGlobals.config;
constructor(private router: Router) {
}
canActivate(): Observable<boolean> {
if (!this.config.showHomepage) {
this.router.navigate(['/user-mgmt/login']);
return of(false);
} else {
return of(true);
}
}
}
|
Add utility function for converting date objects to Mturk formatted date strings. | /**
* Expects a string in MTurk's URL encoded date format
* (e.g. '09262017' would be converted into a Date object for
* September 26th, 2017)
* @param encodedDate string in described format
*/
export const encodedDateStringToDate = (encodedDate: string): Date => {
const parseableDateString =
encodedDate.slice(0, 2) +
' ' +
encodedDate.slice(2, 4) +
' ' +
encodedDate.slice(4);
return new Date(Date.parse(parseableDateString));
};
| /**
* Expects a string in MTurk's URL encoded date format
* (e.g. '09262017' would be converted into a Date object for
* September 26th, 2017)
* @param encodedDate string in described format
*/
export const encodedDateStringToDate = (encodedDate: string): Date => {
const parseableDateString =
encodedDate.slice(0, 2) +
' ' +
encodedDate.slice(2, 4) +
' ' +
encodedDate.slice(4);
return new Date(Date.parse(parseableDateString));
};
/**
* Converts Date objects to MTurk formatted date strings.
* (e.g. Date object for September 26th, 2017 would be converted to '09262017')
* @param date
*/
export const dateToEncodedDateString = (date: Date): string => {
const day = padTwoDigits(date.getDay());
const month = padTwoDigits(date.getMonth());
const year = date.getFullYear().toString();
return month + day + year;
};
const padTwoDigits = (num: number): string => {
return num < 10 ? '0' + num.toString() : num.toString();
};
|
Revert to `symbol` from `unique symbol`. | declare const observableSymbol: symbol;
export default observableSymbol;
declare global {
export interface SymbolConstructor {
readonly observable: unique symbol;
}
}
| declare const observableSymbol: symbol;
export default observableSymbol;
declare global {
export interface SymbolConstructor {
readonly observable: symbol;
}
}
|
Add interface for execAsync result | import {exec} from 'child_process';
export function execAsync(command: string) {
return new Promise<any>(
(resolve, reject) => exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
}));
};
| import {exec} from 'child_process';
export interface IExecAsyncResult {
stdout: string;
stderr: string;
}
export function execAsync(command: string) {
return new Promise<IExecAsyncResult>(
(resolve, reject) => exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
}));
};
|
Update media cons. to use new token types | import { Convention } from './Convention'
import { TokenMeaning } from './Token'
import { MediaSyntaxNodeType } from '../../SyntaxNodes/MediaSyntaxNode'
import { MediaConvention } from './MediaConvention'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
const AUDIO = new MediaConvention('audio', AudioNode, TokenMeaning.AudioStartAndAudioDescription, TokenMeaning.AudioUrlAndAudioEnd)
const IMAGE = new MediaConvention('image', ImageNode, TokenMeaning.ImageStartAndAudioDescription, TokenMeaning.ImageUrlAndAudioEnd)
const VIDEO = new MediaConvention('video', VideoNode, TokenMeaning.VideoStartAndAudioDescription, TokenMeaning.VideoUrlAndAudioEnd)
export {
AUDIO,
IMAGE,
VIDEO
}
| import { MediaConvention } from './MediaConvention'
import { AudioToken } from './Tokens/AudioToken'
import { ImageToken } from './Tokens/ImageToken'
import { VideoToken } from './Tokens/VideoToken'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
const AUDIO = new MediaConvention('audio', AudioNode, AudioToken)
const IMAGE = new MediaConvention('image', ImageNode, ImageToken)
const VIDEO = new MediaConvention('video', VideoNode, VideoToken)
export {
AUDIO,
IMAGE,
VIDEO
}
|
Fix toolbar's logo placement in toolbar's template | import * as DOM from "../../core/util/dom";
interface ToolbarProps {
location: "above" | "below" | "left" | "right";
sticky: "sticky" | "non-sticky";
logo?: "normal" | "grey";
}
export default (props: ToolbarProps): HTMLElement => {
let logo;
if (props.logo != null) {
const cls = props.logo === "grey" ? "bk-grey" : null;
logo = <a href="http://bokeh.pydata.org/" target="_blank" class={["bk-logo", "bk-logo-small", cls]}></a>
}
return (
<div class={[`bk-toolbar-${props.location}`, `bk-toolbar-${props.sticky}`]}>
<div class='bk-button-bar'>
{logo}
<div class='bk-button-bar-list' type="pan" />
<div class='bk-button-bar-list' type="scroll" />
<div class='bk-button-bar-list' type="pinch" />
<div class='bk-button-bar-list' type="tap" />
<div class='bk-button-bar-list' type="press" />
<div class='bk-button-bar-list' type="rotate" />
<div class='bk-button-bar-list' type="actions" />
<div class='bk-button-bar-list' type="inspectors" />
<div class='bk-button-bar-list' type="help" />
</div>
</div>
)
}
| import * as DOM from "../../core/util/dom";
interface ToolbarProps {
location: "above" | "below" | "left" | "right";
sticky: "sticky" | "non-sticky";
logo?: "normal" | "grey";
}
export default (props: ToolbarProps): HTMLElement => {
let logo;
if (props.logo != null) {
const cls = props.logo === "grey" ? "bk-grey" : null;
logo = <a href="http://bokeh.pydata.org/" target="_blank" class={["bk-logo", "bk-logo-small", cls]}></a>
}
return (
<div class={[`bk-toolbar-${props.location}`, `bk-toolbar-${props.sticky}`]}>
{logo}
<div class='bk-button-bar'>
<div class='bk-button-bar-list' type="pan" />
<div class='bk-button-bar-list' type="scroll" />
<div class='bk-button-bar-list' type="pinch" />
<div class='bk-button-bar-list' type="tap" />
<div class='bk-button-bar-list' type="press" />
<div class='bk-button-bar-list' type="rotate" />
<div class='bk-button-bar-list' type="actions" />
<div class='bk-button-bar-list' type="inspectors" />
<div class='bk-button-bar-list' type="help" />
</div>
</div>
)
}
|
Return success: true when loader mutation is run | import { TruffleDB } from "truffle-db";
import { ArtifactsLoader } from "./artifacts";
import { schema as rootSchema } from "truffle-db/schema";
import { Workspace, schema } from "truffle-db/workspace";
const tmp = require("tmp");
import {
makeExecutableSchema
} from "@gnd/graphql-tools";
import { gql } from "apollo-server";
//dummy query here because of known issue with Apollo mutation-only schemas
const typeDefs = gql`
type Mutation {
loadArtifacts: Boolean
}
type Query {
dummy: String
}
`;
const resolvers = {
Mutation: {
loadArtifacts: {
resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => {
const tempDir = tmp.dirSync({ unsafeCleanup: true })
const compilationConfig = {
contracts_directory: contractsDirectory,
contracts_build_directory: tempDir.name,
all: true
}
const loader = new ArtifactsLoader(db, compilationConfig);
await loader.load()
tempDir.removeCallback();
return true;
}
}
}
}
export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
| import { TruffleDB } from "truffle-db";
import { ArtifactsLoader } from "./artifacts";
import { schema as rootSchema } from "truffle-db/schema";
import { Workspace, schema } from "truffle-db/workspace";
const tmp = require("tmp");
import {
makeExecutableSchema
} from "@gnd/graphql-tools";
import { gql } from "apollo-server";
//dummy query here because of known issue with Apollo mutation-only schemas
const typeDefs = gql`
type ArtifactsLoadPayload {
success: Boolean
}
type Mutation {
artifactsLoad: ArtifactsLoadPayload
}
type Query {
dummy: String
}
`;
const resolvers = {
Mutation: {
artifactsLoad: {
resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => {
const tempDir = tmp.dirSync({ unsafeCleanup: true })
const compilationConfig = {
contracts_directory: contractsDirectory,
contracts_build_directory: tempDir.name,
all: true
}
const loader = new ArtifactsLoader(db, compilationConfig);
await loader.load()
tempDir.removeCallback();
return true;
}
}
},
ArtifactsLoadPayload: {
success: {
resolve: () => true
}
}
}
export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
|
Fix windows paths in scanner | import * as Path from "path";
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, ""));
return []
.concat(files as any)
.map((file: string) => {
if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
file = file.replace(/\.ts$/i, ".js");
}
return Path.resolve(file);
})
.concat(excludes as any);
}
| import * as Path from "path";
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, "").replace(/\\/g, "/"));
return []
.concat(files as any)
.map((file: string) => {
if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
file = file.replace(/\.ts$/i, ".js");
}
return Path.resolve(file).replace(/\\/g, "/");
})
.concat(excludes as any);
}
|
Remove scroll after every event for perf | module ImprovedInitiative {
export class EventLog {
Events = ko.observableArray<string>();
LatestEvent = ko.pureComputed(() => this.Events()[this.Events().length - 1] || "Welcome to Improved Initiative!");
EventsTail = ko.pureComputed(() => this.Events().slice(0, this.Events().length - 1));
AddEvent = (event: string) => {
this.Events.push(event);
this.scrollToBottomOfLog();
}
ToggleFullLog = () => {
if(this.ShowFullLog()) {
this.ShowFullLog(false);
$('.combatants').css('flex-shrink', 1);
} else {
this.ShowFullLog(true);
$('.combatants').css('flex-shrink', 0);
this.scrollToBottomOfLog();
}
}
ShowFullLog = ko.observable<boolean>(false);
private element = $('.event-log');
private scrollToBottomOfLog = () => {
let scrollHeight = this.element[0].scrollHeight;
this.element.scrollTop(scrollHeight);
}
}
} | module ImprovedInitiative {
export class EventLog {
Events = ko.observableArray<string>();
LatestEvent = ko.pureComputed(() => this.Events()[this.Events().length - 1] || "Welcome to Improved Initiative!");
EventsTail = ko.pureComputed(() => this.Events().slice(0, this.Events().length - 1));
AddEvent = (event: string) => {
this.Events.push(event);
}
ToggleFullLog = () => {
if(this.ShowFullLog()) {
this.ShowFullLog(false);
$('.combatants').css('flex-shrink', 1);
} else {
this.ShowFullLog(true);
$('.combatants').css('flex-shrink', 0);
this.scrollToBottomOfLog();
}
}
ShowFullLog = ko.observable<boolean>(false);
private element = $('.event-log');
private scrollToBottomOfLog = () => {
let scrollHeight = this.element[0].scrollHeight;
this.element.scrollTop(scrollHeight);
}
}
} |
Return Undefined on Empty Input | import * as React from "react";
export interface InputProps{
onChange: (value: any) => void,
label?: string
id?: string,
class?: string,
value?: string
}
export function Input(props: InputProps) {
return <div className={props.class +" float-label"}>
<input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value)} />
<label> {props.label} </label>
</div>
} | import * as React from "react";
export interface InputProps{
onChange: (value: any) => void,
label?: string
id?: string,
class?: string,
value?: string
}
export function Input(props: InputProps) {
return <div className={props.class +" float-label"}>
<input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value === ""?undefined:e.target.value)} />
<label> {props.label} </label>
</div>
} |
Fix cgroup not deleted after sandbox finished | import { SandboxParameter } from './interfaces';
import nativeAddon from './nativeAddon';
import { SandboxProcess } from './sandboxProcess';
import { existsSync } from 'fs';
import * as randomString from 'randomstring';
import * as path from 'path';
export * from './interfaces';
if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) {
throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme.");
}
export function startSandbox(parameter: SandboxParameter): SandboxProcess {
const actualParameter = Object.assign({}, parameter);
actualParameter.cgroup = path.join(actualParameter.cgroup, randomString.generate(9));
const startResult: { pid: number; execParam: ArrayBuffer } = nativeAddon.startSandbox(actualParameter);
return new SandboxProcess(parameter, startResult.pid, startResult.execParam);
};
| import { SandboxParameter } from './interfaces';
import nativeAddon from './nativeAddon';
import { SandboxProcess } from './sandboxProcess';
import { existsSync } from 'fs';
import * as randomString from 'randomstring';
import * as path from 'path';
export * from './interfaces';
if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) {
throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme.");
}
export function startSandbox(parameter: SandboxParameter): SandboxProcess {
const actualParameter = Object.assign({}, parameter);
actualParameter.cgroup = path.join(actualParameter.cgroup, randomString.generate(9));
const startResult: { pid: number; execParam: ArrayBuffer } = nativeAddon.startSandbox(actualParameter);
return new SandboxProcess(actualParameter, startResult.pid, startResult.execParam);
};
|
Make command optional for IMiddlewareArguments | import {
middleware,
Middleware as GenericMiddleware
} from '@pawelgalazka/middleware'
import { useMiddlewares } from './middlewares'
export { useMiddlewares } from './middlewares'
export { help, withHelp } from './middlewares/helper'
export { rawArgs } from './middlewares/rawArgsParser'
export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any
export type CLIParams = string[]
export type CommandsModule = ICommandsDictionary | CommandFunction
export type Middleware = GenericMiddleware<IMiddlewareArguments>
export interface ICLIOptions {
[key: string]: number | string | boolean
}
export interface ICommandsDictionary {
[namespace: string]: CommandsModule
}
export interface IMiddlewareArguments {
options: ICLIOptions
params: CLIParams
definition: CommandsModule
namespace: string
command: CommandFunction
reject: (error: Error) => void
}
export class CLIError extends Error {}
export function cli(
definition: CommandsModule,
middlewares: Middleware[] = useMiddlewares()
) {
middleware<IMiddlewareArguments>(middlewares)({
command: () => null,
definition,
namespace: '',
options: {},
params: [],
reject: error => {
throw error
}
})
}
| import {
middleware,
Middleware as GenericMiddleware
} from '@pawelgalazka/middleware'
import { useMiddlewares } from './middlewares'
export { useMiddlewares } from './middlewares'
export { help, withHelp } from './middlewares/helper'
export { rawArgs } from './middlewares/rawArgsParser'
export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any
export type CLIParams = string[]
export type CommandsModule = ICommandsDictionary | CommandFunction
export type Middleware = GenericMiddleware<IMiddlewareArguments>
export interface ICLIOptions {
[key: string]: number | string | boolean
}
export interface ICommandsDictionary {
[namespace: string]: CommandsModule
}
export interface IMiddlewareArguments {
options: ICLIOptions
params: CLIParams
definition: CommandsModule
namespace: string
command?: CommandFunction
reject: (error: Error) => void
}
export class CLIError extends Error {}
export function cli(
definition: CommandsModule,
middlewares: Middleware[] = useMiddlewares()
) {
middleware<IMiddlewareArguments>(middlewares)({
definition,
namespace: '',
options: {},
params: [],
reject: error => {
throw error
}
})
}
|
Validate accepts an array of models |
import {PropertyType} from "./model/property-type";
import {ModelOptions, ProcessMode} from "./model/options";
import {ValidateResult} from "./manager/validate";
import {model} from "./model/model";
import {type} from "./decorator/type";
import {length} from "./decorator/length";
import {range} from "./decorator/range";
import {manager} from "./manager/manager";
function options(options: ModelOptions) {
manager.setGlobalOptions(options);
}
function validate(model: Object): boolean;
function validate(model: Object, result: ValidateResult);
function validate(model: Object, result?: ValidateResult) {
let error = manager.validate(model);
if (!result) {
return error == null;
} else {
result(error);
}
}
export {
PropertyType, ProcessMode,
model, options, validate,
type, length, range
} |
import {PropertyType} from "./model/property-type";
import {ModelOptions, ProcessMode} from "./model/options";
import {ValidateResult} from "./manager/validate";
import {model} from "./model/model";
import {type} from "./decorator/type";
import {length} from "./decorator/length";
import {range} from "./decorator/range";
import {manager} from "./manager/manager";
function options(options: ModelOptions) {
manager.setGlobalOptions(options);
}
function validate(model: Object): boolean;
function validate(model: Object, result: ValidateResult);
function validate(models: Object[]): boolean;
function validate(models: Object[], result: ValidateResult);
function validate(modelOrArray: Object[], resultOrNull?: ValidateResult) {
let models: Object[];
if (Array.isArray(modelOrArray)) {
models = modelOrArray;
} else {
models = [modelOrArray];
}
for (let model of models) {
let error = manager.validate(model);
if (error != null) {
if (!resultOrNull) {
return false;
} else {
resultOrNull(error);
return;
}
}
}
if (!resultOrNull) {
return true;
} else {
resultOrNull(null);
}
}
export {
PropertyType, ProcessMode,
model, options, validate,
type, length, range
} |
Expand apphost to support multiple components | import * as React from 'react';
export default class AppHost extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
React.Children.only(this.props.children)
);
}
}
| import * as React from 'react';
export default class AppHost extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
Fix naming mismatches in the Haskell/Rust sets | import { createTrainingSet } from './training-set';
export const goRustAssignmentsTrainingSet = {
title: "Go vs Rust",
left: "Go.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 19, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const haskellRustAssignmentsTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const goRustTrainingSet = {
title: "Go vs Rust",
left: "Go.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 23, prefix: ".png" }, { name: "Rust.", number: 23, prefix: ".png" })
};
export const haskellRustTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
};
| import { createTrainingSet } from './training-set';
export const goRustAssignmentsTrainingSet = {
title: "Go vs Rust",
left: "Go.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 19, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const haskellRustAssignmentsTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Haskell.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const goRustTrainingSet = {
title: "Go vs Rust",
left: "Go.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 23, prefix: ".png" }, { name: "Rust.", number: 23, prefix: ".png" })
};
export const haskellRustTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Haskell.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
};
|
Revert "render blank content for unknown types" | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import StringWithComponent from 'components/string-with-component';
import BeatmapsetDiscussionPostJson from 'interfaces/beatmapset-discussion-post-json';
import UserJson from 'interfaces/user-json';
import { route } from 'laroute';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
interface Props {
post: BeatmapsetDiscussionPostJson;
user: UserJson;
}
export default function SystemPost({ post, user }: Props) {
if (!post.system) return null;
if (post.message.type !== 'resolved') {
console.error(`unknown type: ${post.message.type}`);
}
const className = classWithModifiers('beatmap-discussion-system-post', post.message.type, {
deleted: post.deleted_at != null,
});
return (
<div className={className}>
<div className='beatmap-discussion-system-post__content'>
{post.message.type === 'resolved' && (
<StringWithComponent
mappings={{
user: <a
className='beatmap-discussion-system-post__user'
href={route('users.show', { user: user.id })}
>
{user.username}
</a>,
}}
pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
/>
)}
</div>
</div>
);
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import StringWithComponent from 'components/string-with-component';
import BeatmapsetDiscussionPostJson from 'interfaces/beatmapset-discussion-post-json';
import UserJson from 'interfaces/user-json';
import { route } from 'laroute';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
interface Props {
post: BeatmapsetDiscussionPostJson;
user: UserJson;
}
export default function SystemPost({ post, user }: Props) {
if (!post.system) return null;
if (post.message.type !== 'resolved') return null;
const className = classWithModifiers('beatmap-discussion-system-post', post.message.type, {
deleted: post.deleted_at != null,
});
return (
<div className={className}>
<div className='beatmap-discussion-system-post__content'>
<StringWithComponent
mappings={{
user: <a
className='beatmap-discussion-system-post__user'
href={route('users.show', { user: user.id })}
>
{user.username}
</a>,
}}
pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
/>
</div>
</div>
);
}
|
Send message to all windows (for now) | export interface IMessage {
data: {};
name: string;
sender: string;
}
export class Service {
private uid : number;
constructor(public _postMessage) {
var _self = this;
}
private postMessage(name: string, data: {}) : void {
var _self = this;
var message : IMessage = {
data: data,
name: name,
sender: _self.uid
};
_self._postMessage(JSON.stringify(message));
}
postResize(height: number) : void {
var _self = this;
_self.postMessage(
"resize",
{height: height}
);
}
}
export var factory = ($window) => new Service((...args) => $window.postMessage.apply($window, args));
| export interface IMessage {
data: {};
name: string;
sender: string;
}
export class Service {
private uid : number;
constructor(public _postMessage) {
var _self = this;
}
private postMessage(name: string, data: {}) : void {
var _self = this;
var message : IMessage = {
data: data,
name: name,
sender: _self.uid
};
_self._postMessage(JSON.stringify(message), "*");
}
postResize(height: number) : void {
var _self = this;
_self.postMessage(
"resize",
{height: height}
);
}
}
export var factory = ($window) => new Service((...args) => $window.postMessage.apply($window, args));
|
Add passing naked URL test |
import { expect } from 'chai'
import * as Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { LinkNode } from '../../SyntaxNodes/LinkNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
describe('A naked URL', () => {
it('produces a link node. The content of the link is the URL minus its protocol', () => {
expect(Up.toAst('https://archive.org')).to.be.eql(
insideDocumentAndParagraph([
new LinkNode([
new PlainTextNode('archive.org')
], 'https://archive.org')
]))
})
})
|
import { expect } from 'chai'
import * as Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { LinkNode } from '../../SyntaxNodes/LinkNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
describe('A naked URL', () => {
it('produces a link node. The content of the link is the URL minus its protocol', () => {
expect(Up.toAst('https://archive.org')).to.be.eql(
insideDocumentAndParagraph([
new LinkNode([
new PlainTextNode('archive.org')
], 'https://archive.org')
]))
})
it('is terminated by a space', () => {
expect(Up.toAst('https://archive.org ')).to.be.eql(
insideDocumentAndParagraph([
new LinkNode([
new PlainTextNode('archive.org')
], 'https://archive.org')
]))
})
}) |
Remove roles from our entity model | import { Affiliation, Household } from 'cmpd-common-api';
import { BaseEntity, Column, Entity, JoinColumn, OneToMany, OneToOne, PrimaryColumn } from 'typeorm';
@Entity('nominators')
export class Nominator extends BaseEntity {
private constructor(props) {
super();
Object.assign(this, props);
}
@PrimaryColumn('text') id: string;
@Column('text') name: string;
@Column('text') email: string;
@Column('text', { nullable: true })
rank: string;
@Column('text', { nullable: true })
role: string;
@Column('text', { nullable: true })
phone: string;
@Column('boolean', { default: true })
disabled: boolean;
@Column('boolean', { name: 'email_verified', default: false })
emailVerified: boolean;
@Column('text') phoneNumber: string;
@Column('int', { name: 'nomination_limit', default: 5 })
nominationLimit: number;
@Column('int', { name: 'affiliation_id', nullable: true })
affiliationId: number;
@OneToOne(() => Affiliation)
@JoinColumn({ name: 'affiliation_id' })
affiliation: Affiliation;
@OneToMany(() => Household, household => household.nominator)
households: Household[];
static fromJSON(props) {
const entity = new Nominator(props);
return entity;
}
}
| import { Affiliation, Household } from 'cmpd-common-api';
import { BaseEntity, Column, Entity, JoinColumn, OneToMany, OneToOne, PrimaryColumn } from 'typeorm';
@Entity('nominators')
export class Nominator extends BaseEntity {
private constructor(props) {
super();
Object.assign(this, props);
}
@PrimaryColumn('text') id: string;
@Column('text') name: string;
@Column('text') email: string;
@Column('text', { nullable: true })
rank: string;
// @Column('text', { nullable: true })
// role: string;
@Column('text', { nullable: true })
phone: string;
@Column('boolean', { default: true })
disabled: boolean;
@Column('boolean', { name: 'email_verified', default: false })
emailVerified: boolean;
@Column('text') phoneNumber: string;
@Column('int', { name: 'nomination_limit', default: 5 })
nominationLimit: number;
@Column('int', { name: 'affiliation_id', nullable: true })
affiliationId: number;
@OneToOne(() => Affiliation)
@JoinColumn({ name: 'affiliation_id' })
affiliation: Affiliation;
@OneToMany(() => Household, household => household.nominator)
households: Household[];
static fromJSON(props) {
const entity = new Nominator(props);
return entity;
}
}
|
Fix typescript for lazy-loaded iframes | import React, { Component } from 'react';
import window from 'global';
interface IFrameProps {
id: string;
key?: string;
title: string;
src: string;
allowFullScreen: boolean;
scale: number;
style?: any;
}
interface BodyStyle {
width: string;
height: string;
transform: string;
transformOrigin: string;
}
export class IFrame extends Component<IFrameProps> {
iframe: any = null;
componentDidMount() {
const { id } = this.props;
this.iframe = window.document.getElementById(id);
}
shouldComponentUpdate(nextProps: IFrameProps) {
const { scale } = nextProps;
// eslint-disable-next-line react/destructuring-assignment
if (scale !== this.props.scale) {
this.setIframeBodyStyle({
width: `${scale * 100}%`,
height: `${scale * 100}%`,
transform: `scale(${1 / scale})`,
transformOrigin: 'top left',
});
}
return false;
}
setIframeBodyStyle(style: BodyStyle) {
return Object.assign(this.iframe.contentDocument.body.style, style);
}
render() {
const { id, title, src, allowFullScreen, scale, ...rest } = this.props;
return <iframe id={id} title={title} src={src} allowFullScreen={allowFullScreen} {...rest} loading="lazy"/>;
}
}
| import React, { Component } from 'react';
import window from 'global';
interface IFrameProps {
id: string;
key?: string;
title: string;
src: string;
allowFullScreen: boolean;
scale: number;
style?: any;
}
interface BodyStyle {
width: string;
height: string;
transform: string;
transformOrigin: string;
}
export class IFrame extends Component<IFrameProps> {
iframe: any = null;
componentDidMount() {
const { id } = this.props;
this.iframe = window.document.getElementById(id);
}
shouldComponentUpdate(nextProps: IFrameProps) {
const { scale } = nextProps;
// eslint-disable-next-line react/destructuring-assignment
if (scale !== this.props.scale) {
this.setIframeBodyStyle({
width: `${scale * 100}%`,
height: `${scale * 100}%`,
transform: `scale(${1 / scale})`,
transformOrigin: 'top left',
});
}
return false;
}
setIframeBodyStyle(style: BodyStyle) {
return Object.assign(this.iframe.contentDocument.body.style, style);
}
render() {
const { id, title, src, allowFullScreen, scale, ...rest } = this.props;
return (
<iframe
id={id}
title={title}
src={src}
allowFullScreen={allowFullScreen}
// @ts-ignore
loading="lazy"
{...rest}
/>
);
}
}
|
Add tapReporter to package export | export { default as matchTestFiles } from "./matchTestFiles";
export { default as globals } from "./globals";
export { default as specSyntax } from "./specSyntax";
export { default as suiteSyntax } from "./suiteSyntax";
export { default as runner } from "./runner";
export { default as resultsReporter } from "./resultsReporter";
export { default as tableReporter } from "./tableReporter";
export { default as dotReporter } from "./dotReporter";
export { default as setupReporter } from "./setupReporter";
export { default as junit } from "./junit";
export { default as exitOnErroredTests } from "./exitOnErroredTests";
export { default as exitOnFailedTests } from "./exitOnFailedTests";
export { default as compose } from "./compose";
export { default as starter } from "./starter";
export { default as event } from "./event";
export { default as args } from "./args";
export { default as assert } from "./assert";
export { default as random } from "./random";
export { default as mock } from "./mock";
export { default as log } from "./log";
| export { default as matchTestFiles } from "./matchTestFiles";
export { default as globals } from "./globals";
export { default as specSyntax } from "./specSyntax";
export { default as suiteSyntax } from "./suiteSyntax";
export { default as runner } from "./runner";
export { default as resultsReporter } from "./resultsReporter";
export { default as tableReporter } from "./tableReporter";
export { default as dotReporter } from "./dotReporter";
export { default as tapReporter } from "./tapReporter";
export { default as setupReporter } from "./setupReporter";
export { default as junit } from "./junit";
export { default as exitOnErroredTests } from "./exitOnErroredTests";
export { default as exitOnFailedTests } from "./exitOnFailedTests";
export { default as compose } from "./compose";
export { default as starter } from "./starter";
export { default as event } from "./event";
export { default as args } from "./args";
export { default as assert } from "./assert";
export { default as random } from "./random";
export { default as mock } from "./mock";
export { default as log } from "./log";
|
Fix 404.html import in app template | /**
* Created by Caleydo Team on 31.08.2016.
*/
import 'file-loader?name=index.html!extract-loader!html-loader?interpolate!./index.html';
import 'file-loader?name=404.html-loader!./404.html';
import 'file-loader?name=robots.txt!./robots.txt';
import 'phovea_ui/src/_bootstrap';
import './style.scss';
import {create as createApp} from './app';
import {create as createHeader, AppHeaderLink} from 'phovea_ui/src/header';
import {APP_NAME} from './language';
createHeader(
<HTMLElement>document.querySelector('#caleydoHeader'),
{ appLink: new AppHeaderLink(APP_NAME) }
);
const parent = document.querySelector('#app');
createApp(parent).init();
| /**
* Created by Caleydo Team on 31.08.2016.
*/
import 'file-loader?name=index.html!extract-loader!html-loader?interpolate!./index.html';
import 'file-loader?name=404.html!./404.html';
import 'file-loader?name=robots.txt!./robots.txt';
import 'phovea_ui/src/_bootstrap';
import './style.scss';
import {create as createApp} from './app';
import {create as createHeader, AppHeaderLink} from 'phovea_ui/src/header';
import {APP_NAME} from './language';
createHeader(
<HTMLElement>document.querySelector('#caleydoHeader'),
{ appLink: new AppHeaderLink(APP_NAME) }
);
const parent = document.querySelector('#app');
createApp(parent).init();
|
Add more strict types to DB methods | import { openDB, type IDBPDatabase } from 'idb';
export async function getDB() {
const db = await openDB('pokeapi.js', 1, {
async upgrade(db) {
const objectStore = db.createObjectStore('cachedResources', {
keyPath: 'cacheKey',
});
objectStore.createIndex('whenCached', 'whenCached', {
unique: false,
});
await objectStore.transaction.done
}
});
return db;
}
export async function get(db: IDBPDatabase, cacheKey: string) {
const tx = db.transaction('cachedResources', 'readonly');
const store = tx.store;
return store.get(cacheKey);
}
export async function put(db: IDBPDatabase, cacheKey: string, data: any) {
const tx = db.transaction('cachedResources', 'readwrite');
const store = tx.store;
const whenCached = Date.now();
return store.put({
cacheKey,
whenCached,
data,
})
}
export async function deleteKey(db: IDBPDatabase, cacheKey: string) {
const tx = db.transaction('cachedResources', 'readwrite');
const store = tx.store;
return store.delete(cacheKey);
} | import { openDB, type IDBPDatabase, type DBSchema } from 'idb';
interface CacheDBSchema extends DBSchema {
cachedResources: {
key: string;
value: {
cacheKey: string;
whenCached: number;
data: string;
};
indexes: {
whenCached: number
}
};
}
export async function getDB() {
const db = await openDB<CacheDBSchema>('pokeapi.js', 1, {
async upgrade(db) {
const objectStore = db.createObjectStore('cachedResources', {
keyPath: 'cacheKey',
});
objectStore.createIndex('whenCached', 'whenCached', {
unique: false,
});
await objectStore.transaction.done
}
});
return db;
}
export async function get(db: IDBPDatabase<CacheDBSchema>, cacheKey: string) {
const tx = db.transaction('cachedResources', 'readonly');
const store = tx.store;
return store.get(cacheKey);
}
export async function put(db: IDBPDatabase<CacheDBSchema>, cacheKey: string, data: string) {
const tx = db.transaction('cachedResources', 'readwrite');
const store = tx.store;
const whenCached = Date.now();
return store.put({
cacheKey,
whenCached,
data,
})
}
export async function deleteKey(db: IDBPDatabase<CacheDBSchema>, cacheKey: string) {
const tx = db.transaction('cachedResources', 'readwrite');
const store = tx.store;
return store.delete(cacheKey);
} |
Disable atom task wrapping of all event handlers. | declare class WeakMap< Key , Value > {
get( key : Key ) : Value
set( key : Key , value : Value ) : this
}
namespace $ {
export class $mol_view_dom extends $mol_object {
static nodes = new ( WeakMap || $mol_dict )< $mol_view , Element >()
static node( view : $mol_view ) {
let node = $mol_view_dom.nodes.get( view )
if( !node ) {
node = $mol_dom_make(
{
localName : view.dom_name() ,
namespaceURI : view.dom_name_space() ,
}
)
$mol_view_dom.mount( view , node )
}
return node
}
static mount( view : $mol_view , node : Element ) {
$mol_view_dom.nodes.set( view , node )
$mol_dom_render(
node , {
id : view.toString() ,
attributes : view.attr_static() ,
events : view.event_wrapped() ,
}
)
for( let plugin of view.plugins() ) {
$mol_view_dom.nodes.set( plugin , node )
$mol_dom_render(
node , {
attributes : plugin.attr_static() ,
events : plugin.event_wrapped() ,
}
)
}
return node
}
}
}
| declare class WeakMap< Key , Value > {
get( key : Key ) : Value
set( key : Key , value : Value ) : this
}
namespace $ {
export class $mol_view_dom extends $mol_object {
static nodes = new ( WeakMap || $mol_dict )< $mol_view , Element >()
static node( view : $mol_view ) {
let node = $mol_view_dom.nodes.get( view )
if( !node ) {
node = $mol_dom_make(
{
localName : view.dom_name() ,
namespaceURI : view.dom_name_space() ,
}
)
$mol_view_dom.mount( view , node )
}
return node
}
static mount( view : $mol_view , node : Element ) {
$mol_view_dom.nodes.set( view , node )
$mol_dom_render(
node , {
id : view.toString() ,
attributes : view.attr_static() ,
events : view.event() ,
}
)
for( let plugin of view.plugins() ) {
$mol_view_dom.nodes.set( plugin , node )
$mol_dom_render(
node , {
attributes : plugin.attr_static() ,
events : plugin.event() ,
}
)
}
return node
}
}
}
|
Extend Contraint with searchRecursively boolean | export interface Constraint {
value: string|string[];
type: string; // add | subtract
}
/**
* Companion object
*/
export class Constraint {
public static convertTo(constraint: Constraint|string|string[]): Constraint {
return (Array.isArray(constraint) || typeof(constraint) == 'string')
? { value: constraint, type: 'add' }
: constraint;
}
} | export interface Constraint {
value: string|string[];
type: string; // add | subtract
searchRecursively?: boolean;
}
export class Constraint {
public static convertTo(constraint: Constraint|string|string[]): Constraint {
return (Array.isArray(constraint) || typeof(constraint) == 'string')
? { value: constraint, type: 'add', searchRecursively: false }
: constraint;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.