Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Throw on edge record, too. | import { FactRecord, FactReference } from '../storage';
export type EdgeRecord = {
predecessor_hash: string,
predecessor_type: string,
successor_hash: string,
successor_type: string,
role: string
};
function makeEdgeRecord(predecessor: FactReference, successor: FactRecord, role: string): EdgeRecord {
return {
predecessor_hash: predecessor.hash,
predecessor_type: predecessor.type,
successor_hash: successor.hash,
successor_type: successor.type,
role
};
}
export function makeEdgeRecords(fact: FactRecord): EdgeRecord[] {
let records: EdgeRecord[] = [];
for (const role in fact.predecessors) {
const predecessor = fact.predecessors[role];
if (Array.isArray(predecessor)) {
records = records.concat(predecessor.map(p => makeEdgeRecord(p, fact, role)));
}
else {
records.push(makeEdgeRecord(predecessor, fact, role));
}
}
return records;
} | import { FactRecord, FactReference } from '../storage';
export type EdgeRecord = {
predecessor_hash: string,
predecessor_type: string,
successor_hash: string,
successor_type: string,
role: string
};
function makeEdgeRecord(predecessor: FactReference, successor: FactRecord, role: string): EdgeRecord {
if (!predecessor.hash || !predecessor.type || !successor.hash || !successor.type) {
throw new Error('Attempting to save edge with null hash or type.');
}
return {
predecessor_hash: predecessor.hash,
predecessor_type: predecessor.type,
successor_hash: successor.hash,
successor_type: successor.type,
role
};
}
export function makeEdgeRecords(fact: FactRecord): EdgeRecord[] {
let records: EdgeRecord[] = [];
for (const role in fact.predecessors) {
const predecessor = fact.predecessors[role];
if (Array.isArray(predecessor)) {
records = records.concat(predecessor.map(p => makeEdgeRecord(p, fact, role)));
}
else {
records.push(makeEdgeRecord(predecessor, fact, role));
}
}
return records;
} |
Drop context and replace it with HOC | import * as invariant from "invariant";
import * as PropTypes from "prop-types";
import * as React from "react";
interface NavigatorProps {
children: ((
navigate: (url: string, replace?: boolean, preserveQs?: boolean) => any
) => React.ReactElement<any>);
}
const Navigator: React.StatelessComponent<NavigatorProps> = (
{ children },
{ router }
) => {
invariant(router, "You should not use <Navigator> outside a <Router>");
const {
history,
route: {
location: { search }
}
} = router;
const navigate = (url, replace = false, preserveQs = false) => {
const targetUrl = preserveQs ? url + search : url;
replace ? history.replace(targetUrl) : history.push(targetUrl);
window.scrollTo({ top: 0, behavior: "smooth" });
};
return children(navigate);
};
Navigator.contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired
}).isRequired
})
};
Navigator.displayName = "Navigator";
interface NavigatorLinkProps {
replace?: boolean;
to: string;
children: ((navigate: () => any) => React.ReactElement<any>);
}
export const NavigatorLink: React.StatelessComponent<NavigatorLinkProps> = ({
children,
replace,
to
}) => (
<Navigator>{navigate => children(() => navigate(to, replace))}</Navigator>
);
NavigatorLink.displayName = "NavigatorLink";
export default Navigator;
| import * as React from "react";
import { RouteComponentProps, withRouter } from "react-router";
interface NavigatorProps {
children: (
navigate: (url: string, replace?: boolean, preserveQs?: boolean) => any
) => React.ReactElement<any>;
}
const Navigator = withRouter<NavigatorProps & RouteComponentProps<any>>(
({ children, location, history }) => {
const { search } = location;
const navigate = (url, replace = false, preserveQs = false) => {
const targetUrl = preserveQs ? url + search : url;
replace ? history.replace(targetUrl) : history.push(targetUrl);
window.scrollTo({ top: 0, behavior: "smooth" });
};
return children(navigate);
}
);
Navigator.displayName = "Navigator";
interface NavigatorLinkProps {
replace?: boolean;
to: string;
children: (navigate: () => any) => React.ReactElement<any>;
}
export const NavigatorLink: React.StatelessComponent<NavigatorLinkProps> = ({
children,
replace,
to
}) => (
<Navigator>{navigate => children(() => navigate(to, replace))}</Navigator>
);
NavigatorLink.displayName = "NavigatorLink";
export default Navigator;
|
Fix missing module import of | import { NgModule } from '@angular/core';
import {
AdjustMarginDirective,
Display1Directive,
Display2Directive,
Display3Directive,
Display4Directive,
HeadlineDirective,
TitleDirective,
Subheading1Directive,
Subheading2Directive,
Body1Directive,
Body2Directive,
CaptionDirective
} from './typography.directive';
const TYPOGRAPHY_DIRECTIVES = [
AdjustMarginDirective,
Display1Directive,
Display2Directive,
Display3Directive,
Display4Directive,
HeadlineDirective,
TitleDirective,
Subheading1Directive,
Subheading2Directive,
Body1Directive,
Body2Directive,
CaptionDirective
];
@NgModule({
exports: [TYPOGRAPHY_DIRECTIVES],
declarations: [TYPOGRAPHY_DIRECTIVES],
})
export class TypographyModule { } | import { NgModule } from '@angular/core';
import {
Typography,
AdjustMarginDirective,
Display1Directive,
Display2Directive,
Display3Directive,
Display4Directive,
HeadlineDirective,
TitleDirective,
Subheading1Directive,
Subheading2Directive,
Body1Directive,
Body2Directive,
CaptionDirective
} from './typography.directive';
const TYPOGRAPHY_DIRECTIVES = [
Typography,
AdjustMarginDirective,
Display1Directive,
Display2Directive,
Display3Directive,
Display4Directive,
HeadlineDirective,
TitleDirective,
Subheading1Directive,
Subheading2Directive,
Body1Directive,
Body2Directive,
CaptionDirective
];
@NgModule({
exports: [TYPOGRAPHY_DIRECTIVES],
declarations: [TYPOGRAPHY_DIRECTIVES],
})
export class TypographyModule { } |
Throw error if no options | /// <reference path="../typings/node/node.d.ts" />
import * as fs from 'fs';
export class Dependument {
private source: string;
private output: string;
constructor(options: any) {
if (!options.source) {
throw new Error("No source path specified in options");
}
if (!options.output) {
throw new Error("No output path specified in options");
}
this.source = options.source;
this.output = options.output;
}
writeOutput() {
fs.writeFile(this.output, 'dependument test writeOutput', (err) => {
if (err) throw err;
console.log(`Output written to ${this.output}`);
});
}
}
| /// <reference path="../typings/node/node.d.ts" />
import * as fs from 'fs';
export class Dependument {
private source: string;
private output: string;
constructor(options: any) {
if (!options) {
throw new Error("No options provided");
}
if (!options.source) {
throw new Error("No source path specified in options");
}
if (!options.output) {
throw new Error("No output path specified in options");
}
this.source = options.source;
this.output = options.output;
}
writeOutput() {
fs.writeFile(this.output, 'dependument test writeOutput', (err) => {
if (err) throw err;
console.log(`Output written to ${this.output}`);
});
}
}
|
Remove random loadout from angular | import { module } from 'angular';
import { LoadoutDrawerComponent } from './loadout-drawer.component';
import { LoadoutPopupComponent } from './loadout-popup.component';
import { react2angular } from 'react2angular';
import RandomLoadoutButton from './random/RandomLoadoutButton';
export default module('loadoutModule', [])
.component('dimLoadoutPopup', LoadoutPopupComponent)
.component('loadoutDrawer', LoadoutDrawerComponent)
.component('randomLoadout', react2angular(RandomLoadoutButton, ['destinyVersion']))
.name;
| import { module } from 'angular';
import { LoadoutDrawerComponent } from './loadout-drawer.component';
import { LoadoutPopupComponent } from './loadout-popup.component';
export default module('loadoutModule', [])
.component('dimLoadoutPopup', LoadoutPopupComponent)
.component('loadoutDrawer', LoadoutDrawerComponent)
.name;
|
Remove the dev tools opening by default | import {app, BrowserWindow} from "electron";
let win;
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL(`file://${__dirname}/app/view/index.html`);
// win.webContents.openDevTools();
win.on("closed", () => {
win = null;
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church
});
app.on("activate", () => {
win === null && createWindow(); // Code like if you were in Satan's church
}); | import {app, BrowserWindow} from "electron";
let win;
function createWindow() {
win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL(`file://${__dirname}/app/view/index.html`);
win.on("closed", () => {
win = null;
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church
});
app.on("activate", () => {
win === null && createWindow(); // Code like if you were in Satan's church
}); |
Add missing export of RLPObject | import BN = require('bn.js')
export type RLPInput = Buffer | string | number | Uint8Array | BN | RLPObject | RLPArray | null
export interface RLPArray extends Array<RLPInput> {}
interface RLPObject {
[x: string]: RLPInput
}
export interface RLPDecoded {
data: Buffer | Buffer[]
remainder: Buffer
}
| import BN = require('bn.js')
export type RLPInput = Buffer | string | number | Uint8Array | BN | RLPObject | RLPArray | null
export interface RLPArray extends Array<RLPInput> {}
export interface RLPObject {
[x: string]: RLPInput
}
export interface RLPDecoded {
data: Buffer | Buffer[]
remainder: Buffer
}
|
Move hasOwnProperty to the last export | export * from './types'
export * from './clone'
export * from './hasOwnProperty'
export * from './invoker'
export * from './isEmpty'
export * from './keys'
export * from './length'
export * from './lensPath'
export * from './lensProp'
export * from './path'
export * from './prop'
export * from './set'
export * from './values'
| export * from './types'
export * from './clone'
export * from './invoker'
export * from './isEmpty'
export * from './keys'
export * from './length'
export * from './lensPath'
export * from './lensProp'
export * from './path'
export * from './prop'
export * from './set'
export * from './values'
// export last to avoid conflicts with exports native hasOwnProperty
export * from './hasOwnProperty'
|
Add types to enforce the function returning a number | import Css from '../properties/Css';
import Dimension from '../../impl/Dimension';
import Element from '../node/Element';
var api = Dimension('width', function (element: Element) {
// IMO passing this function is better than using dom['offset' + 'width']
return element.dom().offsetWidth;
});
var set = function (element: Element, h: string | number) {
api.set(element, h);
};
var get = function (element: Element) {
return api.get(element);
};
var getOuter = function (element: Element) {
return api.getOuter(element);
};
var setMax = function (element: Element, value: number) {
// These properties affect the absolute max-height, they are not counted natively, we want to include these properties.
var inclusions = [ 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right' ];
var absMax = api.max(element, value, inclusions);
Css.set(element, 'max-width', absMax + 'px');
};
export default {
set,
get,
getOuter,
setMax,
}; | import Css from '../properties/Css';
import Dimension from '../../impl/Dimension';
import Element from '../node/Element';
import { HTMLElement } from '@ephox/dom-globals';
var api = Dimension('width', function (element: Element) {
// IMO passing this function is better than using dom['offset' + 'width']
return (element.dom() as HTMLElement).offsetWidth;
});
var set = function (element: Element, h: string | number) {
api.set(element, h);
};
var get = function (element: Element) {
return api.get(element);
};
var getOuter = function (element: Element) {
return api.getOuter(element);
};
var setMax = function (element: Element, value: number) {
// These properties affect the absolute max-height, they are not counted natively, we want to include these properties.
var inclusions = [ 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right' ];
var absMax = api.max(element, value, inclusions);
Css.set(element, 'max-width', absMax + 'px');
};
export default {
set,
get,
getOuter,
setMax,
}; |
Add 'editable' to MapField class | export class MapField {
label: string;
namespace: string;
name: string;
uri: string;
guidelines: string;
source: string;
definition: string;
obligation: string;
range: any;
repeatable: boolean;
input: string;
visible: boolean;
}
| export class MapField {
label: string;
namespace: string;
name: string;
uri: string;
guidelines: string;
source: string;
definition: string;
obligation: string;
range: any;
repeatable: boolean;
input: string;
visible: boolean;
editable: boolean;
}
|
Add more language config settings for indent, etc. | import * as vscode from 'vscode';
import * as client from './client';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(client.launch(context));
}
export function deactivate() {
}
| import * as vscode from 'vscode';
import * as client from './client';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.languages.setLanguageConfiguration('reason', {
indentationRules: {
decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
increaseIndentPattern: /^.*\{[^}"']*$/,
},
onEnterRules: [
{
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
afterText: /^\s*\*\/$/,
action: { indentAction: vscode.IndentAction.IndentOutdent, appendText: ' * ' }
},
{
beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
action: { indentAction: vscode.IndentAction.None, appendText: ' * ' }
},
{
beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
action: { indentAction: vscode.IndentAction.None, appendText: '* ' }
},
{
beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
action: { indentAction: vscode.IndentAction.None, removeText: 1 }
},
{
beforeText: /^(\t|(\ \ ))*\ \*[^/]*\*\/\s*$/,
action: { indentAction: vscode.IndentAction.None, removeText: 1 }
}
],
wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
}));
context.subscriptions.push(client.launch(context));
}
export function deactivate() {
}
|
Fix default import of remove-markdown. | import * as React from "react"
import * as Relay from "react-relay/classic"
import * as removeMarkdown from "remove-markdown"
import { Dimensions, StyleSheet, View, ViewProperties } from "react-native"
import SerifText from "../Text/Serif"
const sideMargin = Dimensions.get("window").width > 700 ? 50 : 0
interface Props extends ViewProperties, RelayProps {}
class Biography extends React.Component<Props, any> {
render() {
const gene = this.props.gene
if (!gene.description) {
return null
}
return (
<View style={{ marginLeft: sideMargin, marginRight: sideMargin }}>
{this.blurb(gene)}
</View>
)
}
blurb(gene) {
if (gene.description) {
return (
<SerifText style={styles.blurb} numberOfLines={0}>
{removeMarkdown(gene.description)}
</SerifText>
)
}
}
}
const styles = StyleSheet.create({
blurb: {
fontSize: 16,
lineHeight: 20,
marginBottom: 20,
},
bio: {
fontSize: 16,
lineHeight: 20,
marginBottom: 40,
},
})
export default Relay.createContainer(Biography, {
fragments: {
gene: () => Relay.QL`
fragment on Gene {
description
}
`,
},
})
interface RelayProps {
gene: {
description: string | null
}
}
| import * as React from "react"
import * as Relay from "react-relay/classic"
import removeMarkdown from "remove-markdown"
import { Dimensions, StyleSheet, View, ViewProperties } from "react-native"
import SerifText from "../Text/Serif"
const sideMargin = Dimensions.get("window").width > 700 ? 50 : 0
interface Props extends ViewProperties, RelayProps {}
class Biography extends React.Component<Props, any> {
render() {
const gene = this.props.gene
if (!gene.description) {
return null
}
return (
<View style={{ marginLeft: sideMargin, marginRight: sideMargin }}>
{this.blurb(gene)}
</View>
)
}
blurb(gene) {
if (gene.description) {
return (
<SerifText style={styles.blurb} numberOfLines={0}>
{removeMarkdown(gene.description)}
</SerifText>
)
}
}
}
const styles = StyleSheet.create({
blurb: {
fontSize: 16,
lineHeight: 20,
marginBottom: 20,
},
bio: {
fontSize: 16,
lineHeight: 20,
marginBottom: 40,
},
})
export default Relay.createContainer(Biography, {
fragments: {
gene: () => Relay.QL`
fragment on Gene {
description
}
`,
},
})
interface RelayProps {
gene: {
description: string | null
}
}
|
Fix for the resource not loading on the Integration Server | module app.core.metaschema {
import IHttpPromise = angular.IHttpPromise;
import IPromise = angular.IPromise;
import IQService = angular.IQService;
import IDeferred = angular.IDeferred;
import DataschemaService = app.core.dataschema.DataschemaService;
export class MetaschemaService {
static $inject = ['$http', '$q'];
private metaschema:IPromise<Metaschema>;
constructor($http:ng.IHttpService, $q:IQService) {
var deffered:IDeferred<Metaschema> = $q.defer();
$http.get('/resource/metaschema.json').success((json:any):void => {
deffered.resolve(Metaschema.fromJSON(json));
});
this.metaschema = deffered.promise;
}
/**
* Gets a promise of the Metaschema.
*
* @returns {IPromise<Metaschema>}
*/
getMetaschema():IPromise<Metaschema> {
return this.metaschema;
}
}
angular.module('app.core').service('MetaschemaService', MetaschemaService);
}
| module app.core.metaschema {
import IHttpPromise = angular.IHttpPromise;
import IPromise = angular.IPromise;
import IQService = angular.IQService;
import IDeferred = angular.IDeferred;
import DataschemaService = app.core.dataschema.DataschemaService;
export class MetaschemaService {
static $inject = ['$http', '$q'];
private metaschema:IPromise<Metaschema>;
constructor($http:ng.IHttpService, $q:IQService) {
var deffered:IDeferred<Metaschema> = $q.defer();
$http.get('resource/metaschema.json').success((json:any):void => {
deffered.resolve(Metaschema.fromJSON(json));
});
this.metaschema = deffered.promise;
}
/**
* Gets a promise of the Metaschema.
*
* @returns {IPromise<Metaschema>}
*/
getMetaschema():IPromise<Metaschema> {
return this.metaschema;
}
}
angular.module('app.core').service('MetaschemaService', MetaschemaService);
}
|
Remove func property from SearchOption | /*
* searchoption.js
*
* encapsulates a search option
*/
"use strict";
interface SettingsFunc {
(): void;
}
export class SearchOption {
shortarg: string;
longarg: string;
desc: string;
func: SettingsFunc;
public sortarg: string;
constructor(shortarg: string, longarg: string, desc: string, func: SettingsFunc) {
this.shortarg = shortarg;
this.longarg = longarg;
this.desc = desc;
this.func = func;
this.sortarg = this.getSortarg();
}
private getSortarg(): string {
if (this.shortarg)
return this.shortarg.toLowerCase() + 'a' + this.longarg.toLowerCase();
return this.longarg.toLowerCase();
}
}
| /*
* searchoption.js
*
* encapsulates a search option
*/
"use strict";
export class SearchOption {
shortarg: string;
longarg: string;
desc: string;
public sortarg: string;
constructor(shortarg: string, longarg: string, desc: string) {
this.shortarg = shortarg;
this.longarg = longarg;
this.desc = desc;
this.sortarg = this.getSortarg();
}
private getSortarg(): string {
if (this.shortarg)
return this.shortarg.toLowerCase() + 'a' + this.longarg.toLowerCase();
return this.longarg.toLowerCase();
}
}
|
Use shorthand expression for variable assignment in createCommandRegex | import escapeStringRegexp = require('escape-string-regexp');
import { Command } from '../chat-service/command';
export function createCommandRegex(commands: string[], rootCommand = false): RegExp {
let beginning = '';
let end = '';
if (rootCommand) {
beginning = '^';
end = '$';
}
return new RegExp(`${beginning}(${commands.map((element) => {
return escapeStringRegexp(Command.commandPrefix) + element + '\\b';
}).join('|')})${end}`, 'i');
}
| import escapeStringRegexp = require('escape-string-regexp');
import { Command } from '../chat-service/command';
export function createCommandRegex(commands: string[], rootCommand = false): RegExp {
const beginning = rootCommand ? '^' : '';
const end = rootCommand ? '$' : '';
return new RegExp(`${beginning}(${commands.map((element) => {
return escapeStringRegexp(Command.commandPrefix) + element + '\\b';
}).join('|')})${end}`, 'i');
}
|
Add missing properties in getGlobalContext.organizationSettings | export class OrganizationSettingsMock implements Xrm.OrganizationSettings {
public baseCurrencyId: string;
public defaultCountryCode: string;
public isAutoSaveEnabled: boolean;
public languageId: number;
public organizationId: string;
public uniqueName: string;
public useSkypeProtocol: boolean;
constructor(components: IOrganizationSettingsComponents) {
this.baseCurrencyId = components.baseCurrencyId;
this.defaultCountryCode = components.defaultCountryCode;
this.isAutoSaveEnabled = components.isAutoSaveEnabled;
this.languageId = components.languageId;
this.organizationId = components.organizationId;
this.uniqueName = components.uniqueName;
this.useSkypeProtocol = components.useSkypeProtocol;
}
}
export interface IOrganizationSettingsComponents {
baseCurrencyId?: string;
defaultCountryCode?: string;
isAutoSaveEnabled?: boolean;
languageId?: number;
organizationId?: string;
uniqueName?: string;
useSkypeProtocol?: boolean;
}
| export class OrganizationSettingsMock implements Xrm.OrganizationSettings {
public baseCurrencyId: string;
public defaultCountryCode: string;
public isAutoSaveEnabled: boolean;
public languageId: number;
public organizationId: string;
public uniqueName: string;
public useSkypeProtocol: boolean;
public baseCurrency: Xrm.LookupValue;
public attributes: any;
constructor(components: IOrganizationSettingsComponents) {
this.baseCurrencyId = components.baseCurrencyId;
this.defaultCountryCode = components.defaultCountryCode;
this.isAutoSaveEnabled = components.isAutoSaveEnabled;
this.languageId = components.languageId;
this.organizationId = components.organizationId;
this.uniqueName = components.uniqueName;
this.useSkypeProtocol = components.useSkypeProtocol;
this.baseCurrency = components.baseCurrency;
this.attributes = components.attributes;
}
}
export interface IOrganizationSettingsComponents {
baseCurrencyId?: string;
defaultCountryCode?: string;
isAutoSaveEnabled?: boolean;
languageId?: number;
organizationId?: string;
uniqueName?: string;
useSkypeProtocol?: boolean;
baseCurrency?: Xrm.LookupValue;
attributes?: any;
}
|
Add helpful error message for VaaS MFA users | import {Command} from '@heroku-cli/command'
import * as Heroku from '@heroku-cli/schema'
import ux from 'cli-ux'
export default class Auth2faGenerate extends Command {
static description = 'disables 2fa on account'
static aliases = [
'twofactor:disable',
'2fa:disable',
]
static example = `$ heroku auth:2fa:disable
Disabling 2fa on me@example.com... done`
async run() {
ux.action.start('Disabling 2fa')
const {body: account} = await this.heroku.get<Heroku.Account>('/account')
ux.action.start(`Disabling 2fa on ${account.email}`)
if (!account.two_factor_authentication) this.error('2fa is already disabled')
const password = await ux.prompt('Password', {type: 'hide'})
await this.heroku.patch('/account', {body: {password, two_factor_authentication: false}})
}
}
| import {Command} from '@heroku-cli/command'
import * as Heroku from '@heroku-cli/schema'
import ux from 'cli-ux'
export default class Auth2faGenerate extends Command {
static description = 'disables 2fa on account'
static aliases = [
'twofactor:disable',
'2fa:disable',
]
static example = `$ heroku auth:2fa:disable
Disabling 2fa on me@example.com... done`
async run() {
ux.action.start('Disabling 2fa')
const {body: account} = await this.heroku.get<Heroku.Account>('/account'), {
headers: {
Accept: 'application/vnd.heroku+json; version=3.with_vaas_info',
}
}
ux.action.start(`Disabling 2fa on ${account.email}`)
if (account.vaas_enrolled) this.error('Cannot disable 2fa via CLI\nPlease visit your Account page on the Heroku Dashboad to manage 2fa')
if (!account.two_factor_authentication) this.error('2fa is already disabled')
const password = await ux.prompt('Password', {type: 'hide'})
await this.heroku.patch('/account', {body: {password, two_factor_authentication: false}})
}
}
|
Add unit tests for min decorator | import { Min } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (greater or equals than min value)', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 5;
expect(testClass.myNumber).toEqual(5);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 3;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (less than min value)', () => {
class TestClassMinValue {
@Min(5, true)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 10;
testClass.myNumber = 3;
expect(testClass.myNumber).toEqual(10);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMinValue {
@Min(5, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMinValue();
expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
});
}); | import { Min } from './../../src/';
describe('LoggerMethod decorator', () => {
it('should assign a valid value (greater or equals than min value)', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
let valueToAssign = 5;
testClass.myNumber = valueToAssign;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should assign null to the property (default value, protect = false) without throw an exception', () => {
class TestClassMinValue {
@Min(5)
myNumber: number;
}
let testClass = new TestClassMinValue();
testClass.myNumber = 3;
expect(testClass.myNumber).toBeNull();
});
it('should protect the previous value when assign an invalid value (less than min value)', () => {
class TestClassMinValue {
@Min(5, true)
myNumber: number;
}
let testClass = new TestClassMinValue();
let validValueToAssign = 10;
testClass.myNumber = validValueToAssign;
testClass.myNumber = 3;
expect(testClass.myNumber).toEqual(validValueToAssign);
});
it('should throw an error when the value assigned is invalid', () => {
let exceptionMsg = 'Invalid min value assigned!';
class TestClassMinValue {
@Min(5, false, exceptionMsg)
myNumber: number;
}
let testClass = new TestClassMinValue();
expect(() => testClass.myNumber = 3).toThrowError(exceptionMsg);
});
}); |
Apply initial state (concact) if provided so that even if no actions sent yet, the initial state is provided to subscribers. | import { Flow } from './Flow';
import { Soak, completeSoak } from './Soak';
import { Observable, Subject } from 'rxjs';
/**
* The dispatch and state that comprises a dw Store.
*/
export type Store<State, Action> = {
dispatch$: Subject<Action>;
state$: Observable<State>;
};
/**
* Links a flow, soak and initial state to create a store object.
* Objects passed to the dispatch function will be filtered through the flow
* then scanned to apply state changes defined by the soak, starting with the initial state.
*
* @param flow the transformations to the action stream
* @param soak the transformations to state based on actions
* @param initialState the initial state prior to any applied soaks.
*/
export const createStore = <State, Action>(
flow: Flow<Action>,
soak: Soak<State, Action>,
initialState?: State
): Store<State, Action> => {
const subject$ = new Subject<Action>();
const fullSoak = completeSoak(soak);
return {
dispatch$: subject$,
state$: flow(subject$).scan<Action, State>(fullSoak, initialState).share()
};
};
export default createStore; | import { Flow } from './Flow';
import { Soak, completeSoak } from './Soak';
import { Observable, Subject } from 'rxjs';
/**
* The dispatch and state that comprises a dw Store.
*/
export type Store<State, Action> = {
/** dispatch actions into the store */
dispatch$: Subject<Action>;
/** observable of actions after flows applied */
flow$: Observable<Action>
/** observable of state after flows and soaks applied */
state$: Observable<State>;
};
/**
* Links a flow, soak and initial state to create a store object.
* Objects passed to the dispatch function will be filtered through the flow
* then scanned to apply state changes defined by the soak, starting with the initial state.
*
* @param flow the transformations to the action stream
* @param soak the transformations to state based on actions
* @param initialState the initial state prior to any applied soaks.
*/
export const createStore = <State, Action>(
flow: Flow<Action>,
soak: Soak<State, Action>,
initialState?: State
): Store<State, Action> => {
// insert
const subject$ = new Subject<Action>();
// flow
const flow$ = flow(subject$).share();
// soak
const fullSoak = completeSoak(soak);
const scan$ = flow$.scan<Action, State>(fullSoak, initialState);
// state
const state$ = (initialState
? Observable.concat(Observable.of(initialState), scan$)
: scan$).share();
const store = {
dispatch$: subject$,
flow$: flow$,
state$: state$
};
// empty action through to trigger any initial states.
return store;
};
export default createStore; |
Tweak resolving location of tree-sitter-ruby.wasm | import path from 'path';
import Parser from 'web-tree-sitter';
const TREE_SITTER_RUBY_WASM = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
const TreeSitterFactory = {
language: null,
async initalize(): Promise<void> {
await Parser.init();
console.debug(`Loading Ruby tree-sitter syntax from ${TREE_SITTER_RUBY_WASM}`);
this.language = await Parser.Language.load(TREE_SITTER_RUBY_WASM);
},
build(): Parser {
const parser = new Parser();
parser.setLanguage(this.language);
return parser;
},
};
export default TreeSitterFactory;
| import path from 'path';
import fs from 'fs';
import Parser from 'web-tree-sitter';
const TREE_SITTER_RUBY_WASM = ((): string => {
let wasmPath = path.resolve(__dirname, 'tree-sitter-ruby.wasm');
if (!fs.existsSync(wasmPath)) {
wasmPath = path.resolve(__dirname, '..', 'tree-sitter-ruby.wasm');
}
return wasmPath;
})();
const TreeSitterFactory = {
language: null,
async initalize(): Promise<void> {
await Parser.init();
console.debug(`Loading Ruby tree-sitter syntax from ${TREE_SITTER_RUBY_WASM}`);
this.language = await Parser.Language.load(TREE_SITTER_RUBY_WASM);
},
build(): Parser {
const parser = new Parser();
parser.setLanguage(this.language);
return parser;
},
};
export default TreeSitterFactory;
|
Remove ConnectToServerOptions interface in favor of shorter ConnectOptions | /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: String
password: String
loginDetails?: Object
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectToServerOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
/**
* Shorter name, less typing :-)
*/
export interface ConnectOptions extends ConnectToServerOptions {
}
export interface ConnectionMap {
[name:string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectToServerOptions(options?:any):ConnectToServerOptions {
var defaults = <ConnectToServerOptions> {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
var opts = options || {};
return angular.extend(defaults, opts);
}
export function createConnectOptions(options?:any) {
return <ConnectOptions> createConnectToServerOptions(options);
}
}
| /// <reference path="includes.ts"/>
/// <reference path="stringHelpers.ts"/>
namespace Core {
/**
* Typescript interface that represents the UserDetails service
*/
export interface UserDetails {
username: String
password: String
loginDetails?: Object
}
/**
* Typescript interface that represents the options needed to connect to another JVM
*/
export interface ConnectOptions {
scheme: String;
host?: String;
port?: Number;
path?: String;
useProxy: boolean;
jolokiaUrl?: String;
userName: String;
password: String;
view: String;
name: String;
secure: boolean;
}
export interface ConnectionMap {
[name: string]: ConnectOptions;
}
/**
* Factory to create an instance of ConnectToServerOptions
* @returns {ConnectToServerOptions}
*/
export function createConnectOptions(options?: any): ConnectOptions {
let defaults: ConnectOptions = {
scheme: 'http',
host: null,
port: null,
path: null,
useProxy: true,
jolokiaUrl: null,
userName: null,
password: null,
view: null,
name: null,
secure: false
};
let opts = options || {};
return angular.extend(defaults, opts);
}
}
|
Add error message service test | import { TestBed, inject } from '@angular/core/testing';
import { ErrorMessageService } from './error-message.service';
describe('ErrorMessageService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ErrorMessageService]
});
});
it('should ...', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service).toBeTruthy();
}));
});
| import {inject, TestBed} from "@angular/core/testing";
import {ErrorMessageService} from "./error-message.service";
import {CUSTOM_ERROR_MESSAGES} from "../Tokens/tokens";
import {errorMessageService} from "../ng-bootstrap-form-validation.module";
describe('ErrorMessageService', () => {
const customRequiredErrorMessage = {
error: 'required',
format: function (label, error) {
return `${label} IS DEFINITELY REQUIRED!!!`;
}
};
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: ErrorMessageService,
useFactory: errorMessageService,
deps: [CUSTOM_ERROR_MESSAGES]
},
{
provide: CUSTOM_ERROR_MESSAGES,
useValue: [
customRequiredErrorMessage
]
}
]
});
});
it('should inject ErrorMessageService', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service).toBeTruthy();
}));
describe('errorMessages()', () => {
it('should return custom errors before default errors', inject([ErrorMessageService], (service: ErrorMessageService) => {
expect(service.errorMessages[0]).toEqual(customRequiredErrorMessage);
}));
});
});
|
Update how the query string is generated | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../../environments/environment';
import { Hero, HeroUniverse, HeroRole } from '../models';
@Injectable()
export class HeroService {
private url = `${environment.backend.url}/heroes`;
constructor(private http: Http) {
}
searchHeroes(universe: HeroUniverse, role: HeroRole, terms: string): Observable<Hero[]> {
return this.http
.get(`${this.url}?universe=${universe}&role=${role}&terms=${encodeURI(terms || '')}`)
.map(response => response.json() as Hero[]);
}
getHero(name: string): Promise<Hero> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Hero[])
.then(heroes => heroes.filter(hero => hero.name === name).pop())
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
// TODO: add real error handling
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../../environments/environment';
import { Hero, HeroUniverse, HeroRole } from '../models';
@Injectable()
export class HeroService {
private url = `${environment.backend.url}/heroes`;
constructor(private http: Http) {
}
searchHeroes(universe: HeroUniverse, role: HeroRole, terms: string): Observable<Hero[]> {
const query = this.querystring({ universe, role, terms });
return this.http
.get(`${this.url}?${query}`)
.map(response => response.json() as Hero[]);
}
getHero(name: string): Promise<Hero> {
return this.http.get(this.url)
.toPromise()
.then(response => response.json() as Hero[])
.then(heroes => heroes.filter(hero => hero.name === name).pop())
.catch(this.handleError);
}
private querystring(query) {
return Object
.keys(query)
.filter(key => query[key] || query[key] === 0 || query[key] === false)
.map(key => encodeURI(key) + '=' + encodeURI(query[key]))
.join('&');
}
private handleError(error: any): Promise<any> {
// TODO: add real error handling
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
|
Refresh cake counter when a cake is added | import * as React from "react";
import { CakeProps } from "./Cake.tsx";
import { CakeListProps } from "./CakeList.tsx";
interface CakeCounterState {
daysSinceLastCake: number;
}
class CakeCounter extends React.Component<CakeListProps, CakeCounterState> {
constructor(props: CakeListProps) {
super(props);
this.state = {
daysSinceLastCake: this.calculateDaysSinceLastCake(this.props.cakes)
};
}
calculateDateDiffInDays(a: Date, b: Date): number {
const MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.abs(Math.floor((utc2 - utc1) / MILLISECONDS_IN_DAY));
}
calculateDaysSinceLastCake(cakes: any) {
const lastCake = this.props.cakes[0];
return this.calculateDateDiffInDays(new Date(), lastCake.date);
}
render() {
console.log("cakecounter render", new Date());
return (<div>
Days since last cake: {this.state.daysSinceLastCake}
</div>);
}
}
export {
CakeCounter
}; | import * as React from "react";
import { CakeProps } from "./Cake.tsx";
import { CakeListProps } from "./CakeList.tsx";
interface CakeCounterState {
daysSinceLastCake: number;
}
class CakeCounter extends React.Component<CakeListProps, CakeCounterState> {
constructor(props: CakeListProps) {
super(props);
this.calculateNewState = this.calculateNewState.bind(this);
this.state = this.calculateNewState(this.props);
}
calculateNewState(props: CakeListProps): CakeCounterState {
return {
daysSinceLastCake: this.calculateDaysSinceLastCake(props.cakes)
};
}
calculateDateDiffInDays(a: Date, b: Date): number {
const MILLISECONDS_IN_DAY = 1000 * 60 * 60 * 24;
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.abs(Math.floor((utc2 - utc1) / MILLISECONDS_IN_DAY));
}
componentWillReceiveProps(nextProps: CakeListProps) {
this.state = this.calculateNewState(nextProps);
}
calculateDaysSinceLastCake(cakes: any) {
const lastCake = this.props.cakes[0];
return this.calculateDateDiffInDays(new Date(), lastCake.date);
}
render() {
return (<div>
Days since last cake: {this.state.daysSinceLastCake}
</div>);
}
}
export {
CakeCounter
}; |
Add gast.TOP_LEVEL to the API | /**
* defines the public API of Chevrotain.
* changes here may require major version change. (semVer)
*/
declare var CHEV_TEST_MODE
declare var global
var testMode = (typeof global === "object" && global.CHEV_TEST_MODE) ||
(typeof window === "object" && (<any>window).CHEV_TEST_MODE)
var API:any = {}
/* istanbul ignore next */
if (!testMode) {
// runtime API
API.Parser = chevrotain.recognizer.Parser
API.Lexer = chevrotain.lexer.Lexer
API.Token = chevrotain.tokens.Token
// utilities
API.extendToken = chevrotain.tokens.extendToken
// grammar reflection API
API.gast = {}
API.gast.GAstVisitor = chevrotain.gast.GAstVisitor
API.gast.FLAT = chevrotain.gast.FLAT
API.gast.AT_LEAST_ONE = chevrotain.gast.AT_LEAST_ONE
API.gast.MANY = chevrotain.gast.MANY
API.gast.OPTION = chevrotain.gast.OPTION
API.gast.OR = chevrotain.gast.OR
API.gast.ProdRef = chevrotain.gast.ProdRef
API.gast.Terminal = chevrotain.gast.Terminal
}
else {
console.log("running in TEST_MODE")
API = chevrotain
}
| /**
* defines the public API of Chevrotain.
* changes here may require major version change. (semVer)
*/
declare var CHEV_TEST_MODE
declare var global
var testMode = (typeof global === "object" && global.CHEV_TEST_MODE) ||
(typeof window === "object" && (<any>window).CHEV_TEST_MODE)
var API:any = {}
/* istanbul ignore next */
if (!testMode) {
// runtime API
API.Parser = chevrotain.recognizer.Parser
API.Lexer = chevrotain.lexer.Lexer
API.Token = chevrotain.tokens.Token
// utilities
API.extendToken = chevrotain.tokens.extendToken
// grammar reflection API
API.gast = {}
API.gast.GAstVisitor = chevrotain.gast.GAstVisitor
API.gast.FLAT = chevrotain.gast.FLAT
API.gast.AT_LEAST_ONE = chevrotain.gast.AT_LEAST_ONE
API.gast.MANY = chevrotain.gast.MANY
API.gast.OPTION = chevrotain.gast.OPTION
API.gast.OR = chevrotain.gast.OR
API.gast.ProdRef = chevrotain.gast.ProdRef
API.gast.Terminal = chevrotain.gast.Terminal
API.gast.TOP_LEVEL = chevrotain.gast.TOP_LEVEL
}
else {
console.log("running in TEST_MODE")
API = chevrotain
}
|
Add basic deletion in history | import * as React from 'react';
import { observer } from 'mobx-react';
import store from '../../store';
import { HistoryItem } from '../../models';
import { formatTime } from '../../utils';
import { Favicon, Item, Remove, Title, Time, Site } from './style';
const onClick = (data: HistoryItem) => (e: React.MouseEvent) => {
if (e.ctrlKey) {
data.selected = !data.selected;
}
};
export default observer(({ data }: { data: HistoryItem }) => {
return (
<Item key={data._id} onClick={onClick(data)} selected={data.selected}>
<Favicon
style={{
backgroundImage: `url(${store.faviconsStore.favicons[data.favicon]})`,
}}
/>
<Title>{data.title}</Title>
<Site>{data.url.split('/')[2]}</Site>
<Time>{formatTime(new Date(data.date))}</Time>
<Remove />
</Item>
);
});
| import * as React from 'react';
import { observer } from 'mobx-react';
import store from '../../store';
import { HistoryItem } from '../../models';
import { formatTime } from '../../utils';
import { Favicon, Item, Remove, Title, Time, Site } from './style';
const onClick = (item: HistoryItem) => (e: React.MouseEvent) => {
if (e.ctrlKey) {
item.selected = !item.selected;
}
};
const onRemoveClick = (item: HistoryItem) => () => {
store.historyStore.removeItem(item._id);
};
export default observer(({ data }: { data: HistoryItem }) => {
return (
<Item key={data._id} onClick={onClick(data)} selected={data.selected}>
<Favicon
style={{
backgroundImage: `url(${store.faviconsStore.favicons[data.favicon]})`,
}}
/>
<Title>{data.title}</Title>
<Site>{data.url.split('/')[2]}</Site>
<Time>{formatTime(new Date(data.date))}</Time>
<Remove onClick={onRemoveClick(data)} />
</Item>
);
});
|
Add tests for GraphQL mutations | import { gql } from "apollo-server";
import { createTestClient } from "apollo-server-testing";
import { server } from "../src";
describe("Queries", () => {
it("returns a list of kernelspecs", async () => {
const { query } = createTestClient(server);
const kernelspecsQuery = gql`
query GetKernels {
listKernelSpecs {
name
}
}
`;
const response = await query({ query: kernelspecsQuery });
expect(response).not.toBeNull();
expect(response.data.listKernelSpecs.length).toBeGreaterThan(0);
});
});
| import { gql } from "apollo-server";
import { createTestClient } from "apollo-server-testing";
import { server } from "../src";
describe("Queries", () => {
it("returns a list of kernelspecs", async () => {
const { query } = createTestClient(server);
const LIST_KERNELSPECS = gql`
query GetKernels {
listKernelSpecs {
name
}
}
`;
const response = await query({ query: LIST_KERNELSPECS });
expect(response).not.toBeNull();
expect(response.data.listKernelSpecs.length).toBeGreaterThan(0);
});
});
describe("Mutations", () => {
let kernelId;
it("launches a kernel", async () => {
const { mutate } = createTestClient(server);
const START_KERNEL = gql`
mutation StartJupyterKernel {
startKernel(name: "python3") {
id
status
}
}
`;
const response = await mutate({ mutation: START_KERNEL });
kernelId = response.data.startKernel.id;
expect(response).not.toBeNull();
expect(response.data.startKernel.status).toBe("launched");
});
it("shuts down a kernel", async () => {
const { mutate } = createTestClient(server);
const SHUTDOWN_KERNEL = gql`
mutation KillJupyterKernel($id: ID) {
shutdownKernel(id: $id) {
id
status
}
}
`;
const response = await mutate({
mutation: SHUTDOWN_KERNEL,
variables: { id: kernelId }
});
expect(response).not.toBeNull();
expect(response.data.shutdownKernel.status).toBe("shutdown");
});
});
|
Make offering actions button clickable in mobile view. | import * as React from 'react';
import * as Col from 'react-bootstrap/lib/Col';
import * as Row from 'react-bootstrap/lib/Row';
import { OfferingTabsComponent, OfferingTab } from '@waldur/marketplace/details/OfferingTabsComponent';
import { Offering } from '@waldur/marketplace/types';
import { OfferingActions } from '../actions/OfferingActions';
import { OfferingHeader } from './OfferingHeader';
interface OfferingDetailsProps {
offering: Offering;
tabs: OfferingTab[];
}
export const OfferingDetails: React.FC<OfferingDetailsProps> = props => (
<div className="wrapper wrapper-content">
{props.offering.shared && (
<div className="pull-right m-r-md">
<OfferingActions row={props.offering}/>
</div>
)}
<OfferingHeader offering={props.offering}/>
<Row>
<Col lg={12}>
<OfferingTabsComponent tabs={props.tabs}/>
</Col>
</Row>
</div>
);
| import * as React from 'react';
import * as Col from 'react-bootstrap/lib/Col';
import * as Row from 'react-bootstrap/lib/Row';
import { OfferingTabsComponent, OfferingTab } from '@waldur/marketplace/details/OfferingTabsComponent';
import { Offering } from '@waldur/marketplace/types';
import { OfferingActions } from '../actions/OfferingActions';
import { OfferingHeader } from './OfferingHeader';
interface OfferingDetailsProps {
offering: Offering;
tabs: OfferingTab[];
}
export const OfferingDetails: React.FC<OfferingDetailsProps> = props => (
<div className="wrapper wrapper-content">
{props.offering.shared && (
<div className="pull-right m-r-md" style={{position: 'relative', zIndex: 100}}>
<OfferingActions row={props.offering}/>
</div>
)}
<OfferingHeader offering={props.offering}/>
<Row>
<Col lg={12}>
<OfferingTabsComponent tabs={props.tabs}/>
</Col>
</Row>
</div>
);
|
Change the way of rendering App Component | import { render } from 'inferno'
import App from './components/app.ts'
const container = document.getElementById('app')
const app = new App()
render(app.render(), container)
| import { render } from 'inferno'
import h from 'inferno-hyperscript'
import App from './components/app.ts'
const container = document.getElementById('app')
render(h(App), container)
|
Fix direct load of transforms on URL - another missing global reference to be refactored | import * as logging from './core/log'
import * as charts from './charts/core'
import * as factory from './models/items/factory'
import * as app from './app/app'
import * as edit from './edit/edit'
import { actions } from './core/action'
import GraphiteChartRenderer from './charts/graphite'
import FlotChartRenderer from './charts/flot'
import PlaceholderChartRenderer from './charts/placeholder'
import manager from './app/manager'
import Config from './app/config'
declare var window, $, tessera
var log = logging.logger('main')
// Temporary, for compatibility with old templates
window.ts.app = app
window.ts.manager = manager
window.ts.templates = tessera.templates
window.ts.charts = charts
window.ts.factory = factory
window.ts.actions = actions
window.ts.edit = edit
app.config = window.ts.config
function setup(config: Config) {
log.info('Registering chart renderers')
charts.renderers.register(new GraphiteChartRenderer({
graphite_url: config.GRAPHITE_URL
}))
charts.renderers.register(new FlotChartRenderer())
charts.renderers.register(new PlaceholderChartRenderer())
log.info('Done.')
}
setup(app.config)
| import * as logging from './core/log'
import * as charts from './charts/core'
import * as factory from './models/items/factory'
import * as app from './app/app'
import * as edit from './edit/edit'
import { actions } from './core/action'
import { transforms } from './models/transform/transform'
import manager from './app/manager'
import Config from './app/config'
import GraphiteChartRenderer from './charts/graphite'
import FlotChartRenderer from './charts/flot'
import PlaceholderChartRenderer from './charts/placeholder'
declare var window, $, tessera
var log = logging.logger('main')
// Temporary, for compatibility with old templates
window.ts.app = app
window.ts.manager = manager
window.ts.templates = tessera.templates
window.ts.charts = charts
window.ts.factory = factory
window.ts.actions = actions
window.ts.edit = edit
window.ts.transforms = transforms
app.config = window.ts.config
function setup(config: Config) {
log.info('Registering chart renderers')
charts.renderers.register(new GraphiteChartRenderer({
graphite_url: config.GRAPHITE_URL
}))
charts.renderers.register(new FlotChartRenderer())
charts.renderers.register(new PlaceholderChartRenderer())
log.info('Done.')
}
setup(app.config)
|
Move division name rendering into getter | import React, {PureComponent} from 'react'
import DivisionMenu, {
MenuItem,
} from 'src/shared/components/threesizer/DivisionMenu'
interface Props {
onMinimize: () => void
onMaximize: () => void
buttons: JSX.Element[]
menuOptions?: MenuItem[]
name?: string
}
class DivisionHeader extends PureComponent<Props> {
public render() {
const {name} = this.props
return (
<div className="threesizer--header">
{name && <div className="threesizer--header-name">{name}</div>}
<div className="threesizer--header-controls">
{this.props.buttons.map(b => b)}
<DivisionMenu menuItems={this.menuItems} />
</div>
</div>
)
}
private get menuItems(): MenuItem[] {
const {onMaximize, onMinimize, menuOptions} = this.props
return [
...menuOptions,
{
action: onMaximize,
text: 'Maximize',
},
{
action: onMinimize,
text: 'Minimize',
},
]
}
}
export default DivisionHeader
| import React, {PureComponent} from 'react'
import DivisionMenu, {
MenuItem,
} from 'src/shared/components/threesizer/DivisionMenu'
interface Props {
onMinimize: () => void
onMaximize: () => void
buttons: JSX.Element[]
menuOptions?: MenuItem[]
name?: string
}
class DivisionHeader extends PureComponent<Props> {
public render() {
return (
<div className="threesizer--header">
{this.renderName}
<div className="threesizer--header-controls">
{this.props.buttons.map(b => b)}
<DivisionMenu menuItems={this.menuItems} />
</div>
</div>
)
}
private get renderName(): JSX.Element {
const {name} = this.props
if (!name) {
return
}
return <div className="threesizer--header-name">{name}</div>
}
private get menuItems(): MenuItem[] {
const {onMaximize, onMinimize, menuOptions} = this.props
return [
...menuOptions,
{
action: onMaximize,
text: 'Maximize',
},
{
action: onMinimize,
text: 'Minimize',
},
]
}
}
export default DivisionHeader
|
Update the HttpVerbs enum so intel sense will work with it. | import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* Enumaration of valid HTTP verbs.
*/
export const HttpVerbs: ObjectMap<HttpVerb> = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
};
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
| import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* Enumaration of valid HTTP verbs.
*/
export const HttpVerbs = Object.freeze({
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
});
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
|
Make schema namespacing optional and added schema identifier | import { GraphQLSchema } from 'graphql';
import { FieldMetadata } from '../extended-schema/extended-schema';
export interface ProxyConfig {
endpoints: EndpointConfig[]
}
interface EndpointConfigBase {
namespace: string
typePrefix: string
fieldMetadata?: {[key: string]: FieldMetadata}
url?: string
schema?: GraphQLSchema
}
interface HttpEndpointConfig extends EndpointConfigBase {
url: string
}
interface LocalEndpointConfig extends EndpointConfigBase {
schema: GraphQLSchema
}
export type EndpointConfig = HttpEndpointConfig | LocalEndpointConfig;
| import { GraphQLSchema } from 'graphql';
import { FieldMetadata } from '../extended-schema/extended-schema';
export interface ProxyConfig {
endpoints: EndpointConfig[]
}
interface EndpointConfigBase {
namespace?: string
typePrefix?: string
fieldMetadata?: {[key: string]: FieldMetadata}
url?: string
schema?: GraphQLSchema
identifier?: string
}
interface HttpEndpointConfig extends EndpointConfigBase {
url: string
}
interface LocalEndpointConfig extends EndpointConfigBase {
schema: GraphQLSchema
}
export type EndpointConfig = HttpEndpointConfig | LocalEndpointConfig;
|
Clear field in Redux-Form when field is unmounted | import * as React from 'react';
import { WrappedFieldMetaProps } from 'redux-form';
import { FieldError } from './FieldError';
import { FormField } from './types';
interface FormGroupProps extends FormField {
meta: WrappedFieldMetaProps;
children: React.ReactChildren;
}
export const FormGroup = (props: FormGroupProps) => {
const { input, required, label, meta: {error}, children, ...rest } = props;
return (
<div className="form-group">
<label className="control-label">
{label}{required && <span className="text-danger"> *</span>}
</label>
{React.cloneElement((children as any), {input, ...rest})}
<FieldError error={error}/>
</div>
);
};
| import * as React from 'react';
// @ts-ignore
import { clearFields, WrappedFieldMetaProps } from 'redux-form';
import { FieldError } from './FieldError';
import { FormField } from './types';
interface FormGroupProps extends FormField {
meta: WrappedFieldMetaProps;
children: React.ReactChildren;
}
export class FormGroup extends React.PureComponent<FormGroupProps> {
render() {
const { input, required, label, meta: {error}, children, ...rest } = this.props;
return (
<div className="form-group">
<label className="control-label">
{label}{required && <span className="text-danger"> *</span>}
</label>
{React.cloneElement((children as any), {input, ...rest})}
<FieldError error={error}/>
</div>
);
}
componentWillUnmount() {
const { meta, input } = this.props;
meta.dispatch(clearFields(meta.form, false, false, input.name));
}
}
|
Fix webpack public path error. | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// Entry point for the notebook bundle containing custom model definitions.
//
// Setup notebook base URL
//
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
export * from './index';
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// Entry point for the notebook bundle containing custom model definitions.
//
// Setup notebook base URL
//
// Some static assets may be required by the custom widget javascript. The base
// url for the notebook is not known at build time and is therefore computed
// dynamically.
(window as any).__webpack_public_path__ = document.querySelector('body')!.getAttribute('data-base-url') + 'nbextensions/{{ cookiecutter.npm_package_name }}';
export * from './index';
|
Update release version to 0.13.1 | import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.0',
RELEASEVERSION: '0.13.0'
};
export = BaseConfig;
| import { EnvConfig } from './env-config.interface';
const BaseConfig: EnvConfig = {
// Sample API url
API: 'https://demo.com',
RELEASEURL: 'https://github.com/nie-ine/raeber-website/releases/tag/0.13.1',
RELEASEVERSION: '0.13.1'
};
export = BaseConfig;
|
Add blocking to log options | import RoutingServer from './routingserver';
export interface ConfigServer {
listenPort: number;
routingServers: RoutingServer[];
}
export interface LogOptions {
clientTimeouts: boolean;
clientConnect: boolean;
clientDisconnect: boolean;
clientError: boolean;
tServerConnect: boolean;
tServerDisconnect: boolean;
tServerError: boolean;
}
export interface ConfigOptions {
clientTimeout: number;
fakeVersion: boolean;
fakeVersionNum: number;
blockInvis: boolean;
useBlacklist: boolean;
blacklistAPIKey: string;
log: LogOptions;
}
export interface Config {
servers: ConfigServer[];
options: ConfigOptions;
}
export const ConfigSettings: Config = require(`../config.js`).ConfigSettings; | import RoutingServer from './routingserver';
export interface ConfigServer {
listenPort: number;
routingServers: RoutingServer[];
}
export interface LogOptions {
clientTimeouts: boolean;
clientConnect: boolean;
clientDisconnect: boolean;
clientError: boolean;
tServerConnect: boolean;
tServerDisconnect: boolean;
tServerError: boolean;
clientBlocked: boolean;
}
export interface ConfigOptions {
clientTimeout: number;
fakeVersion: boolean;
fakeVersionNum: number;
blockInvis: boolean;
useBlacklist: boolean;
blacklistAPIKey: string;
log: LogOptions;
}
export interface Config {
servers: ConfigServer[];
options: ConfigOptions;
}
export const ConfigSettings: Config = require(`../config.js`).ConfigSettings; |
Remove computed attributes from SKU model | import DS from "ember-data";
import { computed, get } from "@ember/object";
import Price from "./price";
import Product from "./product";
import Bom from "./bom";
import SkuImage from "./sku-image";
import SkuField from "./sku-field";
export default class Sku extends DS.Model {
@DS.attr("number") stockQuantity!: number;
@DS.belongsTo("price") price!: Price;
@DS.belongsTo("product") product!: Product;
@DS.belongsTo("bom", { async: false }) bom!: Bom;
@DS.hasMany("sku-image") skuImages!: SkuImage[];
@DS.hasMany("sku-field") skuFields!: SkuField[];
@computed("skuFields.[]")
get attributes(): any {
return this.skuFields.reduce((hash: any, attribute: any) => {
hash[get(attribute, "slug")] = get(attribute, "values");
return hash;
}, {});
}
}
declare module "ember-data/types/registries/model" {
export default interface ModelRegistry {
sku: Sku;
}
}
| import DS from "ember-data";
import Price from "./price";
import Product from "./product";
import Bom from "./bom";
export default class Sku extends DS.Model {
@DS.attr("number") stockQuantity!: number;
@DS.attr() attrs!: any;
@DS.belongsTo("price") price!: Price;
@DS.belongsTo("product") product!: Product;
@DS.belongsTo("bom", { async: false }) bom!: Bom;
}
declare module "ember-data/types/registries/model" {
export default interface ModelRegistry {
sku: Sku;
}
}
|
Update usage in Welcome wizard | /** The `localStorage` key for whether we've shown the Welcome flow yet. */
const HasShownWelcomeFlowKey = 'has-shown-welcome-flow'
/**
* Check if the current user has completed the welcome flow.
*/
export function hasShownWelcomeFlow(): boolean {
const hasShownWelcomeFlow = localStorage.getItem(HasShownWelcomeFlowKey)
if (!hasShownWelcomeFlow) {
return false
}
const value = parseInt(hasShownWelcomeFlow, 10)
return value === 1
}
/**
* Update local storage to indicate the welcome flow has been completed.
*/
export function markWelcomeFlowComplete() {
localStorage.setItem(HasShownWelcomeFlowKey, '1')
}
| import { getBoolean, setBoolean } from './local-storage'
/** The `localStorage` key for whether we've shown the Welcome flow yet. */
const HasShownWelcomeFlowKey = 'has-shown-welcome-flow'
/**
* Check if the current user has completed the welcome flow.
*/
export function hasShownWelcomeFlow(): boolean {
return getBoolean(HasShownWelcomeFlowKey, false)
}
/**
* Update local storage to indicate the welcome flow has been completed.
*/
export function markWelcomeFlowComplete() {
setBoolean(HasShownWelcomeFlowKey, true)
}
|
Correct development URL to use port 3000 for api | let API_URL: string;
API_URL = "http://localhost:3000/api";
export default API_URL;
| let API_URL: string;
API_URL = `${window.location.protocol}//${window.location.hostname}:3000/api`;
export default API_URL;
|
Save as flag and rename methods. | import * as React from 'react';
import Track from '../model/Track';
import { clear } from '../service';
import './Footer.css';
interface Props extends React.HTMLProps<HTMLDivElement> {
tracks: Track[];
}
function Footer({ tracks }: Props) {
return (
<div className="Footer">
<button
disabled={!tracks.length}
onClick={() => allowExportToM3U(tracks)}
>Export</button>
<button
disabled={!tracks.length}
onClick={() => clear()}
>Clear</button>
</div>
);
}
function allowExportToM3U(tracks: Track[]) {
chrome.permissions.request({
permissions: ['downloads']
}, function (granted) {
if (granted) exportToM3U(tracks);
});
}
function exportToM3U(tracks: Track[]) {
const html = document.implementation.createHTMLDocument('Extereo Playlist');
const ul = html.createElement('ol');
tracks.forEach(track => {
const li = html.createElement('li');
const a = html.createElement('a');
a.href = track.href;
a.innerText = track.title;
li.appendChild(a);
ul.appendChild(li);
});
html.body.appendChild(ul);
const blob = new Blob([html.documentElement.outerHTML], {
type: 'text/html'
});
chrome.downloads.download({
url: URL.createObjectURL(blob),
filename: 'playlist.html'
});
}
export default Footer; | import * as React from 'react';
import Track from '../model/Track';
import { clear } from '../service';
import './Footer.css';
interface Props extends React.HTMLProps<HTMLDivElement> {
tracks: Track[];
}
function Footer({ tracks }: Props) {
return (
<div className="Footer">
<button
disabled={!tracks.length}
onClick={() => allowDownload(tracks)}
>Export</button>
<button
disabled={!tracks.length}
onClick={() => clear()}
>Clear</button>
</div>
);
}
function allowDownload(tracks: Track[]) {
chrome.permissions.request({
permissions: ['downloads']
}, function (granted) {
if (granted) exportToHTML(tracks);
});
}
function exportToHTML(tracks: Track[]) {
const html = document.implementation.createHTMLDocument('Extereo Playlist');
const ul = html.createElement('ol');
tracks.forEach(track => {
const li = html.createElement('li');
const a = html.createElement('a');
a.href = track.href;
a.innerText = track.title;
li.appendChild(a);
ul.appendChild(li);
});
html.body.appendChild(ul);
const blob = new Blob([html.documentElement.outerHTML], {
type: 'text/html'
});
chrome.downloads.download({
url: URL.createObjectURL(blob),
filename: 'playlist.html',
saveAs: true
});
}
export default Footer; |
Fix the export for the buffer | import { Stream } from 'most';
export function buffer<T>(count: number): (stream: Stream<T>) => Stream<T[]>;
export default buffer;
| import { Stream } from 'most';
export default function buffer<T>(count: number): (stream: Stream<T>) => Stream<T[]>;
|
Add deprecation notice for ofType instance operator | import { Inject, Injectable } from '@angular/core';
import { Action, ScannedActionsSubject } from '@ngrx/store';
import { Observable, Operator, OperatorFunction } from 'rxjs';
import { filter } from 'rxjs/operators';
@Injectable()
export class Actions<V = Action> extends Observable<V> {
constructor(@Inject(ScannedActionsSubject) source?: Observable<V>) {
super();
if (source) {
this.source = source;
}
}
lift<R>(operator: Operator<V, R>): Observable<R> {
const observable = new Actions<R>();
observable.source = this;
observable.operator = operator;
return observable;
}
ofType<V2 extends V = V>(...allowedTypes: string[]): Actions<V2> {
return ofType<any>(...allowedTypes)(this as Actions<any>) as Actions<V2>;
}
}
export function ofType<T extends Action>(
...allowedTypes: string[]
): OperatorFunction<Action, T> {
return filter(
(action: Action): action is T =>
allowedTypes.some(type => type === action.type)
);
}
| import { Inject, Injectable } from '@angular/core';
import { Action, ScannedActionsSubject } from '@ngrx/store';
import { Observable, Operator, OperatorFunction } from 'rxjs';
import { filter } from 'rxjs/operators';
@Injectable()
export class Actions<V = Action> extends Observable<V> {
constructor(@Inject(ScannedActionsSubject) source?: Observable<V>) {
super();
if (source) {
this.source = source;
}
}
lift<R>(operator: Operator<V, R>): Observable<R> {
const observable = new Actions<R>();
observable.source = this;
observable.operator = operator;
return observable;
}
/**
* @deprecated from 6.1.0. Use the pipeable `ofType` operator instead.
*/
ofType<V2 extends V = V>(...allowedTypes: string[]): Actions<V2> {
return ofType<any>(...allowedTypes)(this as Actions<any>) as Actions<V2>;
}
}
export function ofType<T extends Action>(
...allowedTypes: string[]
): OperatorFunction<Action, T> {
return filter(
(action: Action): action is T =>
allowedTypes.some(type => type === action.type)
);
}
|
Allow to terminate ERRED resources. | import { translate } from '@waldur/i18n';
import { marketplaceIsVisible } from '@waldur/marketplace/utils';
import { validateState } from '@waldur/resource/actions/base';
import { ResourceAction } from '@waldur/resource/actions/types';
export default function createAction(ctx): ResourceAction {
return {
name: 'terminate_resource',
type: 'form',
method: 'POST',
component: 'marketplaceResourceTerminateDialog',
title: translate('Terminate'),
useResolve: true,
isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null,
validators: [validateState('OK')],
};
}
| import { translate } from '@waldur/i18n';
import { marketplaceIsVisible } from '@waldur/marketplace/utils';
import { validateState } from '@waldur/resource/actions/base';
import { ResourceAction } from '@waldur/resource/actions/types';
export default function createAction(ctx): ResourceAction {
return {
name: 'terminate_resource',
type: 'form',
method: 'POST',
component: 'marketplaceResourceTerminateDialog',
title: translate('Terminate'),
useResolve: true,
isVisible: marketplaceIsVisible() && ctx.resource.marketplace_resource_uuid !== null,
validators: [validateState('OK', 'Erred')],
};
}
|
Add Authentication to persistStore blacklist | ///<reference path="./Interfaces/IStoreCreator.ts" />
import {
compose,
createStore,
applyMiddleware,
combineReducers
} from 'redux';
import {
routerReducer,
routerMiddleware
} from 'react-router-redux';
import {
persistStore,
autoRehydrate
} from 'redux-persist';
import thunk from 'redux-thunk';
import Reducers from 'Reducers/Index';
import * as objectAssign from 'object-assign';
class StoreCreator<T> implements IStoreCreator<T>
{
private store: Redux.Store<T>;
/**
* @param {ReactRouter.History} historyInstance
*/
constructor(historyInstance: ReactRouter.History)
{
/*
* Setup the middlewares and reducers
*/
const router = routerMiddleware(historyInstance);
const reducers = combineReducers(objectAssign({}, Reducers, {
routing : routerReducer
}));
/*
* Further middleware and enhancer prep
*/
const middlewares = [thunk, router];
const enhancer = compose(applyMiddleware(...middlewares), autoRehydrate());
/*
* Create our store with the reducers and enhancers.
* Persist this state in localStorage, minus routing!
*/
this.store = createStore(reducers, undefined, enhancer) as Redux.Store<T>;
persistStore(this.store, {
blacklist : ['routing']
});
}
/**
* @returns Redux
*/
public getStore(): Redux.Store<T>
{
return this.store;
};
};
export default StoreCreator; | ///<reference path="./Interfaces/IStoreCreator.ts" />
import {
compose,
createStore,
applyMiddleware,
combineReducers
} from 'redux';
import {
routerReducer,
routerMiddleware
} from 'react-router-redux';
import {
persistStore,
autoRehydrate
} from 'redux-persist';
import thunk from 'redux-thunk';
import Reducers from 'Reducers/Index';
import * as objectAssign from 'object-assign';
class StoreCreator<T> implements IStoreCreator<T>
{
private store: Redux.Store<T>;
/**
* @param {ReactRouter.History} historyInstance
*/
constructor(historyInstance: ReactRouter.History)
{
/*
* Setup the middlewares and reducers
*/
const router = routerMiddleware(historyInstance);
const reducers = combineReducers(objectAssign({}, Reducers, {
routing : routerReducer
}));
/*
* Further middleware and enhancer prep
*/
const middlewares = [thunk, router];
const enhancer = compose(applyMiddleware(...middlewares), autoRehydrate());
/*
* Create our store with the reducers and enhancers.
* Persist this state in localStorage, minus routing!
*/
this.store = createStore(reducers, undefined, enhancer) as Redux.Store<T>;
persistStore(this.store, {
blacklist : [
'routing',
'authentication'
]
});
}
/**
* @returns Redux
*/
public getStore(): Redux.Store<T>
{
return this.store;
};
};
export default StoreCreator; |
Fix setState run before mount | import { Component } from 'react';
import { AppStore } from '../services/';
import { loadAndBundleSpec } from '../utils';
interface SpecProps {
specUrl?: string;
spec?: object;
store?: AppStore;
children?: any;
}
interface SpecState {
error?: Error;
loading: boolean;
store?: AppStore;
}
export class StoreProvider extends Component<SpecProps, SpecState> {
store: AppStore;
constructor(props: SpecProps) {
super(props);
this.state = {
loading: true,
};
this.load();
}
async load() {
let { specUrl, spec } = this.props;
this.setState({
loading: true,
});
try {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl!);
this.setState({
loading: false,
store: new AppStore(resolvedSpec, specUrl),
});
} catch (e) {
this.setState({
error: e,
});
}
}
setError(e?: Error) {
this.setState({
error: e,
});
}
render() {
if (this.state.error) throw this.state.error;
return this.props.children(this.state);
}
}
| import { Component } from 'react';
import { AppStore } from '../services/';
import { loadAndBundleSpec } from '../utils';
interface SpecProps {
specUrl?: string;
spec?: object;
store?: AppStore;
children?: any;
}
interface SpecState {
error?: Error;
loading: boolean;
store?: AppStore;
}
export class StoreProvider extends Component<SpecProps, SpecState> {
store: AppStore;
constructor(props: SpecProps) {
super(props);
this.state = {
loading: true,
};
}
componentDidMount() {
this.load();
}
async load() {
let { specUrl, spec } = this.props;
this.setState({
loading: true,
});
try {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl!);
this.setState({
loading: false,
store: new AppStore(resolvedSpec, specUrl),
});
} catch (e) {
this.setState({
error: e,
});
}
}
setError(e?: Error) {
this.setState({
error: e,
});
}
render() {
if (this.state.error) throw this.state.error;
return this.props.children(this.state);
}
}
|
Add example of incorrect consumption of enumerable. Test here should be passing | import { Enumerable, ResetableIterator } from '../src/Enumerable';
describe('Enumerable', () => {
describe('DefaultIfEmpty', () => {
it('Should return itself if sequence has items', () => {
const source = Enumerable.Of([1, 2, 3, 4, 5]);
const expected = source;
const result = source.DefaultIfEmpty(1);
expect(result).toEqual(expected);
});
it('Should return an a sequence with the default value if the sequence is empty', () => {
const source = Enumerable.Of(<number[]>[]);
const expected = [1];
const result = source.DefaultIfEmpty(1).ToArray();
expect(result).toEqual(expected);
});
});
});
| import { Enumerable, ResetableIterator } from '../src/Enumerable';
describe('Enumerable', () => {
describe('DefaultIfEmpty', () => {
it('Should return itself if sequence has items', () => {
const originalSource = [1, 2, 3, 4, 5];
const source = Enumerable.Of(originalSource);
const expected = originalSource;
const result = source.DefaultIfEmpty(1).ToArray();
expect(result).toEqual(expected);
});
it('Should return an a sequence with the default value if the sequence is empty', () => {
const source = Enumerable.Of(<number[]>[]);
const expected = [1];
const result = source.DefaultIfEmpty(1).ToArray();
expect(result).toEqual(expected);
});
});
});
|
Revert "fix image element in post header" | /* eslint-disable @next/next/no-img-element */
import * as React from 'react';
import { Container } from '~/components/layout';
export interface PostHeaderImageProps {
src: string;
alt?: string;
}
export const PostHeaderImage: React.FC<PostHeaderImageProps> = ({ alt, src }) => {
return (
<section className="px-4 lg:px-6 pt-12">
<Container>
<div className="relative w-full h-full aspect-video overflow-hidden rounded-md shadow-lg">
<img loading="lazy" src={src} alt={alt} className="object-cover" />
</div>
</Container>
</section>
);
};
| import Image from 'next/image';
import * as React from 'react';
import { Container } from '~/components/layout';
export interface PostHeaderImageProps {
src: string;
alt?: string;
}
export const PostHeaderImage: React.FC<PostHeaderImageProps> = ({ alt, src }) => {
return (
<section className="px-4 lg:px-6 pt-12">
<Container>
<div className="relative w-full h-full aspect-video overflow-hidden rounded-md shadow-lg">
<Image loading="lazy" src={src} alt={alt} layout="fill" objectFit="cover" />
</div>
</Container>
</section>
);
};
|
Add known values to the type of ImportDesriptor.type as documentation. | /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
export class ImportDescriptor {
type: string;
url: string;
constructor(type: string, url: string) {
this.type = type;
this.url = url;
}
}
| /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
export class ImportDescriptor {
type: 'html-import' | 'html-script' | 'html-style' | string;
url: string;
constructor(type: string, url: string) {
this.type = type;
this.url = url;
}
}
|
Allow @WatchChanges to trigger original setter and ngOnChanges when setting the same object reference. | import { SimpleChanges, SimpleChange } from '@angular/core';
/**
* @hidden
*/
export function WatchChanges(): PropertyDecorator {
return (target: any, key: string, propDesc?: PropertyDescriptor) => {
const privateKey = '_' + key.toString();
propDesc = propDesc || {
configurable: true,
enumerable: true,
};
propDesc.get = propDesc.get || (function (this: any) { return this[privateKey]; });
const originalSetter = propDesc.set || (function (this: any, val: any) { this[privateKey] = val; });
propDesc.set = function (this: any, val: any) {
const oldValue = this[key];
if (val !== oldValue) {
originalSetter.call(this, val);
if (this.ngOnChanges) {
// in case wacthed prop changes trigger ngOnChanges manually
const changes: SimpleChanges = {
[key]: new SimpleChange(oldValue, val, false)
};
this.ngOnChanges(changes);
}
}
};
return propDesc;
};
}
| import { SimpleChanges, SimpleChange } from '@angular/core';
/**
* @hidden
*/
export function WatchChanges(): PropertyDecorator {
return (target: any, key: string, propDesc?: PropertyDescriptor) => {
const privateKey = '_' + key.toString();
propDesc = propDesc || {
configurable: true,
enumerable: true,
};
propDesc.get = propDesc.get || (function (this: any) { return this[privateKey]; });
const originalSetter = propDesc.set || (function (this: any, val: any) { this[privateKey] = val; });
propDesc.set = function (this: any, val: any) {
const oldValue = this[key];
if (val !== oldValue || (typeof val === 'object' && val === oldValue)) {
originalSetter.call(this, val);
if (this.ngOnChanges) {
// in case wacthed prop changes trigger ngOnChanges manually
const changes: SimpleChanges = {
[key]: new SimpleChange(oldValue, val, false)
};
this.ngOnChanges(changes);
}
}
};
return propDesc;
};
}
|
Add required to sync subQuery | export type Ordering = 'NONE' | 'ASC' | 'DESC';
export interface QueryOrder {
field: string;
ordering: Ordering;
chain?: string[];
}
export interface QueryFilters {
[attribute: string]: any;
}
export interface QueryPagination {
skip?: number;
take?: number;
}
export interface QueryInclude {
[alias: string]: SubQuery | boolean;
}
export interface SubQuery {
include?: QueryInclude;
filters?: QueryFilters;
attributes?: string[];
}
export interface Query {
queryId?: number;
model?: string;
byId?: number;
count?: boolean;
extra?: any;
include?: QueryInclude;
filters?: QueryFilters;
attributes?: string[];
pagination?: QueryPagination;
order?: QueryOrder;
}
| export type Ordering = 'NONE' | 'ASC' | 'DESC';
export interface QueryOrder {
field: string;
ordering: Ordering;
chain?: string[];
}
export interface QueryFilters {
[attribute: string]: any;
}
export interface QueryPagination {
skip?: number;
take?: number;
}
export interface QueryInclude {
[alias: string]: SubQuery | boolean;
}
export interface SubQuery {
include?: QueryInclude;
filters?: QueryFilters;
attributes?: string[];
required?: boolean;
}
export interface Query {
queryId?: number;
model?: string;
byId?: number;
count?: boolean;
extra?: any;
include?: QueryInclude;
filters?: QueryFilters;
attributes?: string[];
pagination?: QueryPagination;
order?: QueryOrder;
}
|
Add delete function and change add name | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Map, MapType } from './map';
@Injectable()
export class MapService {
constructor(private http: Http) {
}
addMap(
title: string = "",
height: number,
width: number,
mapType: MapType,
creatorId: number,
graphics: string = ""
) {
// TODO: compute hash, id, date and return an Observable<Map>
}
map(id: number) {
}
maps() {
}
} | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Map, MapType } from './map';
@Injectable()
export class MapService {
constructor(private http: Http) {
}
add(
title: string = "",
height: number,
width: number,
mapType: MapType,
creatorId: number,
graphics: string = ""
) {
// TODO: compute hash, id, date and return an Observable<Map>
}
map(id: number) {
}
maps() {
}
delete(id: number) {}
} |
Remove bootstrap dependency from react store | import { createStore, applyMiddleware } from 'redux';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as _ from 'lodash';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import appReducer from './reducers/app';
// import { AppState } from './constants/types';
import { loadState, saveState, setLocalUser } from './localStorage';
import { getToken } from './constants/utils';
import { receiveTokenActionCreator } from './actions/token';
const configureStore = () => {
// const persistedState = loadState();
let middleware = [thunk];
let newMiddleware = [];
if (process.env.NODE_ENV !== 'production') {
setLocalUser();
const loggerMiddleware = createLogger();
newMiddleware = [...middleware, loggerMiddleware];
} else {
newMiddleware = middleware;
}
const store = createStore(
appReducer,
// persistedState,
applyMiddleware(...newMiddleware)
);
let token = getToken();
if (token !== null) {
store.dispatch(receiveTokenActionCreator(token.user, token));
}
store.subscribe(_.throttle(() => {
saveState(store.getState());
}, 1000));
return store;
};
export default configureStore;
| import { createStore, applyMiddleware } from 'redux';
import * as _ from 'lodash';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import appReducer from './reducers/app';
// import { AppState } from './constants/types';
import { loadState, saveState, setLocalUser } from './localStorage';
import { getToken } from './constants/utils';
import { receiveTokenActionCreator } from './actions/token';
const configureStore = () => {
// const persistedState = loadState();
let middleware = [thunk];
let newMiddleware = [];
if (process.env.NODE_ENV !== 'production') {
setLocalUser();
const loggerMiddleware = createLogger();
newMiddleware = [...middleware, loggerMiddleware];
} else {
newMiddleware = middleware;
}
const store = createStore(
appReducer,
// persistedState,
applyMiddleware(...newMiddleware)
);
let token = getToken();
if (token !== null) {
store.dispatch(receiveTokenActionCreator(token.user, token));
}
store.subscribe(_.throttle(() => {
saveState(store.getState());
}, 1000));
return store;
};
export default configureStore;
|
Fix redirect from 'home.infrastructure' to 'home.search' | import { module } from 'angular';
import { STATE_CONFIG_PROVIDER, StateConfigProvider } from 'core/navigation/state.provider';
import { SETTINGS } from 'core/config/settings';
export const INFRASTRUCTURE_STATES = 'spinnaker.core.search.states';
module(INFRASTRUCTURE_STATES, [
STATE_CONFIG_PROVIDER
]).config((stateConfigProvider: StateConfigProvider) => {
'ngInject';
stateConfigProvider.addToRootState({
name: 'search',
url: '/search?q',
reloadOnSearch: false,
views: {
'main@': {
template: `
<infrastructure-search-v1 ng-if="$resolve.version == 1" class="flex-fill"></infrastructure-search-v1>
<infrastructure-search-v2 ng-if="$resolve.version == 2" class="flex-fill"></infrastructure-search-v2>
`,
}
},
data: {
pageTitleMain: {
label: 'Search'
}
},
resolve: {
version: () => SETTINGS.searchVersion || 1,
}
});
stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'search' });
stateConfigProvider.addRewriteRule('/infrastructure?q', '/search?q');
stateConfigProvider.addRewriteRule('', '/search');
stateConfigProvider.addRewriteRule('/', '/search');
});
| import { module } from 'angular';
import { STATE_CONFIG_PROVIDER, StateConfigProvider } from 'core/navigation/state.provider';
import { SETTINGS } from 'core/config/settings';
export const INFRASTRUCTURE_STATES = 'spinnaker.core.search.states';
module(INFRASTRUCTURE_STATES, [
STATE_CONFIG_PROVIDER
]).config((stateConfigProvider: StateConfigProvider) => {
'ngInject';
stateConfigProvider.addToRootState({
name: 'search',
url: '/search?q',
reloadOnSearch: false,
views: {
'main@': {
template: `
<infrastructure-search-v1 ng-if="$resolve.version == 1" class="flex-fill"></infrastructure-search-v1>
<infrastructure-search-v2 ng-if="$resolve.version == 2" class="flex-fill"></infrastructure-search-v2>
`,
}
},
data: {
pageTitleMain: {
label: 'Search'
}
},
resolve: {
version: () => SETTINGS.searchVersion || 1,
}
});
stateConfigProvider.addToRootState({ name: 'infrastructure', url: '/search?q', redirectTo: 'home.search' });
stateConfigProvider.addRewriteRule('/infrastructure?q', '/search?q');
stateConfigProvider.addRewriteRule('', '/search');
stateConfigProvider.addRewriteRule('/', '/search');
});
|
Change initial value of `auth$` behavior subject | import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx';
import { FirebaseAuth, FirebaseAuthState } from 'angularfire2';
@Injectable()
export class AuthService {
auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(null);
constructor (private auth: FirebaseAuth, private router: Router) {
this.auth.subscribe(
data => {
this.auth$.next(data);
},
err => {
this.auth$.error(err);
}
);
}
login(email: string, password: string): Observable<FirebaseAuthState> {
return this.fromFirebaseAuthPromise(this.auth.login({ email, password }));
}
register(email: string, password: string): Observable<FirebaseAuthState> {
return this.fromFirebaseAuthPromise(this.auth.createUser({ email, password }));
}
fromFirebaseAuthPromise(promise): Observable<any> {
const subject = new Subject<any>();
promise
.then(res => {
subject.next(res);
subject.complete();
})
.catch(err => {
subject.error(err);
subject.complete();
});
return subject.asObservable();
}
logout() {
this.auth.logout();
this.router.navigate(['/home']);
}
}
| import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx';
import { FirebaseAuth, FirebaseAuthState } from 'angularfire2';
@Injectable()
export class AuthService {
auth$: BehaviorSubject<FirebaseAuthState> = new BehaviorSubject(undefined);
constructor (private auth: FirebaseAuth, private router: Router) {
this.auth.subscribe(
data => {
this.auth$.next(data);
},
err => {
this.auth$.error(err);
}
);
}
login(email: string, password: string): Observable<FirebaseAuthState> {
return this.fromFirebaseAuthPromise(this.auth.login({ email, password }));
}
register(email: string, password: string): Observable<FirebaseAuthState> {
return this.fromFirebaseAuthPromise(this.auth.createUser({ email, password }));
}
fromFirebaseAuthPromise(promise): Observable<any> {
const subject = new Subject<any>();
promise
.then(res => {
subject.next(res);
subject.complete();
})
.catch(err => {
subject.error(err);
subject.complete();
});
return subject.asObservable();
}
logout() {
this.auth.logout();
this.router.navigate(['/home']);
}
}
|
Fix issues with e2e testing | import { browser, element, by } from '../../node_modules/protractor/built';
describe('grid pager info', () => {
let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'),
gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'),
pageSizeSelector = element(by.tagName('page-size-selector')).$$('select'),
gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input');
beforeEach(() => {
browser.get('/');
});
it('should show text in accordance to numbered of filter rows and current results-page',() => {
expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records');
paginator.get(7).$$('a').click();
pageSizeSelector.$$('option').get(1).click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records');
paginator.get(5).$$('a').click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records');
});
it('should show count in footer', () => {
gridSearchInput.sendKeys('a');
expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)');
});
}); | import { browser, element, by } from '../../node_modules/protractor/built';
describe('grid pager info', () => {
let paginator = element(by.tagName('ngb-pagination')).$$('nav').$$('ul').$$('li'),
gridPagerInfo = element(by.tagName('grid-pager-info')).$$('div'),
pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select');
gridSearchInput = element(by.tagName('grid-search')).$$('div').$$('div').$$('input');
beforeEach(() => {
browser.get('/');
pageSizeSelector.$('[value="10"]').click();
});
it('should show text in accordance to numbered of filter rows and current results-page',() => {
expect(gridPagerInfo.first().getText()).toEqual('Showing 1 to 10 of 53 records');
paginator.get(7).$$('a').click();
pageSizeSelector.$('[value="20"]').click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 21 to 40 of 53 records');
paginator.get(5).$$('a').click();
expect(gridPagerInfo.first().getText()).toEqual('Showing 41 to 60 of 53 records');
});
it('should show count in footer', () => {
gridSearchInput.sendKeys('a');
expect(gridPagerInfo.first().getText()).toContain('(Filtered from 53 total records)');
});
}); |
Add possibility to use EXTENDEDMIND_API_URL for backend address. | import {Server, Config} from "./server";
/**
* Load configuration file given as command line parameter
*/
let config: Config;
if (process.argv.length > 2) {
console.info("loading configuration file: " + process.argv[2]);
config = require(process.argv[2]);
if (process.argv.length > 3) {
config.backend = process.argv[3];
}
if (process.argv.length > 4){
config.generatedFilesPath = process.argv[4];
}
if (process.env.EXTENDEDMIND_URL){
console.info("setting urlOrigin to: " + process.env.EXTENDEDMIND_URL);
config.urlOrigin = process.env.EXTENDEDMIND_URL;
}
}else {
console.error("no configuration file provided, exiting...");
process.exit();
};
const server = new Server(config);
server.run();
| import {Server, Config} from "./server";
/**
* Load configuration file given as command line parameter
*/
let config: Config;
if (process.argv.length > 2) {
console.info("loading configuration file: " + process.argv[2]);
config = require(process.argv[2]);
if (process.argv.length > 3) {
config.backend = process.argv[3];
} else if (process.env.EXTENDEDMIND_API_URL) {
console.info("setting backend to: " + process.env.EXTENDEDMIND_API_URL);
config.backend = process.env.EXTENDEDMIND_API_URL;
}
if (process.env.EXTENDEDMIND_URL){
console.info("setting urlOrigin to: " + process.env.EXTENDEDMIND_URL);
config.urlOrigin = process.env.EXTENDEDMIND_URL;
}
}else {
console.error("no configuration file provided, exiting...");
process.exit();
};
const server = new Server(config);
server.run();
|
Fix core to support strict TS@4.5 | import { renderError } from '../../common';
import { IAppController } from '../app.controller.interface';
import { Config } from '../config';
import { Context, HttpResponse } from '../http';
export async function convertErrorToResponse(
error: Error, ctx: Context, appController: IAppController, log = console.error
): Promise<HttpResponse> {
if (Config.get('settings.logErrors', 'boolean', true)) {
log(error.stack);
}
if (appController.handleError) {
try {
return await appController.handleError(error, ctx);
} catch (error2) {
return renderError(error2, ctx);
}
}
return renderError(error, ctx);
}
| import { renderError } from '../../common';
import { IAppController } from '../app.controller.interface';
import { Config } from '../config';
import { Context, HttpResponse } from '../http';
export async function convertErrorToResponse(
error: Error, ctx: Context, appController: IAppController, log = console.error
): Promise<HttpResponse> {
if (Config.get('settings.logErrors', 'boolean', true)) {
log(error.stack);
}
if (appController.handleError) {
try {
return await appController.handleError(error, ctx);
} catch (error2: any) {
return renderError(error2, ctx);
}
}
return renderError(error, ctx);
}
|
Add width for the item | import { AfterViewInit, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core';
/**
* This component represents the slide item.
*/
@Component({
moduleId: module.id,
selector: 'ngx-agile-slider-item',
template: `
<li #sliderItem class="ngx-agile-slider-item variablewidth">
<ng-content></ng-content>
</li>
`,
encapsulation: ViewEncapsulation.None
})
export class SliderItemComponent implements AfterViewInit {
/**
* additional classes for li
*/
@Input() additionalClasses: string[];
@ViewChild('sliderItem') sliderItem: ElementRef;
/**
* Called after the view was initialized. Adds the additional classes
*/
public ngAfterViewInit() {
if (this.additionalClasses) {
for (let i = 0; i < this.additionalClasses.length; i++) {
this.sliderItem.nativeElement.classList.add(this.additionalClasses[i]);
}
}
}
}
| import { AfterViewInit, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core';
/**
* This component represents the slide item.
*/
@Component({
moduleId: module.id,
selector: 'ngx-agile-slider-item',
template: `
<li #sliderItem class="ngx-agile-slider-item variablewidth">
<ng-content></ng-content>
</li>
`,
encapsulation: ViewEncapsulation.None
})
export class SliderItemComponent implements AfterViewInit {
/**
* additional classes for li
*/
@Input() additionalClasses: string[];
@Input() width: string;
@ViewChild('sliderItem') sliderItem: ElementRef;
/**
* Called after the view was initialized. Adds the additional classes
*/
public ngAfterViewInit() {
if (this.additionalClasses) {
for (let i = 0; i < this.additionalClasses.length; i++) {
this.sliderItem.nativeElement.classList.add(this.additionalClasses[i]);
}
}
if (this.width) {
this.sliderItem.nativeElement.style.width = this.width;
}
}
}
|
Add warning for Node.js 0.10.x deprecation | ///<reference path=".d.ts"/>
"use strict";
// this call must be first to avoid requiring c++ dependencies
require("./common/verify-node-version").verifyNodeVersion(require("../package.json").engines.node);
require("./bootstrap");
import * as fiber from "fibers";
import Future = require("fibers/future");
import * as shelljs from "shelljs";
shelljs.config.silent = true;
import {installUncaughtExceptionListener} from "./common/errors";
installUncaughtExceptionListener(process.exit);
fiber(() => {
let config: Config.IConfig = $injector.resolve("$config");
let err: IErrors = $injector.resolve("$errors");
err.printCallStack = config.DEBUG;
let commandDispatcher: ICommandDispatcher = $injector.resolve("commandDispatcher");
let messages: IMessagesService = $injector.resolve("$messagesService");
messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */];
if (process.argv[2] === "completion") {
commandDispatcher.completeCommand().wait();
} else {
commandDispatcher.dispatchCommand().wait();
}
$injector.dispose();
Future.assertNoFutureLeftBehind();
}).run();
| ///<reference path=".d.ts"/>
"use strict";
let node = require("../package.json").engines.node;
// this call must be first to avoid requiring c++ dependencies
require("./common/verify-node-version").verifyNodeVersion(node, "NativeScript", "2.2.0");
require("./bootstrap");
import * as fiber from "fibers";
import Future = require("fibers/future");
import * as shelljs from "shelljs";
shelljs.config.silent = true;
import {installUncaughtExceptionListener} from "./common/errors";
installUncaughtExceptionListener(process.exit);
fiber(() => {
let config: Config.IConfig = $injector.resolve("$config");
let err: IErrors = $injector.resolve("$errors");
err.printCallStack = config.DEBUG;
let commandDispatcher: ICommandDispatcher = $injector.resolve("commandDispatcher");
let messages: IMessagesService = $injector.resolve("$messagesService");
messages.pathsToMessageJsonFiles = [/* Place client-specific json message file paths here */];
if (process.argv[2] === "completion") {
commandDispatcher.completeCommand().wait();
} else {
commandDispatcher.dispatchCommand().wait();
}
$injector.dispose();
Future.assertNoFutureLeftBehind();
}).run();
|
Add a test for quick-info | /// <reference path='fourslash.ts' />
//// var name1 = undefined, id1 = undefined;
//// var /*obj1*/obj1 = {/*name1*/name1, /*id1*/id1};
//// var name2 = "Hello";
//// var id2 = 10000;
//// var /*obj2*/obj2 = {/*name2*/name2, /*id2*/id2};
goTo.marker("obj1");
verify.quickInfoIs("(var) obj1: {\n name1: any;\n id1: any;\n}");
goTo.marker("name1");
verify.quickInfoIs("(property) name1: any");
goTo.marker("id1");
verify.quickInfoIs("(property) id1: any");
goTo.marker("obj2");
verify.quickInfoIs("(var) obj2: {\n name2: string;\n id2: number;\n}");
goTo.marker("name2");
verify.quickInfoIs("(property) name2: string");
goTo.marker("id2");
verify.quickInfoIs("(property) id2: number");
| |
Add commented-out input instruction test file | /*
import { expect } from 'chai'
import Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { InputInstructionNode } from '../../SyntaxNodes/InputInstructionNode'
describe('Text surrounded by curly brackets', () => {
it('is put into an input instruciton node', () => {
expect(Up.toAst('Press {esc} to quit.')).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Press '),
new InputInstructionNode('esc'),
new PlainTextNode('to quit'),
]))
})
})
describe('An input instruction', () => {
it('is not evaluated for other conventions', () => {
expect(Up.toAst("Select the {Start Game(s)} menu item.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Hello, '),
new InputInstructionNode('Start Games(s)'),
new PlainTextNode('!')
]))
})
it('has any outer whitespace trimmed away', () => {
expect(Up.toAst("Select the { \t Start Game(s) \t } menu item.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Select the '),
new InputInstructionNode('Start Games(s)'),
new PlainTextNode('menu item.')
]))
})
context('can contain escaped closing curly brackets', () => {
it('touching the delimiters', () => {
expect(Up.toAst("Press {\\}} to view paths.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Press '),
new InputInstructionNode('}'),
new PlainTextNode(' to view paths')
]))
})
it('not touching the delimiters', () => {
expect(Up.toAst("Press { \\} } to view paths.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Press '),
new InputInstructionNode('}'),
new PlainTextNode(' to view paths')
]))
})
})
context('can contain unescaped opening curly brackets', () => {
it('touching the delimiters', () => {
expect(Up.toAst("Press {{} to view paths.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Press '),
new InputInstructionNode('}'),
new PlainTextNode(' to view paths')
]))
})
it('not touching the delimiters', () => {
expect(Up.toAst("Press { { } to view paths.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Press '),
new InputInstructionNode('}'),
new PlainTextNode(' to view paths')
]))
})
})
it('can be directly followed by another input instruction', () => {
expect(Up.toAst("Press {ctrl}{q} to quit.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('Hello, '),
new InputInstructionNode('Start Games(s)'),
new PlainTextNode('!')
]))
})
})
*/ | |
Add scroll event mock generator | import {
NativeSyntheticEvent,
NativeScrollEvent,
NativeScrollPoint,
} from 'react-native';
export default (
contentOffset?: NativeScrollPoint,
): NativeSyntheticEvent<NativeScrollEvent> => ({
nativeEvent: {
contentOffset: { x: 0, y: 50, ...contentOffset },
contentInset: { top: 0, right: 0, left: 0, bottom: 0 },
contentSize: { width: 0, height: 0 },
layoutMeasurement: { width: 0, height: 0 },
zoomScale: 1,
},
bubbles: false,
cancelable: false,
currentTarget: 0,
defaultPrevented: false,
eventPhase: 0,
isDefaultPrevented: () => false,
isPropagationStopped: () => false,
isTrusted: false,
persist: () => {},
preventDefault: () => {},
stopPropagation: () => false,
target: 0,
timeStamp: 0,
type: '',
});
| |
Add helper to quickly write tests for tests/data/... examples | import { readFileTree } from '../../files/deno.ts'
import { FileTree } from '../../types/filetree.ts'
import { validate } from '../../validators/bids.ts'
import { ValidationResult } from '../../types/validation-result.ts'
import { DatasetIssues } from '../../issues/datasetIssues.ts'
export async function validatePath(
t: Deno.TestContext,
path: string,
): Promise<{ tree: FileTree; result: ValidationResult }> {
let tree: FileTree = new FileTree('', '')
let result: ValidationResult = { issues: new DatasetIssues(), summary: {} }
await t.step('file tree is read', async () => {
tree = await readFileTree(path)
})
await t.step('completes validation', async () => {
result = await validate(tree)
})
return { tree, result }
}
| |
Remove a commented out import. | //import * as fs from "fs";
import Utils from "./Utils";
import Job from "./Job";
import {existsSync, statSync} from "fs";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let newDirectory: string;
if (!args.length) {
newDirectory = Utils.homeDirectory;
} else {
newDirectory = Utils.resolveDirectory(job.directory, args[0]);
if (!existsSync(newDirectory)) {
throw new Error(`The directory ${newDirectory} doesn"t exist.`);
}
if (!statSync(newDirectory).isDirectory()) {
throw new Error(`${newDirectory} is not a directory.`);
}
}
job.terminal.currentDirectory = newDirectory;
},
clear: (job: Job, args: string[]): void => {
setTimeout(() => job.terminal.clearJobs(), 0);
},
exit: (job: Job, args: string[]): void => {
// FIXME.
},
};
// A class representing built in commands
export default class Command {
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return ["cd", "clear", "exit"].includes(command);
}
}
| import Utils from "./Utils";
import Job from "./Job";
import {existsSync, statSync} from "fs";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let newDirectory: string;
if (!args.length) {
newDirectory = Utils.homeDirectory;
} else {
newDirectory = Utils.resolveDirectory(job.directory, args[0]);
if (!existsSync(newDirectory)) {
throw new Error(`The directory ${newDirectory} doesn"t exist.`);
}
if (!statSync(newDirectory).isDirectory()) {
throw new Error(`${newDirectory} is not a directory.`);
}
}
job.terminal.currentDirectory = newDirectory;
},
clear: (job: Job, args: string[]): void => {
setTimeout(() => job.terminal.clearJobs(), 0);
},
exit: (job: Job, args: string[]): void => {
// FIXME.
},
};
// A class representing built in commands
export default class Command {
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return ["cd", "clear", "exit"].includes(command);
}
}
|
Update styled-jsx/css typings, add tests for methods css.global and css.resolve | import * as React from 'react';
import * as css from 'styled-jsx/css';
import flushToReact, { flushToHTML } from 'styled-jsx/server';
const styled = (
<div>
<style jsx>{`
color: rebeccapurple;
`}</style>
</div>
);
const styledGlobal = (
<div>
<style jsx global>{`
color: rebeccapurple;
`}</style>
</div>
);
const buttonColor = 'red';
const separatedCSS = css`button { color: ${buttonColor}; }`;
const withSeparatedCSS = (
<div>
<style jsx>{separatedCSS}</style>
</div>
);
const stylesChildren = flushToReact();
const jsxToRender = (
<head>{ stylesChildren }</head>
);
const stylesAsString: string = flushToHTML();
const html = `
<head>${stylesAsString}</head>
`;
| import * as React from 'react';
import * as css from 'styled-jsx/css';
import flushToReact, { flushToHTML } from 'styled-jsx/server';
const styled = (
<div>
<style jsx>{`
color: rebeccapurple;
`}</style>
</div>
);
const styledGlobal = (
<div>
<style jsx global>{`
color: rebeccapurple;
`}</style>
</div>
);
const buttonColor = 'red';
const separatedCSS = css`button { color: ${buttonColor}; }`;
const withSeparatedCSS = (
<div>
<style jsx>{separatedCSS}</style>
</div>
);
const globalCSS = css.global`body { margin: 0; }`;
const withGlobalCSS = (
<div>
<style jsx global>{globalCSS}</style>
</div>
);
const resolvedCSS = css.resolve`a { color: green; }`;
const withResolvedCSS = (
<div>
<button className={resolvedCSS.className}>About</button>
{resolvedCSS.styles}
</div>
);
const dynamicResolvedCSS = css.resolve`a { color: ${buttonColor}; }`;
const withDynamicResolvedCSS = (
<div>
<button className={dynamicResolvedCSS.className}>About</button>
{dynamicResolvedCSS.styles}
</div>
);
const stylesChildren = flushToReact();
const jsxToRender = (
<head>{ stylesChildren }</head>
);
const stylesAsString: string = flushToHTML();
const html = `
<head>${stylesAsString}</head>
`;
|
Add EmptyState component for when no HITs are in the redux store | import * as React from 'react';
import { EmptyState } from '@shopify/polaris';
export interface Props {
onAction: () => void;
}
const EmptyHitTable = ({ onAction }: Props) => {
return (
<EmptyState
heading="You haven't searched any HITs yet."
action={{
content: 'Search HITs',
onAction
}}
image="https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg"
>
<p>Search some HITs to get started.</p>
</EmptyState>
);
};
export default EmptyHitTable; | |
Add Search Resource Unit Test: | import { SearchResource } from './search.resource';
describe('Resource Search', () => {
beforeEach(angular.mock.module('roam'));
it('should be registered', inject((searchResource: SearchResource) => {
expect(searchResource).not.toBeNull();
}));
});
| |
Add a notebook widget factory | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IKernelId
} from 'jupyter-js-services';
import {
IWidgetFactory, IDocumentContext
} from 'jupyter-js-ui/lib/docmanager';
import {
RenderMime
} from 'jupyter-js-ui/lib/rendermime';
import {
MimeData as IClipboard
} from 'phosphor-dragdrop';
import {
Widget
} from 'phosphor-widget';
import {
INotebookModel
} from './model';
import {
NotebookPanel
} from './panel';
/**
* A widget factory for notebook panels.
*/
export
class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
/**
* Construct a new notebook widget factory.
*/
constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
this._rendermime = rendermime;
this._clipboard = clipboard;
}
/**
* Get whether the factory has been disposed.
*/
get isDisposed(): boolean {
return this._rendermime === null;
}
/**
* Dispose of the resources used by the factory.
*/
dispose(): void {
this._rendermime = null;
this._clipboard = null;
}
/**
* Create a new widget.
*/
createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
let rendermime = this._rendermime.clone();
if (kernel) {
context.changeKernel(kernel);
}
return new NotebookPanel(model, rendermime, context, this._clipboard);
}
/**
* Take an action on a widget before closing it.
*
* @returns A promise that resolves to true if the document should close
* and false otherwise.
*/
beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
// No special action required.
return Promise.resolve(true);
}
private _rendermime: RenderMime<Widget> = null;
private _clipboard: IClipboard = null;
}
| |
Add more object shape properties to AuditResult. | interface AuditResult {
displayValue: string;
debugString: string;
comingSoon?: boolean;
score: number;
description: string;
extendedInfo?: {
value: string;
formatter: string;
};
}
interface AggregationResultItem {
overall: number;
name: string;
scored: boolean;
subItems: Array<AuditResult | string>;
}
interface Aggregation {
name: string;
score: Array<AggregationResultItem>;
}
interface Results {
url: string;
aggregations: Array<Aggregation>;
audits: Object;
lighthouseVersion: string;
};
export {
Results,
Aggregation,
AggregationResultItem,
AuditResult,
}
| interface AuditResult {
displayValue: string;
debugString: string;
comingSoon?: boolean;
score: number;
description: string;
name: string;
category: string;
helpText?: string;
requiredArtifacts?: Array<string>;
extendedInfo?: {
value: string;
formatter: string;
};
}
interface AggregationResultItem {
overall: number;
name: string;
scored: boolean;
subItems: Array<AuditResult | string>;
}
interface Aggregation {
name: string;
score: Array<AggregationResultItem>;
}
interface Results {
url: string;
aggregations: Array<Aggregation>;
audits: Object;
lighthouseVersion: string;
};
export {
Results,
Aggregation,
AggregationResultItem,
AuditResult,
}
|
Add test for support of custom decorator names. | import {
getType,
} from '../src';
function UserDecorator(target: any) { }
function OtherDecorator(target: any) { }
@UserDecorator
export class MyClassA {
a: string;
}
@OtherDecorator
export class MyClassB {
a: string;
}
describe('Custom Decorators', () => {
// Note UserDecorator is configured in webpack.test.js
it('should allow UserDecorator', () => {
const clsType = getType(MyClassA);
expect(clsType).not.toBeNull();
});
it('should throw on non-decorated', () => {
expect(() => {
getType(MyClassB);
}).toThrow();
});
});
| |
Add failing code block test | /// <reference path="../../../typings/mocha/mocha.d.ts" />
/// <reference path="../../../typings/chai/chai.d.ts" />
import { expect } from 'chai'
import * as Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { CodeBlockNode } from '../../SyntaxNodes/CodeBlockNode'
function insideDocument(syntaxNodes: SyntaxNode[]): DocumentNode {
return new DocumentNode(syntaxNodes);
}
describe('Text surrounded (underlined and overlined) by streaks of backticks', function() {
it('produces a code block node containing the surrounded text', function() {
const text =
`
\`\`\`
let x = y
\`\`\``
expect(Up.ast(text)).to.be.eql(
insideDocument([
new CodeBlockNode([
new PlainTextNode('let x = y')
]),
]))
})
})
| |
Add a notebook widget factory | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IKernelId
} from 'jupyter-js-services';
import {
IWidgetFactory, IDocumentContext
} from 'jupyter-js-ui/lib/docmanager';
import {
RenderMime
} from 'jupyter-js-ui/lib/rendermime';
import {
MimeData as IClipboard
} from 'phosphor-dragdrop';
import {
Widget
} from 'phosphor-widget';
import {
INotebookModel
} from './model';
import {
NotebookPanel
} from './panel';
/**
* A widget factory for notebook panels.
*/
export
class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
/**
* Construct a new notebook widget factory.
*/
constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
this._rendermime = rendermime;
this._clipboard = clipboard;
}
/**
* Get whether the factory has been disposed.
*/
get isDisposed(): boolean {
return this._rendermime === null;
}
/**
* Dispose of the resources used by the factory.
*/
dispose(): void {
this._rendermime = null;
this._clipboard = null;
}
/**
* Create a new widget.
*/
createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
let rendermime = this._rendermime.clone();
if (kernel) {
context.changeKernel(kernel);
}
return new NotebookPanel(model, rendermime, context, this._clipboard);
}
/**
* Take an action on a widget before closing it.
*
* @returns A promise that resolves to true if the document should close
* and false otherwise.
*/
beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
// No special action required.
return Promise.resolve(true);
}
private _rendermime: RenderMime<Widget> = null;
private _clipboard: IClipboard = null;
}
| |
Fix case on TwitchUptime filename | import MessageHandler from "../messageHandler";
import ExtendedInfo from "../extendedInfo";
import TwitchExtendedInfo from "../extendedInfos/twitchExtendedInfo";
import MessageFloodgate from "../messageFloodgate";
import fetch from "node-fetch";
import * as fs from "fs";
function readSettings(): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile("resources/twitchUptime.json", "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
});
}
class TwitchUptime implements MessageHandler {
private _channel: string;
private constructor(channel: string) {
this._channel = channel;
}
public static async create() {
const data = await readSettings();
const channel = JSON.parse(data).channel;
return new TwitchUptime(channel);
}
private _floodgate = new MessageFloodgate(10);
async handleMessage(responder: (content: string) => Promise<void>, content: string, info: ExtendedInfo | undefined) {
const resp = this._floodgate.createResponder(responder);
if (info == undefined || info.type != "TWITCH")
return;
if (/^!uptime$/.test(content)) {
try {
const request = await fetch(`https://decapi.me/twitch/uptime?channel=${this._channel}`);
const text = await request.text();
if (text.indexOf("offline") == -1) {
await resp(`Live for ${text}.`, false);
} else {
await resp(`Offline. (API updates are sometimes delayed)`, false);
}
} catch {
await resp("Couldn't retrieve uptime info—error in request?", false);
}
}
}
}
export default TwitchUptime; | |
Add type interface for old data structures | /**
* Represent the data structure of a game in v1.0.0
*/
export interface IOldGameData {
/**
* Current round of the game
*/
currentRound: number
/**
* The index of maker of this round. Points to the players array.
*/
maker: number
/**
* Array of players in the game
*/
players: IOldPlayers[]
/**
* Current stage of the game
*/
state: IOldState
/**
* Total number of rounds of the game
*/
totalRounds: number
}
/**
* Represent the data structure of a player in v1.0.0
*/
export interface IOldPlayers {
/**
* Bid for the current round.
*/
bid: number
/**
* Win for the current round.
*/
win: number
/**
* Score of each round.
* Index of the array represent the round number.
* While value is the score this player got on that round.
*/
score: number[]
/**
* Name of this player
*/
name: string
}
/**
* The enum for state property under IOldGameData
*/
export enum IOldState {
/**
* No info is filled in. Game is not yet started.
*/
notStarted = 0,
/**
* bid for stack before each round
*/
bid = 1,
/**
* Wait for user to input win stack
*/
inputWin = 2,
/**
* This round has ended. Showing this round result and wait for next round to start
*/
waiting = 3,
/**
* Game has end by reaching the last round and ended
*/
gameEnd = 4
}
| |
Add implementation of Queue in TypeScript | interface Queue<T> {
readonly length: number;
enqueue(value: T): number;
dequeue(): T | undefined;
peek(): T | undefined;
isEmpty(): boolean;
[Symbol.iterator](): IterableIterator<T>;
}
class QueueImpl<T> implements Queue<T> {
private _store: Array<T> = [];
get length(): number {
return this._store.length;
}
public enqueue(value: T): number {
this._store.push(value);
return this._store.length;
}
public dequeue(): T | undefined {
if (this.isEmpty()) return undefined;
return this._store.shift();
}
public peek(): T | undefined {
if (this.isEmpty()) return undefined;
return this._store[0];
}
public isEmpty() {
return this._store.length === 0;
}
public next(): IteratorResult<T> {
if (!this.isEmpty()) {
return { done: false, value: this.dequeue() as any as T }
}
return { done: true, value: undefined };
}
[Symbol.iterator](): IterableIterator<T> {
return this;
}
}
let testQueue: Queue<number> = new QueueImpl();
console.log(`The queue is currently ${testQueue.length} items long`);
testQueue.enqueue(3);
testQueue.enqueue(4);
testQueue.enqueue(5);
console.log(`The queue is currently ${testQueue.length} items long`);
console.log('\nThe items in the queue are:');
for (let item of testQueue) {
console.log(item);
}
console.log(`\nThe queue is now ${testQueue.isEmpty() ? "empty" : "not empty"}`);
| |
Test KapacitorRulesTable tr keys to be UUIDv4 | import React from 'react'
import {shallow} from 'enzyme'
import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable'
import {source, kapacitorRules} from 'test/resources'
const setup = () => {
const props = {
source,
rules: kapacitorRules,
onDelete: () => {},
onChangeRuleStatus: () => {}
}
const wrapper = shallow(<KapacitorRulesTable {...props} />)
return {
wrapper,
props
}
}
describe('Kapacitor.Components.KapacitorRulesTable', () => {
describe('rendering', () => {
it('renders KapacitorRulesTable', () => {
const {wrapper} = setup()
expect(wrapper.exists()).toBe(true)
})
})
})
| import React from 'react'
import {shallow} from 'enzyme'
import {isUUIDv4} from 'src/utils/stringValidators'
import KapacitorRulesTable from 'src/kapacitor/components/KapacitorRulesTable'
import {source, kapacitorRules} from 'test/resources'
const setup = () => {
const props = {
source,
rules: kapacitorRules,
onDelete: () => {},
onChangeRuleStatus: () => {},
}
const wrapper = shallow(<KapacitorRulesTable {...props} />)
return {
wrapper,
props,
}
}
describe('Kapacitor.Components.KapacitorRulesTable', () => {
describe('rendering', () => {
it('renders KapacitorRulesTable', () => {
const {wrapper} = setup()
expect(wrapper.exists()).toBe(true)
})
it('renders each row with key that is a UUIDv4', () => {
const {wrapper} = setup()
wrapper
.find('tbody')
.children()
.forEach(child => expect(isUUIDv4(child.key())).toEqual(true))
})
})
})
|
Add helper for MSA auth tokens. | import * as request from "request";
export interface Token {
token_type: string;
expires_in: number;
ext_expires_in: number;
access_token: string;
}
interface CachedToken extends Token {
expires_on: number;
}
let cachedToken: CachedToken;
export function getBotframeworkToken(): Promise<Token> {
return new Promise((resolve, reject) => {
try {
if (tokenIsExpired()) {
request.post({
url: "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
form: {
grant_type: "client_credentials",
client_id: process.env["MicrosoftAppId"],
client_secret: process.env["MicrosoftAppSecret"],
scope: "https://api.botframework.com/.default"
}
}, function (err, response, body) {
if (response.statusCode === 200) {
let token = JSON.parse(body) as Token;
let now = new Date();
token["expires_on"] = now.getTime() + token.expires_in * 1000;
cachedToken = token as CachedToken;
resolve(cachedToken);
} else {
reject(err);
}
});
} else {
resolve(cachedToken);
}
} catch (error) {
console.log("error fetching token: " + error);
reject(error);
}
});
}
function tokenIsExpired(): boolean {
let now = new Date();
return !cachedToken || now.getTime() > (cachedToken.expires_on - 5 * 1000);
}
export function validateToken() {
// TODO: validate token from bot service
// https://docs.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-connector-authentication
} | |
Add test for whatwg normalizer | 'use strict';
import * as assert from 'power-assert';
import * as url from 'url';
import * as whatwg from '../rules/whatwg';
//
describe('whatwg', () => {
it('should normalize protocol', () => {
const httpURL = 'http://dom.spec.whatwg.org/';
const actual = whatwg.normalize(url.parse(httpURL));
const expected = 'https://dom.spec.whatwg.org/';
assert(actual === expected);
});
it('should normalize urls of html standard', () => {
const oldURLs = [
'http://whatwg.org/html/#applicationcache',
'http://whatwg.org/html#2dcontext',
'http://www.whatwg.org/specs/web-apps/current-work/#attr-fe-minlength',
'http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constraints',
'https://html.spec.whatwg.org/#imagebitmapfactories',
];
const normalizedURLs = [
'https://html.spec.whatwg.org/multipage/browsers.html#applicationcache',
'https://html.spec.whatwg.org/multipage/scripting.html#2dcontext',
'https://html.spec.whatwg.org/multipage/forms.html#attr-fe-minlength',
'https://html.spec.whatwg.org/multipage/forms.html#constraints',
'https://html.spec.whatwg.org/multipage/webappapis.html#imagebitmapfactories',
];
for (let i = 0; i < oldURLs.length; i++) {
const actual = whatwg.normalize(url.parse(oldURLs[i]));
const expected = normalizedURLs[i];
assert(actual === expected);
}
});
});
| |
Support passing ws options to listen. | // Type definitions for koa-websocket 2.1
// Project: https://github.com/kudos/koa-websocket
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import Koa = require('koa');
import * as ws from 'ws';
import * as http from 'http';
import * as https from 'https';
type KoaWebsocketConnectionHandler = (socket: ws) => void;
type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise<any>) => any;
interface KoaWebsocketMiddlewareContext extends Koa.Context {
websocket: ws;
path: string;
}
declare class KoaWebsocketServer {
app: Koa;
middleware: Koa.Middleware[];
constructor(app: Koa);
listen(server: http.Server | https.Server): ws.Server;
onConnection(handler: KoaWebsocketConnectionHandler): void;
use(middleware: KoaWebsocketMiddleware): this;
}
interface KoaWebsocketApp extends Koa {
ws: KoaWebsocketServer;
}
declare function websockets(app: Koa): KoaWebsocketApp;
export = websockets;
| // Type definitions for koa-websocket 5.0
// Project: https://github.com/kudos/koa-websocket
// Definitions by: Maël Lavault <https://github.com/moimael>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import Koa = require('koa');
import * as ws from 'ws';
import * as http from 'http';
import * as https from 'https';
type KoaWebsocketConnectionHandler = (socket: ws) => void;
type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise<any>) => any;
interface KoaWebsocketMiddlewareContext extends Koa.Context {
websocket: ws;
path: string;
}
declare class KoaWebsocketServer {
app: Koa;
middleware: Koa.Middleware[];
constructor(app: Koa);
listen(options: ws.ServerOptions): ws.Server;
onConnection(handler: KoaWebsocketConnectionHandler): void;
use(middleware: KoaWebsocketMiddleware): this;
}
interface KoaWebsocketApp extends Koa {
ws: KoaWebsocketServer;
}
declare function websockets(app: Koa): KoaWebsocketApp;
export = websockets;
|
Add test to verify does not overwrite existing implementation | import * as fs from "fs";
import { assert } from "chai";
describe("Reflect", () => {
it("does not overwrite existing implementation", () => {
const defineMetadata = Reflect.defineMetadata;
const reflectPath = require.resolve("../Reflect.js");
const reflectContent = fs.readFileSync(reflectPath, "utf8");
const reflectFunction = Function(reflectContent);
reflectFunction();
assert.strictEqual(Reflect.defineMetadata, defineMetadata);
});
}); | |
Fix apply changes to work when response is null | var Range = require('atom').Range;
import {Observable} from "rx";
export function applyChanges(editor: Atom.TextEditor, response: { Changes: OmniSharp.Models.LinePositionSpanTextChange[]; });
export function applyChanges(editor: Atom.TextEditor, response: { Buffer: string });
export function applyChanges(editor: Atom.TextEditor, response: any) {
if (response && response.Changes) {
var buffer = editor.getBuffer();
var checkpoint = buffer.createCheckpoint();
response.Changes.forEach((change) => {
var range = new Range([change.StartLine, change.StartColumn], [change.EndLine, change.EndColumn]);
buffer.setTextInRange(range, change.NewText);
});
buffer.groupChangesSinceCheckpoint(checkpoint);
} else if (response && response.Buffer) {
editor.setText(response.Buffer)
}
}
// If you have preview tabs enabled,
// they will actually try to close
// with changes still.
function resetPreviewTab() {
var pane: HTMLElement = <any>atom.views.getView(atom.workspace.getActivePane());
if (pane) {
var title = pane.querySelector('.title.temp');
if (title) {
title.classList.remove('temp');
}
var tab = pane.querySelector('.preview-tab.active');
if (tab) {
tab.classList.remove('preview-tab');
(<any>tab).isPreviewTab = false;
}
}
}
export function applyAllChanges(changes: OmniSharp.Models.ModifiedFileResponse[]) {
resetPreviewTab();
return Observable.from(changes || [])
.concatMap(change => atom.workspace.open(change.FileName, undefined)
.then(editor => {
resetPreviewTab();
applyChanges(editor, change);
}))
.subscribe();
}
| |
Add Context to setup query/ dir | /**
* Copyright 2018 The Lovefield Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {assert} from '../base/assert';
import {Predicate} from '../base/predicate';
import {PredicateNode} from '../pred/predicate_node';
import {ValuePredicate} from '../pred/value_predicate';
import {Database} from '../schema/database';
import {Table} from '../schema/table';
// Base context for all query types.
export abstract class Context {
// Creates predicateMap such that predicates can be located by ID.
private static buildPredicateMap(rootPredicate: PredicateNode):
Map<number, Predicate> {
const predicateMap = new Map<number, Predicate>();
rootPredicate.traverse((n) => {
const node = n as PredicateNode as Predicate;
predicateMap.set(node.getId(), node);
return true;
});
return predicateMap;
}
public schema: Database;
public where: Predicate|null;
public clonedFrom: Context|null;
// A map used for locating predicates by ID. Instantiated lazily.
private predicateMap: Map<number, Predicate>;
constructor(schema: Database) {
this.schema = schema;
this.clonedFrom = null;
this.where = null;
this.predicateMap = null as any as Map<number, Predicate>;
}
public getPredicate(id: number): Predicate {
if (this.predicateMap === null && this.where !== null) {
this.predicateMap =
Context.buildPredicateMap(this.where as PredicateNode);
}
const predicate: Predicate = this.predicateMap.get(id) as Predicate;
assert(predicate !== undefined);
return predicate;
}
public bind(values: any[]): Context {
assert(this.clonedFrom === null);
return this;
}
public bindValuesInSearchCondition(values: any[]): void {
const searchCondition: PredicateNode = this.where as PredicateNode;
if (searchCondition !== null) {
searchCondition.traverse((node) => {
if (node instanceof ValuePredicate) {
node.bind(values);
}
return true;
});
}
}
public abstract getScope(): Set<Table>;
public abstract clone(): Context;
protected cloneBase(context: Context): void {
if (context.where) {
this.where = context.where.copy();
}
this.clonedFrom = context;
}
}
| |
Implement basic initial integration tests for 404 and 500 | // NOTE Running these tests requires the crossroads-education/eta-web-test module to be installed.
process.env.ETA_TESTING = "true";
process.env.ETA_AUTH_PROVIDER = "cre-web-test";
import tests from "../../server/api/tests";
before(function(done) {
this.timeout(20000); // plenty of time to initialize the server
tests.init().then(() => {
done();
}).catch(err => console.error(err));
});
describe("Requests", () => {
it("should handle a 404 request properly", done => {
tests.request()
.get("/test/foobar")
.expect(404, done);
});
it("should handle a 500 request properly", done => {
tests.request()
.get("/test/error")
.expect(500, done);
});
});
| |
Add unit test cases for toLowercase decorator | import { ToLowercase } from './../../src/';
describe('ToLowercase decorator', () => {
it('should throw an error when is applied over non string property', () => {
class TestClassToLowercaseProperty {
@ToLowercase() myProp: number;
}
let testClass = new TestClassToLowercaseProperty();
expect(() => testClass.myProp = 7).toThrowError('The ToLowercase decorator has to be used over string object');
});
it('should apply default behavior', () => {
class TestClassToLowercaseProperty {
@ToLowercase() myProp: string;
}
let testClass = new TestClassToLowercaseProperty();
let stringToAssign = 'A long String to Be tested';
testClass.myProp = stringToAssign;
expect(testClass.myProp).toEqual(stringToAssign.toLowerCase());
});
it('should use locale', () => {
class TestClassToLowercaseProperty {
@ToLowercase({ useLocale: true }) myProp: string;
}
let testClass = new TestClassToLowercaseProperty();
let stringToAssign = 'A long String to Be tested';
testClass.myProp = stringToAssign;
expect(testClass.myProp).toEqual(stringToAssign.toLocaleLowerCase());
});
}); | |
Add tests for connect typings | /// <reference path="./connect.d.ts" />
import * as http from "http";
import * as connect from "connect";
const app = connect();
// log all requests
app.use((req, res, next) => {
console.log(req, res);
next();
});
// Stop on errors
app.use((err, req, res, next) => {
if (err) {
return res.end(`Error: ${err}`);
}
next();
});
// respond to all requests
app.use((req, res) => {
res.end("Hello from Connect!\n");
});
//create node.js http server and listen on port
http.createServer(app).listen(3000);
//create node.js http server and listen on port using connect shortcut
app.listen(3000);
| |
Add a shared stacks helper | import { EventType } from 'parser/core/Events';
/**
* Returns the current stacks on a given event
* @param event
*/
export function currentStacks(event: any) {
switch (event.type) {
case EventType.RemoveBuff || EventType.RemoveDebuff:
return 0;
case EventType.ApplyBuff || EventType.ApplyDebuff:
return 1;
case EventType.ApplyBuffStack || EventType.RemoveBuffStack || EventType.ApplyDebuffStack || EventType.RemoveDebuffStack:
return event.stack;
default:
return null;
}
}
| |
Add a filter which populates the auth header for avatar requests | import { EndpointToken } from '../lib/endpoint-token'
import { OrderedWebRequest } from './ordered-webrequest'
export function installAuthenticatedAvatarFilter(
orderedWebRequest: OrderedWebRequest
) {
let originTokens = new Map<string, string>()
orderedWebRequest.onBeforeSendHeaders.addEventListener(async details => {
const { origin, pathname } = new URL(details.url)
const token = originTokens.get(origin)
if (token && pathname.startsWith('/api/v3/enterprise/avatars/')) {
return {
requestHeaders: {
...details.requestHeaders,
Authorization: `token ${token}`,
},
}
}
return {}
})
return (accounts: ReadonlyArray<EndpointToken>) => {
originTokens = new Map(
accounts.map(({ endpoint, token }) => [new URL(endpoint).origin, token])
)
}
}
| |
Refactor - split script into small modules | import { modifyManifest } from './modifyManifest';
export function postlinkAndroid() {
try {
modifyManifest();
} catch (e) {
console.warn('Failed to automatically update android manifest. Please continue manually');
}
}
| |
Add unit tests for range decorator | import { Range } from './../../src/';
describe('Range decorator', () => {
it('should throw an error when no annotations are provided', () => {
expect(() => {
class TestClassRangeValue {
@Range() // This will throw a TypeScript error (obviously)
myNumber: number;
}
}).toThrowError('No range options provided');
});
it('should throw an error when the min and ax range values are invalid', () => {
expect(() => {
class TestClassRangeValue {
@Range({ max: 0, min: 10 })
myNumber: number;
}
}).toThrowError('The min range value has to be less than max value');
});
it('should throw an error when the min value are invalid (not a number)', () => {
expect(() => {
class TestClassRangeValue {
@Range({ max: 10, min: +'A' })
myNumber: number;
}
}).toThrowError('The min range value is mandatory');
});
it('should throw an error when the max value are invalid (not a number)', () => {
expect(() => {
class TestClassRangeValue {
@Range({ min: 0, max: +'A' })
myNumber: number;
}
}).toThrowError('The max range value is mandatory');
});
it('should assign a valid value (inside the range)', () => {
class TestClassRangeValue {
@Range({ min: 0, max: 10 })
myNumber: number;
}
let testClass = new TestClassRangeValue();
let valueToAssign = 5;
testClass.myNumber = valueToAssign;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should protect the value when invalid value is assigned', () => {
class TestClassRangeValue {
@Range({ min: 0, max: 10, protect: true })
myNumber: number;
}
let testClass = new TestClassRangeValue();
let valueToAssign = 5;
testClass.myNumber = valueToAssign;
testClass.myNumber = 15;
expect(testClass.myNumber).toEqual(valueToAssign);
});
it('should throw an error when invalid value is assigned', () => {
class TestClassRangeValue {
@Range({ min: 0, max: 10, protect: false, throwOutOfRange: true })
myNumber: number;
}
let testClass = new TestClassRangeValue();
let valueToAssign = 5;
testClass.myNumber = valueToAssign;
expect(() => testClass.myNumber = 15).toThrowError('Value out of range!');
});
}); | |
Add test relating type predicates with and without this parameters | // @strict: true
interface ListItem<TData> {
prev: ListItem<TData> | null;
next: ListItem<TData> | null;
data: TData;
}
type IteratorFn<TData, TResult, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => TResult;
type FilterFn<TData, TResult extends TData, TContext = List<TData>> = (this: TContext, item: TData, node: ListItem<TData>, list: List<TData>) => item is TResult;
declare class List<TData> {
filter<TContext, TResult extends TData>(fn: FilterFn<TData, TResult, TContext>, context: TContext): List<TResult>;
filter<TResult extends TData>(fn: FilterFn<TData, TResult>): List<TResult>;
filter<TContext>(fn: IteratorFn<TData, boolean, TContext>, context: TContext): List<TData>;
filter(fn: IteratorFn<TData, boolean>): List<TData>;
}
interface Test {
a: string;
}
const list2 = new List<Test | null>();
const filter1 = list2.filter(function(item, node, list): item is Test {
this.b; // $ExpectType string
item; // $ExpectType Test | null
node; // $ExpectType ListItem<Test | null>
list; // $ExpectType List<Test | null>
return !!item;
}, {b: 'c'});
const x: List<Test> = filter1; // $ExpectType List<Test>
| |
Add pokemon types - Refactoring | import { Type } from './type.model';
import { ItemTemplate } from '@core/game_master/gameMaster';
import { Util } from '@util';
export class TypeMapper {
public static Map(rawType: ItemTemplate, typeIds: Map<number, string>): Type {
let type: Type = new Type();
type.id = rawType.templateId
type.name = Util.SnakeCase2HumanReadable(rawType.templateId.replace('POKEMON_TYPE_', ''));
type.damage = [];
for (let i = 0; i < rawType.typeEffective.attackScalar.length; i++) {
type.damage.push({
id: typeIds.get(i),
attackScalar: rawType.typeEffective.attackScalar[i]
});
}
return type
}
}
| import { Type } from './type.model';
import { ItemTemplate } from '@core/game_master/gameMaster';
import { Util } from '@util';
import APP_SETTINGS from '@settings/app';
export class TypeMapper {
public static Map(rawType: ItemTemplate): Type {
let type: Type = new Type();
type.id = rawType.templateId;
type.name = Util.SnakeCase2HumanReadable(rawType.templateId.replace('POKEMON_TYPE_', ''));
type.damage = APP_SETTINGS.POKEMON_TYPES.map((pokemonType, index) => { return {
id: pokemonType.id,
attackScalar: rawType.typeEffective.attackScalar[pokemonType.attackScalarIndex]
}});
return type;
}
}
|
Add page size selector e2e test | ///<reference path="../node_modules/@types/jasmine/index.d.ts"/>
import { browser, element, by } from '../node_modules/protractor/built';
describe('page size selector', () =>{
let dataRowsCollection,
firstDataRow,
lastDataRow,
firstPageBtn,
nextPageBtn,
pageSizeSelector,
gridPager
beforeAll(()=>{
browser.get('/');
gridPager = element(by.tagName('grid-pager')).$('ngb-pagination').$('nav ul');
pageSizeSelector = element(by.tagName('page-size-selector')).$('form').$('div').$('select');
dataRowsCollection = element(by.tagName('tbody')).$$('tr');
firstDataRow = element(by.tagName('tbody')).$$('tr').first();
lastDataRow = element(by.tagName('tbody')).$$('tr').last();
firstPageBtn = gridPager.$$('li').first();
nextPageBtn = gridPager.$$('li');
});
it('should filter up to 10 data rows per page when selecting a page size of "10"', () => {
pageSizeSelector.$('[value="10"]').click();
expect(firstDataRow.$$('td').get(1).getText()).toMatch('1');
expect(lastDataRow.$$('td').get(1).getText()).toMatch('10');
expect(dataRowsCollection.count()).toBe(10);
});
it('should filter up to 20 data rows per page when selecting a page size of "20"', () => {
pageSizeSelector.$('[value="20"]').click();
nextPageBtn.get(5).$('a').click();
expect(firstDataRow.$$('td').get(1).getText()).toMatch('21');
expect(lastDataRow.$$('td').get(1).getText()).toMatch('40');
expect(dataRowsCollection.count()).toBe(20);
});
it('should filter up to 50 data rows per page when selecting a page size of "50"', () =>{
// Select '50' on tbPageSizeSelector
pageSizeSelector.$('[value="50"]').click();
// Verifying results on results-page 1
firstPageBtn.$('a').click();
expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
expect(lastDataRow.$$('td').get(1).getText()).toBe('50');
expect(dataRowsCollection.count()).toBe(50);
// Go to next page of results (page 2)
nextPageBtn.get(4).$('a').click();
// Verifying results on results-page 2
expect(firstDataRow.$$('td').get(1).getText()).toBe('51');
expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
expect(dataRowsCollection.count()).toBe(3);
});
it('should filter up to 100 data rows per page when selecting a page size of "100"', () => {
pageSizeSelector.$('[value="100"]').click();
expect(firstDataRow.$$('td').get(1).getText()).toBe('1');
expect(lastDataRow.$$('td').get(1).getText()).toBe('53');
expect(dataRowsCollection.count()).toBe(53);
});
}); | |
Test for dimensions service prepareTimeSteps | import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {HsDimensionService} from './dimension.service';
import {HsMapService} from '../components/map/map.service';
import {HsMapServiceMock} from '../components/map/map.service.mock';
import {HsUtilsService} from '../components/utils/utils.service';
import {HsUtilsServiceMock} from '../components/utils/utils.service.mock';
import {TestBed} from '@angular/core/testing';
describe('HsGetCapabilitiesModule', () => {
beforeAll(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
});
let service: HsDimensionService;
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [],
providers: [
HsDimensionService,
{provide: HsMapService, useValue: new HsMapServiceMock()},
{provide: HsUtilsService, useValue: new HsUtilsServiceMock()},
],
}); //.compileComponents();
service = TestBed.get(HsDimensionService);
});
it('prepareTimeSteps', () => {
const values = service.prepareTimeSteps(
'2016-03-16T12:00:00.000Z/2016-07-16T12:00:00.000Z/P30DT12H'
);
expect(values).toBeDefined();
expect(values).toEqual([
'2016-03-16T12:00:00.000Z',
'2016-04-16T00:00:00.000Z',
'2016-05-16T12:00:00.000Z',
'2016-06-16T00:00:00.000Z',
'2016-07-16T12:00:00.000Z',
]);
});
});
| |
Adjust size of section divider | import * as React from 'react';
import styled from 'styled-components';
import { Draggable, DragMode, Unregister } from 'core/interactions/handlers/draggable';
interface Props {
onDrag: (deltaY: number) => void;
}
export class SectionDivider extends React.Component<Props, {}> {
draggable = new Draggable({ mode: DragMode.absolute });
unregisterDragHandler: Unregister;
dividerRef: HTMLDivElement;
componentDidMount() {
const { draggable } = this;
draggable.onDrag(this.onDrag);
this.unregisterDragHandler = this.draggable.register(this.dividerRef!, this.dividerRef!);
}
componentWillUnmount() {
this.unregisterDragHandler();
}
onDrag = (deltaX: number, deltaY: number) => {
this.props.onDrag(deltaY);
};
render() {
return <Divider innerRef={ref => (this.dividerRef = ref)} />;
}
}
export default SectionDivider;
const Divider = styled.div`
width: 100%;
height: 10px;
background-color: black;
cursor: row-resize;
`;
| import * as React from 'react';
import styled from 'styled-components';
import { Draggable, DragMode, Unregister } from 'core/interactions/handlers/draggable';
interface Props {
onDrag: (deltaY: number) => void;
}
export class SectionDivider extends React.Component<Props, {}> {
draggable = new Draggable({ mode: DragMode.absolute });
unregisterDragHandler: Unregister;
dividerRef: HTMLDivElement;
componentDidMount() {
const { draggable } = this;
draggable.onDrag(this.onDrag);
this.unregisterDragHandler = this.draggable.register(this.dividerRef!, this.dividerRef!);
}
componentWillUnmount() {
this.unregisterDragHandler();
}
onDrag = (deltaX: number, deltaY: number) => {
this.props.onDrag(deltaY);
};
render() {
return <Divider innerRef={ref => (this.dividerRef = ref)} />;
}
}
export default SectionDivider;
const Divider = styled.div`
width: 100%;
height: 3px;
background-color: black;
cursor: row-resize;
`;
|
Add cd historical directories suggestions. | import {executable, sequence, decorate, string, noisySuggestions, runtime, choice} from "../../shell/Parser";
import {expandHistoricalDirectory} from "../../Command";
import {description, styles, style} from "./Suggestions";
import * as _ from "lodash";
import {relativeDirectoryPath} from "./File";
import {pathIn} from "./Common";
const historicalDirectory = runtime(async (context) =>
decorate(
choice(
_.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => decorate(string(alias), description(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack))))
),
style(styles.directory)
)
);
const cdpathDirectory = runtime(
async (context) => choice(context.environment.cdpath(context.directory).filter(directory => directory !== context.directory).map(directory =>
decorate(pathIn(directory, info => info.stat.isDirectory()), description(`In ${directory}`))))
);
export const cd = sequence(decorate(executable("cd"), description("Change the working directory")), choice([
noisySuggestions(historicalDirectory),
noisySuggestions(cdpathDirectory),
relativeDirectoryPath,
]));
| import {executable, sequence, decorate, string, noisySuggestions, runtime, choice} from "../../shell/Parser";
import {expandHistoricalDirectory} from "../../Command";
import {description, styles, style, Suggestion} from "./Suggestions";
import * as _ from "lodash";
import {relativeDirectoryPath} from "./File";
import {pathIn} from "./Common";
import {PluginManager} from "../../PluginManager";
const historicalDirectory = runtime(async (context) =>
decorate(
choice(
_.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => decorate(string(alias), description(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack))))
),
style(styles.directory)
)
);
const cdpathDirectory = runtime(
async (context) => choice(context.environment.cdpath(context.directory).filter(directory => directory !== context.directory).map(directory =>
decorate(pathIn(directory, info => info.stat.isDirectory()), description(`In ${directory}`))))
);
export const cd = sequence(decorate(executable("cd"), description("Change the working directory")), choice([
noisySuggestions(historicalDirectory),
noisySuggestions(cdpathDirectory),
relativeDirectoryPath,
]));
PluginManager.registerAutocompletionProvider("cd", async(context) => {
return _.take(["-", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9"], context.historicalCurrentDirectoriesStack.size)
.map(alias => new Suggestion().withValue(alias).withDescription(expandHistoricalDirectory(alias, context.historicalCurrentDirectoriesStack)).withStyle(styles.directory));
});
|
Check if multiple apps can be loaded | describe('Hslayers application', () => {
beforeEach(() => {
cy.visit('/multi-apps');
});
it('should display multiple hslayers elements', () => {
cy.get('hslayers').should('have.length', 2);
});
});
| |
Introduce input component specifically for IFQL function selection | import React, {SFC, ChangeEvent, KeyboardEvent} from 'react'
type OnFilterChangeHandler = (e: ChangeEvent<HTMLInputElement>) => void
type OnFilterKeyPress = (e: KeyboardEvent<HTMLInputElement>) => void
interface Props {
searchTerm: string
onFilterChange: OnFilterChangeHandler
onFilterKeyPress: OnFilterKeyPress
}
const FuncSelectorInput: SFC<Props> = ({
searchTerm,
onFilterChange,
onFilterKeyPress,
}) => (
<input
className="form-control input-sm ifql-func--input"
type="text"
autoFocus={true}
placeholder="Add Function..."
spellCheck={false}
onChange={onFilterChange}
onKeyDown={onFilterKeyPress}
value={searchTerm}
/>
)
export default FuncSelectorInput
| |
Add fourslash test for in scope completion | /// <reference path='fourslash.ts'/>
////function f() {
//// namespace n {
//// interface I {
//// x: number
//// }
//// /*1*/
//// }
//// /*2*/
////}
/////*3*/
goTo.marker('1');
verify.completionListContains("f", "function f(): void");
verify.completionListContains("n", "namespace n");
verify.completionListContains("I", "interface I");
goTo.marker('2');
verify.completionListContains("f", "function f(): void");
verify.completionListContains("n", "namespace n");
goTo.marker('3');
verify.completionListContains("f", "function f(): void"); | |
Add failing html escaping test | import { expect } from 'chai'
import Up from '../../../index'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
describe('All instances of "<" and "&" inside a plain text node', () => {
it('are replaced with "<" and "&", respectively', () => {
const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
})
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.