commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
---|---|---|---|---|---|---|---|---|---|---|
a705447917c2bc0e975fb77f5561d6fe999e0afc | src/model/role.model.ts | src/model/role.model.ts | export class Role {
name: string;
validationFunction: Function;
constructor(name: string, validationFunction: Function) {
this.name = name;
this.validationFunction = validationFunction;
}
} | export class Role {
name: string;
validationFunction: Function | string[];
constructor(name: string, validationFunction: Function | string[]) {
this.name = name;
this.validationFunction = validationFunction;
}
} | Update role to accept array | Update role to accept array
| TypeScript | mit | AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions,AlexKhymenko/ngx-permissions | ---
+++
@@ -1,8 +1,8 @@
export class Role {
name: string;
- validationFunction: Function;
+ validationFunction: Function | string[];
- constructor(name: string, validationFunction: Function) {
+ constructor(name: string, validationFunction: Function | string[]) {
this.name = name;
this.validationFunction = validationFunction;
} |
45d0fe23f17a5f608b5babfa77cdd45abfc14797 | types/types.test.ts | types/types.test.ts | // a smoke-test for our typescipt typings
import nlp from '../'
import nlpNumbers from '../plugins/numbers'
// Typings for imported plugin
type NLPNumbers = nlp.Plugin<
{
numbers: () => number[]
},
{
a: string
}
>
// vs Typed plugin
type NLPTest = nlp.Plugin<{ test: (text: string) => string }, { test: string }>
const test: NLPTest = (Doc, world) => {
Doc.test = text => text
world.test = 'Hello world!'
}
const nlpEx = nlp
// Give typing to untyped Plugin
.extend(nlpNumbers as NLPNumbers)
// Use typed plugin
.extend(test)
const doc = nlpEx('hello world')
doc.test('test')
doc.numbers()
type a3 = typeof doc.world.a
type b = typeof doc.world.test
// Demo: For external use
export type NLP = typeof nlpEx
// Standard still works
nlp('test')
nlp.tokenize('test')
nlp.version
| // a smoke-test for our typescipt typings
import nlp from '../'
import nlpNumbers from '../plugins/numbers'
// Typings for imported plugin
type NLPNumbers = nlp.Plugin<
{
numbers: () => number[]
},
{
a: string
}
>
// vs Typed plugin
type NLPTest = nlp.Plugin<{ test: (text: string) => string }, { test: string }>
const test: NLPTest = (Doc, world) => {
Doc.test = text => text
world.test = 'Hello world!'
}
const nlpEx = nlp
// Give typing to untyped Plugin
.extend(nlpNumbers as NLPNumbers)
// Use typed plugin
.extend(test)
const doc = nlpEx('hello world')
doc.test('test')
doc.numbers()
doc.world.a === typeof 'string'
doc.world.test === typeof 'string'
// Demo: For external use
export type NLP = typeof nlpEx
// Standard still works
nlp('test')
nlp.tokenize('test')
nlp.version
// Directly set nlp type
const doc2 = nlp<
{
numbers: () => number[]
},
{
a: string
}
>('test')
doc2.numbers()
doc2.world.a === typeof 'string'
| Test setting nlp type directly | Test setting nlp type directly
| TypeScript | mit | nlp-compromise/compromise,nlp-compromise/compromise,nlp-compromise/nlp_compromise,nlp-compromise/nlp_compromise,nlp-compromise/compromise | ---
+++
@@ -28,8 +28,8 @@
const doc = nlpEx('hello world')
doc.test('test')
doc.numbers()
-type a3 = typeof doc.world.a
-type b = typeof doc.world.test
+doc.world.a === typeof 'string'
+doc.world.test === typeof 'string'
// Demo: For external use
export type NLP = typeof nlpEx
@@ -38,3 +38,15 @@
nlp('test')
nlp.tokenize('test')
nlp.version
+
+// Directly set nlp type
+const doc2 = nlp<
+ {
+ numbers: () => number[]
+ },
+ {
+ a: string
+ }
+>('test')
+doc2.numbers()
+doc2.world.a === typeof 'string' |
b06b415dfdaf62dd2772863574a68a2e78def996 | src/components/Footer.tsx | src/components/Footer.tsx | 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(['<!doctype html>', html.documentElement.outerHTML], {
type: 'text/html'
});
chrome.downloads.download({
url: URL.createObjectURL(blob),
filename: 'playlist.html',
saveAs: true
});
}
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.contains({
permissions: ['downloads']
}, result => {
if (result) {
exportToHTML(tracks)
} else {
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(['<!doctype html>', html.documentElement.outerHTML], {
type: 'text/html'
});
chrome.downloads.download({
url: URL.createObjectURL(blob),
filename: 'playlist.html',
saveAs: true
});
}
export default Footer; | Check for download permission before requesting it. | Check for download permission before requesting it.
| TypeScript | mit | soflete/extereo,soflete/extereo | ---
+++
@@ -23,10 +23,18 @@
}
function allowDownload(tracks: Track[]) {
- chrome.permissions.request({
+ chrome.permissions.contains({
permissions: ['downloads']
- }, function (granted) {
- if (granted) exportToHTML(tracks);
+ }, result => {
+ if (result) {
+ exportToHTML(tracks)
+ } else {
+ chrome.permissions.request({
+ permissions: ['downloads']
+ }, function (granted) {
+ if (granted) exportToHTML(tracks)
+ });
+ }
});
}
|
3646288fb82016ed532b67aa458d5a4e3bd2b259 | frontend/projects/admin/src/app/interceptor/admin-error.http-interceptor.ts | frontend/projects/admin/src/app/interceptor/admin-error.http-interceptor.ts | import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Router } from '@angular/router';
import { EMPTY, Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class AdminErrorHttpInterceptor implements HttpInterceptor {
private errorCodes = [401, 403];
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.pipe(
catchError((error: HttpErrorResponse) => {
if (this.errorCodes.indexOf(error.status) !== -1) {
this.router.navigate(['/admin/login']);
return EMPTY;
}
return throwError(error);
})
);
}
}
| import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Router } from '@angular/router';
import { EMPTY, Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class AdminErrorHttpInterceptor implements HttpInterceptor {
private errorCodes = [401, 403];
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.pipe(
catchError((error: HttpErrorResponse) => {
if (this.errorCodes.includes(error.status)) {
this.router.navigate(['/admin/login']);
return EMPTY;
}
return throwError(error);
})
);
}
}
| Simplify status code check in array of status codes with includes | Simplify status code check in array of status codes with includes
| TypeScript | mit | drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild,drumonii/LeagueTrollBuild | ---
+++
@@ -16,7 +16,7 @@
return next.handle(req)
.pipe(
catchError((error: HttpErrorResponse) => {
- if (this.errorCodes.indexOf(error.status) !== -1) {
+ if (this.errorCodes.includes(error.status)) {
this.router.navigate(['/admin/login']);
return EMPTY;
} |
751e03760d66debc3863506fb2362a56ba55945b | src/docregistry/plugin.ts | src/docregistry/plugin.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JupyterLabPlugin
} from '../application';
import {
DocumentRegistry, IDocumentRegistry, TextModelFactory, Base64ModelFactory
} from './index';
/**
* The default document registry provider.
*/
export
const docRegistryProvider: JupyterLabPlugin<IDocumentRegistry> = {
id: 'jupyter.services.document-registry',
provides: IDocumentRegistry,
activate: (): IDocumentRegistry => {
let registry = new DocumentRegistry();
registry.addModelFactory(new TextModelFactory());
registry.addModelFactory(new Base64ModelFactory());
registry.addFileType({
name: 'Text',
extension: '.txt',
fileType: 'file',
fileFormat: 'text'
});
registry.addCreator({
name: 'Text File',
fileType: 'file',
});
return registry;
}
};
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
JupyterLabPlugin
} from '../application';
import {
DocumentRegistry, IDocumentRegistry, TextModelFactory, Base64ModelFactory
} from './index';
/**
* The default document registry provider.
*/
export
const docRegistryProvider: JupyterLabPlugin<IDocumentRegistry> = {
id: 'jupyter.services.document-registry',
provides: IDocumentRegistry,
activate: (): IDocumentRegistry => {
let registry = new DocumentRegistry();
registry.addModelFactory(new TextModelFactory());
registry.addModelFactory(new Base64ModelFactory());
registry.addFileType({
name: 'Text',
extension: '.txt',
fileType: 'file',
fileFormat: 'text'
});
registry.addCreator({
name: 'Text File',
fileType: 'Text',
});
return registry;
}
};
| Fix the text file creator | Fix the text file creator
| TypeScript | bsd-3-clause | eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab | ---
+++
@@ -29,7 +29,7 @@
});
registry.addCreator({
name: 'Text File',
- fileType: 'file',
+ fileType: 'Text',
});
return registry;
} |
6d62ca430ee04dabff2e08b10d7195372bb94b7f | src/server.ts | src/server.ts | import {Bootstrapper} from "typescript-mvc-web-api";
class Server extends Bootstrapper {
public execute(): void {
/*
/api/odata/*
/api/sparql/*
let routes = [
new Route('/', { controller: 'Home', action: 'index' }),
new Route('/', { controller: 'Home', action: 'index' }),
];
*/
let url = this.context.settings.protocol
+ "://" + this.context.settings.hostname
+ ":" + this.context.settings.port
+ this.context.settings.root;
this.context.logger.log("Server running at", url);
this.context.framework.startWebServer(this.context.settings.port, this.context.settings.hostname);
}
}
let server = new Server();
server.initialize();
| import {WebServer} from "typescript-mvc-web-api";
class Server extends WebServer {
public execute(): void {
/*
/api/odata/*
/api/sparql/*
let routes = [
new Route('/', { controller: 'Home', action: 'index' }),
new Route('/', { controller: 'Home', action: 'index' }),
];
*/
let url = this.context.settings.protocol
+ "://" + this.context.settings.hostname
+ ":" + this.context.settings.port
+ this.context.settings.root;
this.context.logger.log("Server running at", url);
this.context.framework.startWebServer(this.context.settings.port, this.context.settings.hostname);
}
}
let server = new Server();
server.initialize();
| Use WebServer instead of Bootstrapper | Use WebServer instead of Bootstrapper
| TypeScript | mit | disco-network/disco-node,disco-network/disco-node | ---
+++
@@ -1,6 +1,6 @@
-import {Bootstrapper} from "typescript-mvc-web-api";
+import {WebServer} from "typescript-mvc-web-api";
-class Server extends Bootstrapper {
+class Server extends WebServer {
public execute(): void {
/* |
26b54ece5a39eb2b886829976ad663732a30a4de | desktop/app/src/fb-stubs/IDEFileResolver.tsx | desktop/app/src/fb-stubs/IDEFileResolver.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export enum IDEType {
'DIFFUSION',
'AS',
'VSCODE',
'XCODE',
}
export abstract class IDEFileResolver {
static async resolveFullPathsFromMyles(
_fileName: string,
_dirRoot: string,
): Promise<string[]> {
throw new Error('Method not implemented.');
}
static openInIDE(
_filePath: string,
_ide: IDEType,
_repo: string,
_lineNumber = 0,
) {
throw new Error('Method not implemented.');
}
static getBestPath(
_paths: string[],
_className: string,
_extension?: string,
): string {
throw new Error('Method not implemented.');
}
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
export enum IDEType {
'DIFFUSION',
'AS',
'VSCODE',
'XCODE',
}
export abstract class IDEFileResolver {
static async resolveFullPathsFromMyles(
_fileName: string,
_dirRoot: string,
): Promise<string[]> {
throw new Error('Method not implemented.');
}
static openInIDE(
_filePath: string,
_ide: IDEType,
_repo: string,
_lineNumber = 0,
) {
throw new Error('Method not implemented.');
}
static async getLithoComponentPath(_className: string): Promise<string> {
throw new Error('Method not implemented.');
}
static getBestPath(
_paths: string[],
_className: string,
_extension?: string,
): string {
throw new Error('Method not implemented.');
}
}
| Add functionality to resolve Litho Components / Sections | Add functionality to resolve Litho Components / Sections
Summary:
Few cases to consider:
- SomeComponent.* might correspond to SomeComponentSpec.java
- SomeComponent.* might correspond to SomeComponentSpec.kt
- SomeComponent.* might not have a corresponding Spec file
- SomeComponent.kt (if it's a KComponent) corresponds to SomeComponent.kt
Reviewed By: adityasharat
Differential Revision: D23100032
fbshipit-source-id: f0604f3d1061f0e15fa2f455bdddd4d07ac12305
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -31,6 +31,10 @@
throw new Error('Method not implemented.');
}
+ static async getLithoComponentPath(_className: string): Promise<string> {
+ throw new Error('Method not implemented.');
+ }
+
static getBestPath(
_paths: string[],
_className: string, |
ae86ee1fba60200fa0ac747411911f0d574667dd | src/build-file.ts | src/build-file.ts | import runGitCommand from './helpers/run-git-command'
import { Compiler } from 'webpack'
interface BuildFileOptions {
compiler: Compiler
gitWorkTree?: string
command: string
replacePattern: RegExp
asset: string
}
export default function buildFile({ compiler, gitWorkTree, command, replacePattern, asset }: BuildFileOptions) {
let data: string = ''
compiler.hooks.compilation.tap('GitRevisionWebpackPlugin', compilation => {
compilation.hooks.optimizeTree.tapAsync('optimize-tree', (_, __, callback) => {
runGitCommand(gitWorkTree, command, function(err, res) {
if (err) {
return callback(err)
}
data = res
callback()
})
})
compilation.hooks.assetPath.tap('GitRevisionWebpackPlugin', (assetPath: any, chunkData: any) => {
const path = typeof assetPath === 'function' ? assetPath(chunkData) : assetPath
if (!data) return path
return path.replace(replacePattern, data)
})
})
compiler.hooks.emit.tap('GitRevisionWebpackPlugin', compilation => {
compilation.assets[asset] = {
source: function() {
return data
},
size: function() {
return data ? data.length : 0
},
buffer: function() {
return Buffer.from(data)
},
map: function() {
return {}
},
sourceAndMap: function() {
return { source: data, map: {} }
},
updateHash: function() {},
}
})
}
| import runGitCommand from './helpers/run-git-command'
import { Compiler } from 'webpack'
interface BuildFileOptions {
compiler: Compiler
gitWorkTree?: string
command: string
replacePattern: RegExp
asset: string
}
export default function buildFile({ compiler, gitWorkTree, command, replacePattern, asset }: BuildFileOptions) {
let data: string = ''
compiler.hooks.compilation.tap('GitRevisionWebpackPlugin', compilation => {
compilation.hooks.optimizeTree.tapAsync('optimize-tree', (_, __, callback) => {
runGitCommand(gitWorkTree, command, function(err, res) {
if (err) {
return callback(err)
}
data = res
callback()
})
})
compilation.hooks.assetPath.tap('GitRevisionWebpackPlugin', (assetPath: any, chunkData: any) => {
const path = typeof assetPath === 'function' ? assetPath(chunkData) : assetPath
if (!data) return path
return path.replace(replacePattern, data)
})
compilation.hooks.processAssets.tap('GitRevisionWebpackPlugin', assets => {
assets[asset] = {
source: function() {
return data
},
size: function() {
return data ? data.length : 0
},
buffer: function() {
return Buffer.from(data)
},
map: function() {
return {}
},
sourceAndMap: function() {
return { source: data, map: {} }
},
updateHash: function() {},
}
})
})
}
| Fix “BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.” 🙈 | Fix “BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.” 🙈 | TypeScript | mit | pirelenito/git-revision-webpack-plugin,pirelenito/git-revision-webpack-plugin,pirelenito/git-revision-webpack-plugin | ---
+++
@@ -30,26 +30,26 @@
if (!data) return path
return path.replace(replacePattern, data)
})
- })
- compiler.hooks.emit.tap('GitRevisionWebpackPlugin', compilation => {
- compilation.assets[asset] = {
- source: function() {
- return data
- },
- size: function() {
- return data ? data.length : 0
- },
- buffer: function() {
- return Buffer.from(data)
- },
- map: function() {
- return {}
- },
- sourceAndMap: function() {
- return { source: data, map: {} }
- },
- updateHash: function() {},
- }
+ compilation.hooks.processAssets.tap('GitRevisionWebpackPlugin', assets => {
+ assets[asset] = {
+ source: function() {
+ return data
+ },
+ size: function() {
+ return data ? data.length : 0
+ },
+ buffer: function() {
+ return Buffer.from(data)
+ },
+ map: function() {
+ return {}
+ },
+ sourceAndMap: function() {
+ return { source: data, map: {} }
+ },
+ updateHash: function() {},
+ }
+ })
})
} |
c108a252cd11ba65d86f68d731f50bdade9ec583 | applications/mail/src/app/App.tsx | applications/mail/src/app/App.tsx | import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, StandardSetup } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
import locales from 'proton-shared/lib/i18n/locales';
import * as config from './config';
import PrivateApp from './PrivateApp';
import './app.scss';
sentry(config);
const App = () => {
return (
<ProtonApp config={config}>
<StandardSetup PrivateApp={PrivateApp} locales={locales} />
</ProtonApp>
);
};
export default hot(App);
| import React from 'react';
import { ProtonApp, StandardSetup } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
import locales from 'proton-shared/lib/i18n/locales';
import * as config from './config';
import PrivateApp from './PrivateApp';
import './app.scss';
sentry(config);
const App = () => {
return (
<ProtonApp config={config}>
<StandardSetup PrivateApp={PrivateApp} locales={locales} />
</ProtonApp>
);
};
export default App;
| Use fast-refresh instead of hot-loader | Use fast-refresh instead of hot-loader
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,4 +1,3 @@
-import { hot } from 'react-hot-loader/root';
import React from 'react';
import { ProtonApp, StandardSetup } from 'react-components';
import sentry from 'proton-shared/lib/helpers/sentry';
@@ -19,4 +18,4 @@
);
};
-export default hot(App);
+export default App; |
58ae0520c07570ddb43ad43fc69f89b611c23a90 | app/angular/src/server/options.ts | app/angular/src/server/options.ts | import packageJson from '../../package.json';
export default {
packageJson,
frameworkPresets: [
require.resolve('./framework-preset-angular.js'),
require.resolve('./framework-preset-angular-cli.js'),
],
};
| // tslint:disable-next-line: no-var-requires
const packageJson = require('../../package.json');
export default {
packageJson,
frameworkPresets: [
require.resolve('./framework-preset-angular.js'),
require.resolve('./framework-preset-angular-cli.js'),
],
};
| Use require instead of import | Use require instead of import
tsc wants all imports to be under rootDir
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -1,4 +1,5 @@
-import packageJson from '../../package.json';
+// tslint:disable-next-line: no-var-requires
+const packageJson = require('../../package.json');
export default {
packageJson, |
4308d86fbc99e28eaff7d676c44a18d1c823be6d | types/components/CollapsibleItem.d.ts | types/components/CollapsibleItem.d.ts | import * as React from "react";
import { SharedBasic } from "./utils";
export interface CollapsibleItemProps extends SharedBasic {
expanded?: boolean;
node?: React.ReactNode;
header: any;
icon?: React.ReactNode;
iconClassName?: string;
onSelect?: (key: number) => any;
eventKey?: any;
}
/**
* React Materialize: CollapsibleItem
*/
declare const CollapsibleItem: React.FC<CollapsibleItemProps>;
export default CollapsibleItem;
| import * as React from "react";
import { SharedBasic } from "./utils";
export interface CollapsibleItemProps extends SharedBasic {
expanded?: boolean;
node?: React.ReactNode;
header: any;
icon?: React.ReactNode;
iconClassName?: string;
onSelect: (eventKey: any) => any;
eventKey?: any;
}
/**
* React Materialize: CollapsibleItem
*/
declare const CollapsibleItem: React.FC<CollapsibleItemProps>;
export default CollapsibleItem;
| Make onSelect for CollapsibleItem props | Make onSelect for CollapsibleItem props
onSelect always called from CollapsibleItem
| TypeScript | mit | react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize | ---
+++
@@ -7,7 +7,7 @@
header: any;
icon?: React.ReactNode;
iconClassName?: string;
- onSelect?: (key: number) => any;
+ onSelect: (eventKey: any) => any;
eventKey?: any;
}
|
9faf1b1fb395e3d89b63a9e8ddbc418df0bfbb32 | client/Player/PlayerSuggestion.ts | client/Player/PlayerSuggestion.ts | module ImprovedInitiative {
export class PlayerSuggestion {
constructor(
public Socket: SocketIOClient.Socket,
public EncounterId: string
) {}
SuggestionVisible = ko.observable(false);
Combatant: KnockoutObservable<StaticCombatantViewModel> = ko.observable();
Name = ko.pureComputed(() => {
if (!this.Combatant()) {
return "";
} else {
return this.Combatant().Name;
}
})
Show = (combatant: StaticCombatantViewModel) => {
this.Combatant(combatant);
this.SuggestionVisible(true);
$("input[name=suggestedDamage]").first().select();
}
Resolve = (form: HTMLFormElement) => {
const value = $(form).find("[name=suggestedDamage]").first().val();
console.log(this.Combatant().Name);
this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], parseInt(value, 10), "Player");
this.Close();
}
Close = () => {
this.SuggestionVisible(false);
}
}
} | module ImprovedInitiative {
export class PlayerSuggestion {
constructor(
public Socket: SocketIOClient.Socket,
public EncounterId: string
) {}
SuggestionVisible = ko.observable(false);
Combatant: KnockoutObservable<StaticCombatantViewModel> = ko.observable();
Name = ko.pureComputed(() => {
if (!this.Combatant()) {
return "";
} else {
return this.Combatant().Name;
}
})
Show = (combatant: StaticCombatantViewModel) => {
this.Combatant(combatant);
this.SuggestionVisible(true);
$("input[name=suggestedDamage]").first().focus();
}
Resolve = (form: HTMLFormElement) => {
const element = $(form).find("[name=suggestedDamage]").first();
const value = parseInt(element.val(), 10);
if (!isNaN(value) && value !== 0) {
this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], value, "Player");
}
element.val("");
this.Close();
}
Close = () => {
this.SuggestionVisible(false);
}
}
} | Remove debug log and fix blank suggestions bug | Remove debug log and fix blank suggestions bug
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -19,13 +19,16 @@
Show = (combatant: StaticCombatantViewModel) => {
this.Combatant(combatant);
this.SuggestionVisible(true);
- $("input[name=suggestedDamage]").first().select();
+ $("input[name=suggestedDamage]").first().focus();
}
Resolve = (form: HTMLFormElement) => {
- const value = $(form).find("[name=suggestedDamage]").first().val();
- console.log(this.Combatant().Name);
- this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], parseInt(value, 10), "Player");
+ const element = $(form).find("[name=suggestedDamage]").first();
+ const value = parseInt(element.val(), 10);
+ if (!isNaN(value) && value !== 0) {
+ this.Socket.emit("suggest damage", this.EncounterId, [this.Combatant().Id], value, "Player");
+ }
+ element.val("");
this.Close();
}
|
8ac0252be0f1c16d98c18fa9471be093f5d99704 | src/components/TransitionSwitch/TransitionSwitch.tsx | src/components/TransitionSwitch/TransitionSwitch.tsx | import * as React from "react";
import {Route} from "react-router-dom";
import * as TransitionGroup from "react-transition-group/TransitionGroup";
import * as CSSTransition from "react-transition-group/CSSTransition";
import {TransitionSwitchProps, TransitionSwitchPropTypes, TransitionSwitchDefaultProps} from "./TransitionSwitchProps";
export class TransitionSwitch extends React.Component<TransitionSwitchProps, undefined> {
public static propTypes = TransitionSwitchPropTypes;
public static defaultProps = TransitionSwitchDefaultProps;
protected get routeProps(): object {
return Object.keys(this.props.children)
.map((field) => this.props.children[field].props)
.find(({path}) => path === this.props.history.location.pathname);
}
public render(): JSX.Element {
const {history: {location}, ...props} = this.props;
const transitionProps: CSSTransition.CSSTransitionProps = {
...props,
...{
key: location.pathname.split("/")[1],
}
} as any;
const currentRouteProps = {
...this.routeProps,
...{
location,
}
};
return (
<TransitionGroup className={this.props.className}>
<CSSTransition {...transitionProps}>
<Route {...currentRouteProps}/>
</CSSTransition>
</TransitionGroup>
);
}
}
| import * as React from "react";
import {Route} from "react-router-dom";
import {TransitionGroup, CSSTransition} from "react-transition-group";
import {TransitionSwitchProps, TransitionSwitchPropTypes, TransitionSwitchDefaultProps} from "./TransitionSwitchProps";
export class TransitionSwitch extends React.Component<TransitionSwitchProps, undefined> {
public static propTypes = TransitionSwitchPropTypes;
public static defaultProps = TransitionSwitchDefaultProps;
protected get routeProps(): object {
return Object.keys(this.props.children)
.map((field) => this.props.children[field].props)
.find(({path}) => path === this.props.history.location.pathname);
}
public render(): JSX.Element {
const {history: {location}, ...props} = this.props;
const transitionProps: any = {
...props,
...{
key: location.pathname.split("/")[1],
}
} as any;
const currentRouteProps = {
...this.routeProps,
...{
location,
}
};
return (
<TransitionGroup className={this.props.className}>
<CSSTransition {...transitionProps}>
<Route {...currentRouteProps}/>
</CSSTransition>
</TransitionGroup>
);
}
}
| Remove type definition for react-transition-group | Remove type definition for react-transition-group
| TypeScript | mit | wearesho-team/wearesho-site,wearesho-team/wearesho-site,wearesho-team/wearesho-site | ---
+++
@@ -1,8 +1,7 @@
import * as React from "react";
import {Route} from "react-router-dom";
-import * as TransitionGroup from "react-transition-group/TransitionGroup";
-import * as CSSTransition from "react-transition-group/CSSTransition";
+import {TransitionGroup, CSSTransition} from "react-transition-group";
import {TransitionSwitchProps, TransitionSwitchPropTypes, TransitionSwitchDefaultProps} from "./TransitionSwitchProps";
@@ -20,7 +19,7 @@
public render(): JSX.Element {
const {history: {location}, ...props} = this.props;
- const transitionProps: CSSTransition.CSSTransitionProps = {
+ const transitionProps: any = {
...props,
...{
key: location.pathname.split("/")[1], |
8ac5136ef9ad9ecda07a313b8dc21dc215b923b6 | src/assets.ts | src/assets.ts | interface IAsset {
Key: string
GetPath(): string
}
export namespace Images {
export const Logo: IAsset = {
Key: "logo",
GetPath(): string { return require('assets/logo.png') }
}
} | interface IImageAsset {
Key: string
GetPath: () => string
}
interface ISoundAsset {
Key: string
Format: {
MP3?: () => string
OGG?: () => string
WAV?: () => string
}
}
export namespace Images {
export const Logo: IImageAsset = {
Key: "logo",
GetPath: (): string => { return require('assets/logo.png') }
}
} | Add ISoundAsset. Rename IAsset to IImageAsset. Update coding style. | Add ISoundAsset. Rename IAsset to IImageAsset. Update coding style.
| TypeScript | mit | dmk2014/phaser-template,dmk2014/phaser-template,dmk2014/phaser-template | ---
+++
@@ -1,13 +1,22 @@
-interface IAsset {
+interface IImageAsset {
Key: string
- GetPath(): string
+ GetPath: () => string
+}
+
+interface ISoundAsset {
+ Key: string
+ Format: {
+ MP3?: () => string
+ OGG?: () => string
+ WAV?: () => string
+ }
}
export namespace Images {
- export const Logo: IAsset = {
+ export const Logo: IImageAsset = {
Key: "logo",
- GetPath(): string { return require('assets/logo.png') }
+ GetPath: (): string => { return require('assets/logo.png') }
}
} |
edc3e5cceb05d8ef1e430d540d39abc9926d2f5e | tool/common.ts | tool/common.ts | import * as gulp from 'gulp';
import * as gulpif from 'gulp-if';
import * as sourcemaps from 'gulp-sourcemaps';
import * as typescript from 'gulp-typescript';
export const DIR_TMP = '.tmp';
export const DIR_DST = 'dist';
export const DIR_SRC = 'src';
/**
* The `project` is used inside the "ts" task to compile TypeScript code using
* tsconfig.json file. The project MUST be created outside of the task to
* enable incremental compilation.
*/
const project = typescript.createProject('tsconfig.json', {
/**
* We don't use any kind of modules or <reference> tags in our project, so we
* don't need to support external modules resolving. According to the
* gulp-typescript plugin docs explicitly disabling it can improve
* compilation time.
*/
noExternalResolve: true
});
export function typescriptTask(enableSourcemaps: boolean = false) {
let files = [`${DIR_SRC}/**/*.ts`, 'typings/browser/**/*.d.ts'];
return gulp.src(files, {base: DIR_SRC})
.pipe(gulpif(enableSourcemaps, sourcemaps.init()))
.pipe(typescript(project))
.pipe(gulpif(enableSourcemaps, sourcemaps.write()))
.pipe(gulp.dest(DIR_TMP));
}
export function copyHtmlTask() {
return gulp.src(`${DIR_SRC}/**/*.html`, {base: DIR_SRC})
.pipe(gulp.dest(DIR_TMP));
}
| import * as gulp from 'gulp';
import * as gulpif from 'gulp-if';
import * as sourcemaps from 'gulp-sourcemaps';
import * as typescript from 'gulp-typescript';
export const DIR_TMP = '.tmp';
export const DIR_DST = 'dist';
export const DIR_SRC = 'src';
/**
* The `project` is used inside the "ts" task to compile TypeScript code using
* tsconfig.json file. The project MUST be created outside of the task to
* enable incremental compilation.
*/
const project = typescript.createProject('tsconfig.json', {
/**
* We don't use any kind of modules or <reference> tags in our project, so we
* don't need to support external modules resolving. According to the
* gulp-typescript plugin docs explicitly disabling it can improve
* compilation time.
*/
noExternalResolve: true
});
/**
* Compiles all TypeScript code in the project to JavaScript.
*
* @param enableSourcemaps Pass `true` to enable source maps generation
*/
export function typescriptTask(enableSourcemaps: boolean = false) {
let files = [`${DIR_SRC}/**/*.ts`, 'typings/browser/**/*.d.ts'];
return gulp.src(files, {base: DIR_SRC})
.pipe(gulpif(enableSourcemaps, sourcemaps.init()))
.pipe(typescript(project))
.pipe(gulpif(enableSourcemaps, sourcemaps.write()))
.pipe(gulp.dest(DIR_TMP));
}
export function copyHtmlTask() {
return gulp.src(`${DIR_SRC}/**/*.html`, {base: DIR_SRC})
.pipe(gulp.dest(DIR_TMP));
}
| Add docs for the typescript task | Add docs for the typescript task
| TypeScript | mit | Farata/polymer-typescript-starter,Farata/polymer-typescript-starter | ---
+++
@@ -22,6 +22,11 @@
noExternalResolve: true
});
+/**
+ * Compiles all TypeScript code in the project to JavaScript.
+ *
+ * @param enableSourcemaps Pass `true` to enable source maps generation
+ */
export function typescriptTask(enableSourcemaps: boolean = false) {
let files = [`${DIR_SRC}/**/*.ts`, 'typings/browser/**/*.d.ts'];
return gulp.src(files, {base: DIR_SRC}) |
2066dc128ad36c2b959d44f7947072c6be225719 | src/styles/themes/index.ts | src/styles/themes/index.ts | export interface Palette {
primary1Color: string,
primary2Color: string,
primary3Color: string,
accent1Color: string,
accent2Color: string,
accent3Color: string,
textColor: string,
secondaryTextColor: string,
alternateTextColor: string,
canvasColor: string,
borderColor: string,
disabledColor: string,
pickerHeaderColor: string,
clockCircleColor: string,
shadowColor?: string
}
export interface Theme {
fontFamily: string;
palette: Palette;
}
| import theme from './light';
export interface Palette {
primary1Color: string,
primary2Color: string,
primary3Color: string,
accent1Color: string,
accent2Color: string,
accent3Color: string,
textColor: string,
secondaryTextColor: string,
alternateTextColor: string,
canvasColor: string,
borderColor: string,
disabledColor: string,
pickerHeaderColor: string,
clockCircleColor: string,
shadowColor?: string
}
export interface Theme {
fontFamily: string;
palette: Palette;
}
export const defaultTheme = theme;
| Add default theme to exports | Add default theme to exports
| TypeScript | mit | cyclic-ui/cyclic-ui,cyclic-ui/cyclic-ui | ---
+++
@@ -1,3 +1,5 @@
+import theme from './light';
+
export interface Palette {
primary1Color: string,
primary2Color: string,
@@ -20,3 +22,5 @@
fontFamily: string;
palette: Palette;
}
+
+export const defaultTheme = theme; |
9f71423903626e7d300f601a4ee1205e541ee261 | app/src/ui/repository-settings/git-ignore.tsx | app/src/ui/repository-settings/git-ignore.tsx | import * as React from 'react'
import { DialogContent } from '../dialog'
import { TextArea } from '../lib/text-area'
import { LinkButton } from '../lib/link-button'
interface IGitIgnoreProps {
readonly text: string | null
readonly onIgnoreTextChanged: (text: string) => void
readonly onShowExamples: () => void
}
/** A view for creating or modifying the repository's gitignore file */
export class GitIgnore extends React.Component<IGitIgnoreProps, void> {
public render() {
return (
<DialogContent>
<p>
The .gitignore file controls which files are tracked by Git and which
are ignored. Check out <LinkButton onClick={this.props.onShowExamples}>git-scm.com</LinkButton> for
more information about the file format, or simply ignore a file by
right clicking on it in the uncommitted changes view.
</p>
<TextArea
placeholder='Ignored files'
value={this.props.text || ''}
onChange={this.onChange}
rows={6} />
</DialogContent>
)
}
private onChange = (event: React.FormEvent<HTMLTextAreaElement>) => {
const text = event.currentTarget.value
this.props.onIgnoreTextChanged(text)
}
}
| import * as React from 'react'
import { DialogContent } from '../dialog'
import { TextArea } from '../lib/text-area'
import { LinkButton } from '../lib/link-button'
interface IGitIgnoreProps {
readonly text: string | null
readonly onIgnoreTextChanged: (text: string) => void
readonly onShowExamples: () => void
}
/** A view for creating or modifying the repository's gitignore file */
export class GitIgnore extends React.Component<IGitIgnoreProps, void> {
public render() {
return (
<DialogContent>
<p>
The .gitignore file controls which files are tracked by Git and which
are ignored. Check out <LinkButton onClick={this.props.onShowExamples}>git-scm.com</LinkButton> for
more information about the file format, or simply ignore a file by
right clicking on it in the uncommitted changes view.
</p>
<TextArea
placeholder='Ignored files'
value={this.props.text || ''}
onValueChanged={this.props.onIgnoreTextChanged}
rows={6} />
</DialogContent>
)
}
}
| Use <TextArea onValueChanged /> in <GitIgnore /> | Use <TextArea onValueChanged /> in <GitIgnore />
| TypeScript | mit | artivilla/desktop,gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,hjobrien/desktop,desktop/desktop,say25/desktop,desktop/desktop,artivilla/desktop,hjobrien/desktop,hjobrien/desktop,gengjiawen/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,desktop/desktop,gengjiawen/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop | ---
+++
@@ -25,14 +25,9 @@
<TextArea
placeholder='Ignored files'
value={this.props.text || ''}
- onChange={this.onChange}
+ onValueChanged={this.props.onIgnoreTextChanged}
rows={6} />
</DialogContent>
)
}
-
- private onChange = (event: React.FormEvent<HTMLTextAreaElement>) => {
- const text = event.currentTarget.value
- this.props.onIgnoreTextChanged(text)
- }
} |
d282fef5a099cf8beb4b1fc0df6776e44b823852 | packages/remark/types/index.d.ts | packages/remark/types/index.d.ts | // TypeScript Version: 3.0
import unified = require('unified')
import remarkParse = require('remark-parse')
import remarkStringify = require('remark-stringify')
type RemarkOptions = remarkParse.RemarkParseOptions &
remarkStringify.RemarkStringifyOptions
declare function remark<
P extends Partial<RemarkOptions> = Partial<RemarkOptions>
>(): unified.Processor<P>
export = remark
| // TypeScript Version: 3.0
import unified = require('unified')
import remarkParse = require('remark-parse')
import remarkStringify = require('remark-stringify')
declare namespace remark {
type RemarkOptions = remarkParse.RemarkParseOptions &
remarkStringify.RemarkStringifyOptions
}
declare function remark<
P extends Partial<remark.RemarkOptions> = Partial<remark.RemarkOptions>
>(): unified.Processor<P>
export = remark
| Fix export of remark options type | Fix export of remark options type
Related to electron/hubdown#19.
Closes GH-432.
Reviewed-by: Zeke Sikelianos <[email protected]>
Reviewed-by: Vlad Hashimoto <[email protected]>
Reviewed-by: Titus Wormer <[email protected]> | TypeScript | mit | wooorm/remark | ---
+++
@@ -4,11 +4,13 @@
import remarkParse = require('remark-parse')
import remarkStringify = require('remark-stringify')
-type RemarkOptions = remarkParse.RemarkParseOptions &
- remarkStringify.RemarkStringifyOptions
+declare namespace remark {
+ type RemarkOptions = remarkParse.RemarkParseOptions &
+ remarkStringify.RemarkStringifyOptions
+}
declare function remark<
- P extends Partial<RemarkOptions> = Partial<RemarkOptions>
+ P extends Partial<remark.RemarkOptions> = Partial<remark.RemarkOptions>
>(): unified.Processor<P>
export = remark |
2c245cc44070e54a71a45ae3f180b1a9002615dd | app/components/button.ts | app/components/button.ts | import React = require('react')
import chroma = require('chroma-js')
import { create } from 'react-free-style'
import { GREEN_SEA } from '../utils/colors'
const Style = create()
const BUTTON_STYLE = Style.registerStyle({
padding: '0.6em 1.125em',
fontSize: '1.1em',
color: '#fff',
borderRadius: '3px',
backgroundColor: GREEN_SEA,
border: '1px solid transparent',
transition: 'border .25s linear, color .25s linear, background-color .25s linear',
display: 'block',
whiteSpace: 'nowrap'
})
const BUTTON_ACTIVE_STYLE = Style.registerStyle({
cursor: 'pointer',
'&:hover': {
backgroundColor: chroma(GREEN_SEA).brighter(5).hex()
}
})
interface ButtonProps {
children: any
className: string
disabled: boolean
}
class Button extends React.Component<ButtonProps, {}> {
render () {
return React.createElement(
'div',
{
className: Style.join(this.props.className, BUTTON_STYLE.className, this.props.disabled ? null : BUTTON_ACTIVE_STYLE.className)
},
this.props.children
)
}
}
export default Style.component(Button)
| import React = require('react')
import chroma = require('chroma-js')
import { create } from 'react-free-style'
import { GREEN_SEA } from '../utils/colors'
const Style = create()
const BUTTON_STYLE = Style.registerStyle({
padding: '0.6em 1.125em',
fontSize: '1.1em',
color: '#fff',
borderRadius: '3px',
backgroundColor: GREEN_SEA,
border: '1px solid transparent',
transition: 'border .25s linear, color .25s linear, background-color .25s linear',
display: 'block',
whiteSpace: 'nowrap'
})
const BUTTON_ACTIVE_STYLE = Style.registerStyle({
cursor: 'pointer',
'&:hover': {
backgroundColor: chroma(GREEN_SEA).brighter(0.5).hex()
}
})
interface ButtonProps {
children: any
className: string
disabled: boolean
}
class Button extends React.Component<ButtonProps, {}> {
render () {
return React.createElement(
'div',
{
className: Style.join(this.props.className, BUTTON_STYLE.className, this.props.disabled ? null : BUTTON_ACTIVE_STYLE.className)
},
this.props.children
)
}
}
export default Style.component(Button)
| Use decimal for chroma brighten | Use decimal for chroma brighten
| TypeScript | mit | blakeembrey/back-row,blakeembrey/back-row,blakeembrey/back-row | ---
+++
@@ -21,7 +21,7 @@
cursor: 'pointer',
'&:hover': {
- backgroundColor: chroma(GREEN_SEA).brighter(5).hex()
+ backgroundColor: chroma(GREEN_SEA).brighter(0.5).hex()
}
})
|
a884d5fdf4cdcbfb2c451647bca546d79d6f1e55 | src/koa/utils.ts | src/koa/utils.ts | /**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/
export function compose(middleware: Function[]) {
if (!Array.isArray(middleware))
throw new TypeError('Middleware stack must be an array!');
for (const fn of middleware) {
if (typeof fn !== 'function')
throw new TypeError('Middleware must be composed of functions!');
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function(context: any, next: Function) {
// last called middleware #
let index = -1;
return dispatch.call(this, 0);
function dispatch(i: number) {
if (i <= index)
return Promise.reject(new Error('next() called multiple times'));
index = i;
let fn = middleware[i];
if (i === middleware.length) fn = next;
if (!fn) return Promise.resolve();
try {
return Promise.resolve(
fn.call(this, context, dispatch.bind(this, i + 1)),
);
} catch (err) {
return Promise.reject(err);
}
}
};
}
| import * as _ from 'underscore';
import debug from 'debug';
const d = debug('sbase:utils');
/**
* Compose `middleware` returning a fully valid middleware comprised of all
* those which are passed.
*/
export function compose(middleware: Function[]) {
if (!Array.isArray(middleware)) {
throw new TypeError('Middleware stack must be an array!');
}
for (const fn of middleware) {
if (typeof fn !== 'function') {
throw new TypeError('Middleware must be composed of functions!');
}
}
/**
* @param {Object} context
* @return {Promise}
* @api public
*/
return function(context: any, next: Function) {
// last called middleware #
let index = -1;
return dispatch.call(this, 0);
function dispatch(i: number) {
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'));
}
index = i;
const fn = i === middleware.length ? next : middleware[i];
if (!fn) return Promise.resolve();
const start = _.now();
try {
d('Begin of fn %O', fn.name);
return Promise.resolve(
fn.call(this, context, dispatch.bind(this, i + 1)),
);
} catch (err) {
return Promise.reject(err);
} finally {
const end = _.now();
d('End of fn %O, duration: %O', fn.name, end - start);
}
}
};
}
| Add debugging message to middlewares. | Add debugging message to middlewares.
| TypeScript | apache-2.0 | nodeswork/sbase,nodeswork/sbase | ---
+++
@@ -1,19 +1,21 @@
+import * as _ from 'underscore';
+import debug from 'debug';
+
+const d = debug('sbase:utils');
+
/**
- * Compose `middleware` returning
- * a fully valid middleware comprised
- * of all those which are passed.
- *
- * @param {Array} middleware
- * @return {Function}
- * @api public
+ * Compose `middleware` returning a fully valid middleware comprised of all
+ * those which are passed.
*/
+export function compose(middleware: Function[]) {
+ if (!Array.isArray(middleware)) {
+ throw new TypeError('Middleware stack must be an array!');
+ }
-export function compose(middleware: Function[]) {
- if (!Array.isArray(middleware))
- throw new TypeError('Middleware stack must be an array!');
for (const fn of middleware) {
- if (typeof fn !== 'function')
+ if (typeof fn !== 'function') {
throw new TypeError('Middleware must be composed of functions!');
+ }
}
/**
@@ -26,19 +28,30 @@
// last called middleware #
let index = -1;
return dispatch.call(this, 0);
+
function dispatch(i: number) {
- if (i <= index)
+ if (i <= index) {
return Promise.reject(new Error('next() called multiple times'));
+ }
+
index = i;
- let fn = middleware[i];
- if (i === middleware.length) fn = next;
+
+ const fn = i === middleware.length ? next : middleware[i];
+
if (!fn) return Promise.resolve();
+
+ const start = _.now();
+
try {
+ d('Begin of fn %O', fn.name);
return Promise.resolve(
fn.call(this, context, dispatch.bind(this, i + 1)),
);
} catch (err) {
return Promise.reject(err);
+ } finally {
+ const end = _.now();
+ d('End of fn %O, duration: %O', fn.name, end - start);
}
}
}; |
95db90ca2b493d9084f375de4586c7ad5559f52c | src/components/tilegrid.component.ts | src/components/tilegrid.component.ts | import { Component, Input, OnInit } from '@angular/core';
import { tilegrid, Extent, Size } from 'openlayers';
@Component({
selector: 'aol-tilegrid',
template: ''
})
export class TileGridComponent implements OnInit {
instance: tilegrid.TileGrid;
@Input() extent: Extent;
@Input() maxZoom: number;
@Input() minZoom: number;
@Input() tileSize: number|Size;
ngOnInit() {
this.instance = tilegrid.createXYZ(this);
}
}
| import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { tilegrid, Extent, Size , Coordinate} from 'openlayers';
@Component({
selector: 'aol-tilegrid',
template: ''
})
export class TileGridComponent implements OnInit, OnChanges {
instance: tilegrid.TileGrid;
@Input() extent: Extent;
@Input() maxZoom: number;
@Input() minZoom: number;
@Input() tileSize: number|Size;
@Input() origin?: Coordinate;
@Input() resolutions: number[];
ngOnInit() {
if (!this.resolutions) {
this.instance = tilegrid.createXYZ(this)
} else {
this.instance = new tilegrid.TileGrid(this);
}
}
ngOnChanges(changes: SimpleChanges) {
if (!this.resolutions) {
this.instance = tilegrid.createXYZ(this)
} else {
this.instance = new tilegrid.TileGrid(this);
}
}
}
| Allow resolutions and origin, and use new tilegrid.Tilegrid constructor | feat(tilegrid): Allow resolutions and origin, and use new tilegrid.Tilegrid constructor
| TypeScript | mpl-2.0 | quentin-ol/ngx-openlayers,karomamczi/ngx-openlayers,karomamczi/ngx-openlayers,quentin-ol/ngx-openlayers,karomamczi/ngx-openlayers,quentin-ol/ngx-openlayers | ---
+++
@@ -1,19 +1,33 @@
-import { Component, Input, OnInit } from '@angular/core';
-import { tilegrid, Extent, Size } from 'openlayers';
+import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
+import { tilegrid, Extent, Size , Coordinate} from 'openlayers';
@Component({
selector: 'aol-tilegrid',
template: ''
})
-export class TileGridComponent implements OnInit {
+export class TileGridComponent implements OnInit, OnChanges {
instance: tilegrid.TileGrid;
@Input() extent: Extent;
@Input() maxZoom: number;
@Input() minZoom: number;
@Input() tileSize: number|Size;
+ @Input() origin?: Coordinate;
+ @Input() resolutions: number[];
ngOnInit() {
- this.instance = tilegrid.createXYZ(this);
+ if (!this.resolutions) {
+ this.instance = tilegrid.createXYZ(this)
+ } else {
+ this.instance = new tilegrid.TileGrid(this);
+ }
+ }
+
+ ngOnChanges(changes: SimpleChanges) {
+ if (!this.resolutions) {
+ this.instance = tilegrid.createXYZ(this)
+ } else {
+ this.instance = new tilegrid.TileGrid(this);
+ }
}
} |
d57027bb5f188017bdeb41e22e835a3411a51e1f | src/util/json.ts | src/util/json.ts | import { readFileSync, writeFileSync } from 'fs'
export default {
read (filename) {
const blob = readFileSync(filename).toString()
return JSON.parse(blob)
},
write (filename, content) {
writeFileSync(filename, JSON.stringify(content, null, 2))
}
}
| import { readFileSync, writeFileSync } from 'fs'
export default {
read (filename) {
const blob = JSON.stringify(readFileSync(filename))
return JSON.parse(blob)
},
write (filename, content) {
writeFileSync(filename, JSON.stringify(content, null, 2))
}
}
| Revert "fix(install): Properly stringify buffer" | Revert "fix(install): Properly stringify buffer"
This reverts commit e92bdf39827315b74ed225fdd63626f5c04bb045.
| TypeScript | isc | sean-clayton/neato-react-starterkit,sean-clayton/neato-react-starterkit | ---
+++
@@ -2,7 +2,7 @@
export default {
read (filename) {
- const blob = readFileSync(filename).toString()
+ const blob = JSON.stringify(readFileSync(filename))
return JSON.parse(blob)
},
|
6f19dedaf6e91e714df58f5abe98027d5c451225 | ee_tests/src/page_objects/user_settings.page.ts | ee_tests/src/page_objects/user_settings.page.ts | import { browser, by, ExpectedConditions as until, $, element } from 'protractor';
import { AppPage } from './app.page';
export class UserSettingsPage extends AppPage {
public async gotoFeaturesTab(): Promise<FeaturesTab> {
await browser.wait(until.presenceOf(element(by.cssContainingText('a', 'Features Opt-in'))));
await element(by.cssContainingText('a', 'Features Opt-in')).click();
return new FeaturesTab();
}
}
export class FeaturesTab {
public async getFeatureLevel(): Promise<string> {
await browser.wait(until.presenceOf(element(by.css('input:checked'))));
let checkedInput = await element(by.css('input:checked'));
return await checkedInput.getAttribute('id');
}
}
| import { browser, by, ExpectedConditions as until, $, element } from 'protractor';
import { AppPage } from './app.page';
export class UserSettingsPage extends AppPage {
public async gotoFeaturesTab(): Promise<FeaturesTab> {
await browser.wait(until.presenceOf(element(by.cssContainingText('a', 'Features Opt-in'))));
await element(by.cssContainingText('a', 'Features Opt-in')).click();
return new FeaturesTab();
}
}
export class FeaturesTab {
readonly featureInputXpath = '//input/ancestor::*[contains(@class, \'active\')]//span[contains(@class,\'icon-\')]';
public async getFeatureLevel(): Promise<string> {
await browser.wait(until.presenceOf(element(by.xpath(this.featureInputXpath))));
let checkedInput = await element(by.xpath(this.featureInputXpath));
let featureInputIconCss = await checkedInput.getAttribute('class');
let featureCss = featureInputIconCss.match('icon-(internal|experimental|beta|released)');
await expect(featureCss).not.toBeNull('feature css');
if (featureCss != null) {
return featureCss[1];
}
return 'null';
}
}
| Update real feature level detection. | Update real feature level detection.
| TypeScript | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | ---
+++
@@ -11,10 +11,16 @@
}
export class FeaturesTab {
-
+ readonly featureInputXpath = '//input/ancestor::*[contains(@class, \'active\')]//span[contains(@class,\'icon-\')]';
public async getFeatureLevel(): Promise<string> {
- await browser.wait(until.presenceOf(element(by.css('input:checked'))));
- let checkedInput = await element(by.css('input:checked'));
- return await checkedInput.getAttribute('id');
+ await browser.wait(until.presenceOf(element(by.xpath(this.featureInputXpath))));
+ let checkedInput = await element(by.xpath(this.featureInputXpath));
+ let featureInputIconCss = await checkedInput.getAttribute('class');
+ let featureCss = featureInputIconCss.match('icon-(internal|experimental|beta|released)');
+ await expect(featureCss).not.toBeNull('feature css');
+ if (featureCss != null) {
+ return featureCss[1];
+ }
+ return 'null';
}
} |
decb7d059316d8527bc370b1218ff96e1fd1188a | tools/tasks/seed/build.js.prod.ts | tools/tasks/seed/build.js.prod.ts | import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';
import Config from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPlugins();
const INLINE_OPTIONS = {
base: Config.TMP_DIR,
useRelativePaths: true,
removeLineBreaks: true
};
/**
* Executes the build process, transpiling the TypeScript files for the production environment.
*/
export = () => {
let tsProject = makeTsProject({}, Config.TMP_DIR);
let src = [
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts',
join(Config.TMP_DIR, '**/*.ts'),
'!' + join(Config.TMP_DIR, `**/${Config.NG_FACTORY_FILE}.ts`)
];
let result = gulp.src(src)
.pipe(plugins.plumber())
.pipe(plugins.inlineNg2Template(INLINE_OPTIONS))
.pipe(tsProject())
.once('error', function(e: any) {
this.once('finish', () => process.exit(1));
});
return result.js
.pipe(plugins.template(templateLocals()))
.pipe(gulp.dest(Config.TMP_DIR))
.on('error', (e: any) => {
console.log(e);
});
};
| import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';
import Config from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPlugins();
const INLINE_OPTIONS = {
base: Config.TMP_DIR,
target: 'es5',
useRelativePaths: true,
removeLineBreaks: true
};
/**
* Executes the build process, transpiling the TypeScript files for the production environment.
*/
export = () => {
let tsProject = makeTsProject({}, Config.TMP_DIR);
let src = [
Config.TOOLS_DIR + '/manual_typings/**/*.d.ts',
join(Config.TMP_DIR, '**/*.ts'),
'!' + join(Config.TMP_DIR, `**/${Config.NG_FACTORY_FILE}.ts`)
];
let result = gulp.src(src)
.pipe(plugins.plumber())
.pipe(plugins.inlineNg2Template(INLINE_OPTIONS))
.pipe(tsProject())
.once('error', function(e: any) {
this.once('finish', () => process.exit(1));
});
return result.js
.pipe(plugins.template(templateLocals()))
.pipe(gulp.dest(Config.TMP_DIR))
.on('error', (e: any) => {
console.log(e);
});
};
| Set inline target to be es5 | Set inline target to be es5
| TypeScript | mit | idready/Philosophers,christophersanson/js-demo-fe,tobiaseisenschenk/data-cube,shaggyshelar/Linkup,natarajanmca11/angular2-seed,mgechev/angular-seed,guilhebl/offer-web,mgechev/angular2-seed,dmitriyse/angular2-seed,radiorabe/raar-ui,davewragg/agot-spa,tctc91/angular2-wordpress-portfolio,NathanWalker/angular2-seed-advanced,lhoezee/faithreg1,zertyz/observatorio-SUAS,trutoo/startatalk-native,shaggyshelar/Linkup,alexmanning23/uafl-web,JohnnyQQQQ/md-dashboard,ppanthony/angular-seed-tutorial,miltador/unichat,Shyiy/angular-seed,JohnnyQQQQ/angular-seed-material2,NathanWalker/angular-seed-advanced,mgechev/angular2-seed,dmitriyse/angular2-seed,hookom/climbontheway,trutoo/startatalk-native,Jimmysh/angular2-seed-advanced,GeoscienceAustralia/gnss-site-manager,OlivierVoyer/angular-seed-advanced,pocmanu/angular2-seed-advanced,trutoo/startatalk-native,ilvestoomas/angular-seed-advanced,fart-one/monitor-ngx,pocmanu/angular2-seed-advanced,idready/Philosophers,zertyz/angular-seed-advanced-spikes,nickaranz/robinhood-ui,AWNICS/mesomeds-ng2,idready/Bloody-Prophety-NG2,GeoscienceAustralia/gnss-site-manager,Shyiy/angular-seed,zertyz/edificando-o-controle-interno,deanQj/angular2-seed-bric,hookom/climbontheway,AWNICS/mesomeds-ng2,Karasuni/angular-seed,zertyz/angular-seed-advanced-spikes,hookom/climbontheway,JohnnyQQQQ/angular-seed-material2,davewragg/agot-spa,m-abs/angular2-seed-advanced,vyakymenko/angular-seed-express,llwt/angular-seed-advanced,idready/Bloody-Prophety-NG2,ManasviA/Dashboard,rawnics/mesomeds-ng2,ronikurnia1/ClientApp,alexmanning23/uafl-web,tctc91/angular2-wordpress-portfolio,chnoumis/angular2-seed-advanced,jigarpt/angular-seed-semi,christophersanson/js-demo-fe,pratheekhegde/a2-redux,fr-esco/angular-seed,pieczkus/whyblogfront,guilhebl/offer-web,dmitriyse/angular2-seed,jelgar1/fpl-api,JohnnyQQQQ/angular-seed-material2,m-abs/angular2-seed-advanced,tctc91/angular2-wordpress-portfolio,shaggyshelar/Linkup,mgechev/angular-seed,prabhatsharma/bwa2,prabhatsharma/bwa2,AnnaCasper/finance-tool,maniche04/ngIntranet,radiorabe/raar-ui,jigarpt/angular-seed-semi,pieczkus/whyblogfront,idready/Philosophers,ManasviA/Dashboard,tiagomapmarques/angular-examples_books,oblong-antelope/oblong-web,zertyz/edificando-o-controle-interno,felipecamargo/ACSC-SBPL-M,lhoezee/faithreg1,chnoumis/angular2-seed-advanced,Karasuni/angular-seed,radiorabe/raar-ui,tobiaseisenschenk/data-cube,wenzelj/nativescript-angular,watonyweng/angular-seed,natarajanmca11/angular2-seed,idready/Bloody-Prophety-NG2,adobley/angular2-tdd-workshop,hookom/climbontheway,ronikurnia1/ClientApp,arun-awnics/mesomeds-ng2,NathanWalker/angular-seed-advanced,wenzelj/nativescript-angular,GeoscienceAustralia/gnss-site-manager,arun-awnics/mesomeds-ng2,zertyz/observatorio-SUAS-formularios,adobley/angular2-tdd-workshop,tobiaseisenschenk/data-cube,pieczkus/whyblogfront,rtang03/fabric-seed,nickaranz/robinhood-ui,nickaranz/robinhood-ui,felipecamargo/ACSC-SBPL-M,jigarpt/angular-seed-semi,pratheekhegde/a2-redux,rtang03/fabric-seed,rtang03/fabric-seed,talentspear/a2-redux,origamyllc/Mangular,OlivierVoyer/angular-seed-advanced,MgCoders/angular-seed,talentspear/a2-redux,NathanWalker/angular2-seed-advanced,fr-esco/angular-seed,Shyiy/angular-seed,ManasviA/Dashboard,MgCoders/angular-seed,MgCoders/angular-seed,sanastasiadis/angular-seed-openlayers,Sn3b/angular-seed-advanced,ysyun/angular-seed-stub-api-environment,jelgar1/fpl-api,zertyz/observatorio-SUAS,fr-esco/angular-seed,zertyz/observatorio-SUAS,alexmanning23/uafl-web,rtang03/fabric-seed,mgechev/angular-seed,AWNICS/mesomeds-ng2,maniche04/ngIntranet,chnoumis/angular2-seed-advanced,arun-awnics/mesomeds-ng2,m-abs/angular2-seed-advanced,radiorabe/raar-ui,MgCoders/angular-seed,adobley/angular2-tdd-workshop,nie-ine/raeber-website,vyakymenko/angular-seed-express,millea1/tips1,sylviefiat/bdmer3,Nightapes/angular2-seed,ppanthony/angular-seed-tutorial,fart-one/monitor-ngx,zertyz/angular-seed-advanced-spikes,llwt/angular-seed-advanced,sylviefiat/bdmer3,oblong-antelope/oblong-web,natarajanmca11/angular2-seed,pocmanu/angular2-seed-advanced,ysyun/angular-seed-stub-api-environment,deanQj/angular2-seed-bric,sylviefiat/bdmer3,Nightapes/angular2-seed,adobley/angular2-tdd-workshop,felipecamargo/ACSC-SBPL-M,guilhebl/offer-web,fart-one/monitor-ngx,watonyweng/angular-seed,lhoezee/faithreg1,nie-ine/raeber-website,ilvestoomas/angular-seed-advanced,wenzelj/nativescript-angular,NathanWalker/angular-seed-advanced,JohnnyQQQQ/md-dashboard,JohnnyQQQQ/md-dashboard,origamyllc/Mangular,miltador/unichat,tiagomapmarques/angular-examples_books,ManasviA/Dashboard,maniche04/ngIntranet,zertyz/observatorio-SUAS-formularios,rawnics/mesomeds-ng2,ysyun/angular-seed-stub-api-environment,dmitriyse/angular2-seed,ppanthony/angular-seed-tutorial,AnnaCasper/finance-tool,AnnaCasper/finance-tool,Sn3b/angular-seed-advanced,davewragg/agot-spa,ronikurnia1/ClientApp,deanQj/angular2-seed-bric,Jimmysh/angular2-seed-advanced,origamyllc/Mangular,pratheekhegde/a2-redux,tiagomapmarques/angular-examples_books,jelgar1/fpl-api,rtang03/fabric-seed,llwt/angular-seed-advanced,prabhatsharma/bwa2,millea1/tips1,mgechev/angular2-seed,NathanWalker/angular2-seed-advanced,Jimmysh/angular2-seed-advanced,OlivierVoyer/angular-seed-advanced,zertyz/observatorio-SUAS,nie-ine/raeber-website,sanastasiadis/angular-seed-openlayers,zertyz/observatorio-SUAS-formularios,sanastasiadis/angular-seed-openlayers,miltador/unichat,Nightapes/angular2-seed,rawnics/mesomeds-ng2,ilvestoomas/angular-seed-advanced,oblong-antelope/oblong-web,OlivierVoyer/angular-seed-advanced,nie-ine/raeber-website,millea1/tips1,ysyun/angular-seed-stub-api-environment,Karasuni/angular-seed,talentspear/a2-redux,vyakymenko/angular-seed-express,Sn3b/angular-seed-advanced,zertyz/edificando-o-controle-interno,christophersanson/js-demo-fe | ---
+++
@@ -9,6 +9,7 @@
const INLINE_OPTIONS = {
base: Config.TMP_DIR,
+ target: 'es5',
useRelativePaths: true,
removeLineBreaks: true
}; |
00af371a7058484d433e3959fe1b20c2bcb319e5 | browser/src/Cursor.ts | browser/src/Cursor.ts | import { Action, UPDATE_FG, UpdateColorAction } from "./Actions"
import { Screen } from "./Screen"
export class Cursor {
private _cursorElement: HTMLElement;
constructor() {
var cursorElement = document.createElement("div")
cursorElement.style.position = "absolute"
this._cursorElement = cursorElement
this._cursorElement.style.backgroundColor = "red"
this._cursorElement.style.opacity = "0.5"
this._cursorElement.className = "cursor"
document.body.appendChild(cursorElement)
}
update(screen: Screen): void {
var cursorRow = screen.cursorRow;
var cursorColumn = screen.cursorColumn;
var fontWidthInPixels = screen.fontWidthInPixels
var fontHeightInPixels = screen.fontHeightInPixels
this._cursorElement.style.top = (cursorRow * fontHeightInPixels) + "px"
this._cursorElement.style.left = (cursorColumn * fontWidthInPixels) + "px"
var width = screen.mode === "normal" ? fontWidthInPixels : fontWidthInPixels / 4;
this._cursorElement.style.width = width + "px"
this._cursorElement.style.height = fontHeightInPixels + "px"
}
dispatch(action: any): void {
if(action.type === UPDATE_FG) {
this._cursorElement.style.backgroundColor = action.color
}
}
}
| import { Action, UPDATE_FG, UpdateColorAction } from "./actions"
import { Screen } from "./Screen"
export class Cursor {
private _cursorElement: HTMLElement;
constructor() {
var cursorElement = document.createElement("div")
cursorElement.style.position = "absolute"
this._cursorElement = cursorElement
this._cursorElement.style.backgroundColor = "red"
this._cursorElement.style.opacity = "0.5"
this._cursorElement.className = "cursor"
document.body.appendChild(cursorElement)
}
update(screen: Screen): void {
var cursorRow = screen.cursorRow;
var cursorColumn = screen.cursorColumn;
var fontWidthInPixels = screen.fontWidthInPixels
var fontHeightInPixels = screen.fontHeightInPixels
this._cursorElement.style.top = (cursorRow * fontHeightInPixels) + "px"
this._cursorElement.style.left = (cursorColumn * fontWidthInPixels) + "px"
var width = screen.mode === "normal" ? fontWidthInPixels : fontWidthInPixels / 4;
this._cursorElement.style.width = width + "px"
this._cursorElement.style.height = fontHeightInPixels + "px"
}
dispatch(action: any): void {
if(action.type === UPDATE_FG) {
this._cursorElement.style.backgroundColor = action.color
}
}
}
| Fix casing issue in Actions | Fix casing issue in Actions
| TypeScript | mit | extr0py/oni,JakubJecminek/oni,extr0py/oni,JakubJecminek/oni,extr0py/oni,JakubJecminek/oni,extr0py/oni,JakubJecminek/oni,extr0py/oni,JakubJecminek/oni | ---
+++
@@ -1,4 +1,4 @@
-import { Action, UPDATE_FG, UpdateColorAction } from "./Actions"
+import { Action, UPDATE_FG, UpdateColorAction } from "./actions"
import { Screen } from "./Screen"
export class Cursor { |
dc9cdfe4f00cb8805a272ba4ce682d649504f24a | src/app/core/import/reader/file-system-reader.ts | src/app/core/import/reader/file-system-reader.ts | import {Reader} from './reader';
import {ReaderErrors} from './reader-errors';
/**
* Reads contents of a file.
* Expects a UTF-8 encoded text file.
*
* @author Sebastian Cuy
* @author Jan G. Wieners
*/
export class FileSystemReader implements Reader {
constructor(private file: File) {}
/**
* Read content of file
*
* @returns {Promise<string>} file content | msgWithParams
*/
public go(): Promise<string> {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = (event: any) => {
resolve(event.target.result);
};
reader.onerror = (event: any) => {
console.error(event.target.error);
reject([ReaderErrors.FILE_UNREADABLE, this.file.name]);
};
reader.readAsText(this.file);
});
}
}
| import {Reader} from './reader';
import {ReaderErrors} from './reader-errors';
const fs = typeof window !== 'undefined' ? window.require('fs') : require('fs');
/**
* Reads contents of a file.
* Expects a UTF-8 encoded text file.
*
* @author Sebastian Cuy
* @author Jan G. Wieners
* @author Thomas Kleinke
*/
export class FileSystemReader implements Reader {
constructor(private file: any) {}
public go(): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(this.file.path, 'utf-8', (err: any, content: any) => {
if (err) {
reject([ReaderErrors.FILE_UNREADABLE, this.file.path]);
} else {
resolve(content);
}
});
});
}
}
| Use fs instead of FileReader in FileSystemReader to fix a bug where a file could not be loaded if it was changed after selection | Use fs instead of FileReader in FileSystemReader to fix a bug where a file could not be loaded if it was changed after selection
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,5 +1,8 @@
import {Reader} from './reader';
import {ReaderErrors} from './reader-errors';
+
+const fs = typeof window !== 'undefined' ? window.require('fs') : require('fs');
+
/**
* Reads contents of a file.
@@ -7,33 +10,24 @@
*
* @author Sebastian Cuy
* @author Jan G. Wieners
+ * @author Thomas Kleinke
*/
export class FileSystemReader implements Reader {
- constructor(private file: File) {}
+ constructor(private file: any) {}
- /**
- * Read content of file
- *
- * @returns {Promise<string>} file content | msgWithParams
- */
public go(): Promise<string> {
return new Promise((resolve, reject) => {
- let reader = new FileReader();
-
- reader.onload = (event: any) => {
- resolve(event.target.result);
- };
-
- reader.onerror = (event: any) => {
- console.error(event.target.error);
- reject([ReaderErrors.FILE_UNREADABLE, this.file.name]);
- };
-
- reader.readAsText(this.file);
+ fs.readFile(this.file.path, 'utf-8', (err: any, content: any) => {
+ if (err) {
+ reject([ReaderErrors.FILE_UNREADABLE, this.file.path]);
+ } else {
+ resolve(content);
+ }
+ });
});
}
} |
f6c849570330aec8b87e439cc653a8f9dc34e752 | src/cloudinary.module.ts | src/cloudinary.module.ts | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FileDropDirective, FileSelectDirective} from 'ng2-file-upload';
import {CloudinaryImageComponent} from './cloudinary-image.component';
import {CloudinaryImageService} from './cloudinary-image.service';
export {CloudinaryOptions} from './cloudinary-options.class';
export {CloudinaryUploader} from './cloudinary-uploader.service';
export {CloudinaryImageService};
@NgModule({
declarations: [
CloudinaryImageComponent,
FileDropDirective,
FileSelectDirective
],
imports: [CommonModule],
exports: [
CloudinaryImageComponent,
FileDropDirective,
FileSelectDirective
],
providers: [
CloudinaryImageService
]
})
export class Ng2CloudinaryModule {}
| import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FileDropDirective, FileSelectDirective} from 'ng2-file-upload';
import {CloudinaryImageComponent} from './cloudinary-image.component';
import {CloudinaryImageService} from './cloudinary-image.service';
export {CloudinaryOptions} from './cloudinary-options.class';
export {CloudinaryTransforms} from './cloudinary-transforms.class';
export {CloudinaryUploader} from './cloudinary-uploader.service';
export {CloudinaryImageService};
@NgModule({
declarations: [
CloudinaryImageComponent,
FileDropDirective,
FileSelectDirective
],
imports: [CommonModule],
exports: [
CloudinaryImageComponent,
FileDropDirective,
FileSelectDirective
],
providers: [
CloudinaryImageService
]
})
export class Ng2CloudinaryModule {}
| Add missing export for CloudinaryTransforms | fix(Ng2CloudinaryModule): Add missing export for CloudinaryTransforms
| TypeScript | mit | Ekito/ng2-cloudinary,Ekito/ng2-cloudinary,Ekito/ng2-cloudinary | ---
+++
@@ -5,6 +5,7 @@
import {CloudinaryImageService} from './cloudinary-image.service';
export {CloudinaryOptions} from './cloudinary-options.class';
+export {CloudinaryTransforms} from './cloudinary-transforms.class';
export {CloudinaryUploader} from './cloudinary-uploader.service';
export {CloudinaryImageService};
|
7343abc8368954ec481ed0798801989d1d35a1e2 | libs/dexie-react-hooks/src/dexie-react-hooks.ts | libs/dexie-react-hooks/src/dexie-react-hooks.ts | import {liveQuery} from "dexie";
import {useSubscription} from "./use-subscription";
import React from "react";
export function useLiveQuery<T>(querier: ()=>Promise<T> | T, dependencies?: any[]): T | undefined;
export function useLiveQuery<T,TDefault> (querier: ()=>Promise<T> | T, dependencies: any[], defaultResult: TDefault) : T | TDefault;
export function useLiveQuery<T,TDefault> (querier: ()=>Promise<T> | T, dependencies?: any[], defaultResult?: TDefault) : T | TDefault{
const [lastResult, setLastResult] = React.useState(defaultResult as T | TDefault);
const subscription = React.useMemo(
() => {
// Make it remember previus subscription's default value when
// resubscribing (á la useTransition())
let currentValue = lastResult;
const observable = liveQuery(querier);
return {
getCurrentValue: () => currentValue,
subscribe: (onNext, onError) => {
const esSubscription = observable.subscribe(value => {
currentValue = value;
setLastResult(value);
onNext(value);
}, onError);
return esSubscription.unsubscribe.bind(esSubscription);
}
};
},
// Re-subscribe any time any of the given dependencies change
dependencies || []
);
// The value returned by this hook reflects the current result from the querier
// Our component will automatically be re-rendered when that value changes.
const value = useSubscription(subscription);
return value;
} | import {liveQuery} from "dexie";
import {useSubscription} from "./use-subscription";
import React from "react";
export function useLiveQuery<T>(querier: ()=>Promise<T> | T, dependencies?: any[]): T | undefined;
export function useLiveQuery<T,TDefault> (querier: ()=>Promise<T> | T, dependencies: any[], defaultResult: TDefault) : T | TDefault;
export function useLiveQuery<T,TDefault> (querier: ()=>Promise<T> | T, dependencies?: any[], defaultResult?: TDefault) : T | TDefault{
const [lastResult, setLastResult] = React.useState(defaultResult as T | TDefault);
const subscription = React.useMemo(
() => {
// Make it remember previous subscription's default value when
// resubscribing (á la useTransition())
let currentValue = lastResult;
const observable = liveQuery(querier);
return {
getCurrentValue: () => currentValue,
subscribe: (onNext, onError) => {
const esSubscription = observable.subscribe(value => {
currentValue = value;
setLastResult(value);
onNext(value);
}, onError);
return esSubscription.unsubscribe.bind(esSubscription);
}
};
},
// Re-subscribe any time any of the given dependencies change
dependencies || []
);
// The value returned by this hook reflects the current result from the querier
// Our component will automatically be re-rendered when that value changes.
const value = useSubscription(subscription);
return value;
} | Fix small typo (previus to previous) | Fix small typo (previus to previous)
| TypeScript | apache-2.0 | jimmywarting/Dexie.js,dfahlander/Dexie.js,dfahlander/Dexie.js,jimmywarting/Dexie.js,dfahlander/Dexie.js,jimmywarting/Dexie.js,jimmywarting/Dexie.js,dfahlander/Dexie.js | ---
+++
@@ -8,7 +8,7 @@
const [lastResult, setLastResult] = React.useState(defaultResult as T | TDefault);
const subscription = React.useMemo(
() => {
- // Make it remember previus subscription's default value when
+ // Make it remember previous subscription's default value when
// resubscribing (á la useTransition())
let currentValue = lastResult;
const observable = liveQuery(querier); |
c9605ec82c45eb13a348eb3f6ad2942654c74ce9 | Wallet/OnlineWallet.Web.Core/ClientApp/layout.tsx | Wallet/OnlineWallet.Web.Core/ClientApp/layout.tsx | import * as React from "react";
import { Navbar, AlertList, TransactionSummary } from "walletCommon";
interface LayoutProps {
}
const Layout: React.SFC<LayoutProps> = ({ ...rest }) => {
return (
<div>
<Navbar />
<AlertList />
<main role="main" className="container">
{rest.children}
</main>
<TransactionSummary />
</div>
);
};
export { Layout };
| import * as React from "react";
import { Navbar, AlertList, TransactionSummary } from "walletCommon";
interface LayoutProps {
}
const Layout: React.SFC<LayoutProps> = ({ ...rest }) => {
return (
<>
<Navbar />
<AlertList />
<main role="main" className="container">
{rest.children}
</main>
<TransactionSummary />
</>
);
};
export { Layout };
| Remove unnecessary div from Layout. | Remove unnecessary div from Layout.
| TypeScript | mit | faddiv/budget-keeper,faddiv/budget-keeper,faddiv/budget-keeper,faddiv/budget-keeper | ---
+++
@@ -6,14 +6,14 @@
const Layout: React.SFC<LayoutProps> = ({ ...rest }) => {
return (
- <div>
+ <>
<Navbar />
<AlertList />
<main role="main" className="container">
{rest.children}
</main>
<TransactionSummary />
- </div>
+ </>
);
};
|
f153007d04f43a5cfce6e929799166c954040375 | src/app/homepage/homepage-activate.service.ts | src/app/homepage/homepage-activate.service.ts | import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {Observable} from 'rxjs';
import * as myGlobals from '../globals';
@Injectable({providedIn: 'root'})
export class HomepageActivateService implements CanActivate {
config = myGlobals.config;
constructor(private router: Router) {
}
canActivate(): Observable<boolean> {
if (!this.config.showHomepage) {
this.router.navigate(['/user-mgmt/login']);
return Observable.of(false);
} else {
return Observable.of(true);
}
}
}
| import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {Observable} from 'rxjs';
import { of } from 'rxjs';
import * as myGlobals from '../globals';
@Injectable({providedIn: 'root'})
export class HomepageActivateService implements CanActivate {
config = myGlobals.config;
constructor(private router: Router) {
}
canActivate(): Observable<boolean> {
if (!this.config.showHomepage) {
this.router.navigate(['/user-mgmt/login']);
return of(false);
} else {
return of(true);
}
}
}
| Fix usage of Observable of method | Fix usage of Observable of method
| TypeScript | apache-2.0 | nimble-platform/frontend-service,nimble-platform/frontend-service,nimble-platform/frontend-service,nimble-platform/frontend-service | ---
+++
@@ -1,6 +1,7 @@
import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {Observable} from 'rxjs';
+import { of } from 'rxjs';
import * as myGlobals from '../globals';
@Injectable({providedIn: 'root'})
@@ -13,9 +14,9 @@
canActivate(): Observable<boolean> {
if (!this.config.showHomepage) {
this.router.navigate(['/user-mgmt/login']);
- return Observable.of(false);
+ return of(false);
} else {
- return Observable.of(true);
+ return of(true);
}
}
} |
9b168cf069338242591f67e515069dead50d16f8 | src/ui/actions/editor/closeActiveProjectFile.ts | src/ui/actions/editor/closeActiveProjectFile.ts | import { ApplicationState } from '../../../shared/models/applicationState';
import { defineAction } from '../../reduxWithLessSux/action';
export const closeActiveProjectFile = defineAction(
'closeActiveProjectFile', (state: ApplicationState) => {
const editors = state.editors.filter((_, editorIndex) => editorIndex !== state.activeEditorIndex);
return {
...state,
editors
};
}
).getDispatcher();
| import { ApplicationState } from '../../../shared/models/applicationState';
import { defineAction } from '../../reduxWithLessSux/action';
export const closeActiveProjectFile = defineAction(
'closeActiveProjectFile', (state: ApplicationState) => {
let { activeEditorIndex } = state;
const editors = state.editors.filter((_, editorIndex) => editorIndex !== activeEditorIndex);
activeEditorIndex = editors.length - 1;
return {
...state,
activeEditorIndex,
editors
};
}
).getDispatcher();
| Fix bug where closing a file could result in a completely blank ui | Fix bug where closing a file could result in a completely blank ui
| TypeScript | mit | codeandcats/Polygen | ---
+++
@@ -3,9 +3,12 @@
export const closeActiveProjectFile = defineAction(
'closeActiveProjectFile', (state: ApplicationState) => {
- const editors = state.editors.filter((_, editorIndex) => editorIndex !== state.activeEditorIndex);
+ let { activeEditorIndex } = state;
+ const editors = state.editors.filter((_, editorIndex) => editorIndex !== activeEditorIndex);
+ activeEditorIndex = editors.length - 1;
return {
...state,
+ activeEditorIndex,
editors
};
} |
54c0f35ec295254cb7c8ccbd24454e18a3cb4c99 | Configuration/Typoscript/setup.ts | Configuration/Typoscript/setup.ts | #
# Plugin (FE) config
#
plugin.tx_tevmailchimp {
persistence {
storagePid = {$plugin.tx_tevmailchimp.persistence.storagePid}
classes {
Tev\TevMailchimp\Domain\Model\Mlist {
newRecordStoragePid = {$plugin.tx_tevmailchimp.persistence.storagePid}
}
}
}
}
#
# Module (BE and CLI) config
#
module.tx_tevmailchimp < plugin.tx_tevmailchimp
#
# JSON page type for incoming Mailchimp webhooks.
#
tev_mailchimp_webhook_json = PAGE
tev_mailchimp_webhook_json {
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json
xhtml_cleaning = 0
admPanel = 0
debug = 0
}
10 = USER
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
vendorName = Tev
extensionName = TevMailchimp
pluginName = Webhooks
}
}
| #
# Plugin (FE) config
#
plugin.tx_tevmailchimp {
persistence {
storagePid = {$plugin.tx_tevmailchimp.persistence.storagePid}
classes {
Tev\TevMailchimp\Domain\Model\Mlist {
newRecordStoragePid = {$plugin.tx_tevmailchimp.persistence.storagePid}
}
}
}
}
#
# Module (BE and CLI) config
#
module.tx_tevmailchimp < plugin.tx_tevmailchimp
#
# JSON page type for incoming Mailchimp webhooks.
#
tev_mailchimp_webhook_json = PAGE
tev_mailchimp_webhook_json {
typeNum = 0
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json
xhtml_cleaning = 0
admPanel = 0
debug = 0
}
10 = USER
10 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
vendorName = Tev
extensionName = TevMailchimp
pluginName = Webhooks
}
}
| Set a typenum for the webhook page definition | Set a typenum for the webhook page definition
| TypeScript | mit | 3ev/tev_mailchimp,3ev/tev_mailchimp | ---
+++
@@ -30,6 +30,8 @@
tev_mailchimp_webhook_json = PAGE
tev_mailchimp_webhook_json {
+ typeNum = 0
+
config {
disableAllHeaderCode = 1
additionalHeaders = Content-type:application/json |
eb3a51b30dc0bad66c4df130acae15923aa9f071 | src/renderer/app/components/BottomSheet/style.ts | src/renderer/app/components/BottomSheet/style.ts | import styled, { css } from 'styled-components';
import { shadows } from '~/shared/mixins';
export const StyledBottomSheet = styled.div`
position: absolute;
top: ${({ visible }: { visible: boolean }) =>
visible ? 'calc(100% - 128px)' : '100%'};
z-index: 99999;
background-color: white;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
left: 50%;
transform: translateX(-50%);
transition: 0.3s top;
width: 700px;
color: black;
box-shadow: ${shadows(4)};
`;
export const SmallBar = styled.div`
position: relative;
left: 50%;
transform: translateX(-50%);
border-radius: 20px;
height: 4px;
width: 32px;
background-color: rgba(0, 0, 0, 0.12);
margin-top: 8px;
`;
| import styled, { css } from 'styled-components';
import { shadows } from '~/shared/mixins';
export const StyledBottomSheet = styled.div`
position: absolute;
top: ${({ visible }: { visible: boolean }) =>
visible ? 'calc(100% - 128px)' : '100%'};
z-index: 99999;
background-color: white;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
left: 50%;
transform: translateX(-50%);
transition: 0.2s top;
width: 700px;
color: black;
box-shadow: ${shadows(4)};
`;
export const SmallBar = styled.div`
position: relative;
left: 50%;
transform: translateX(-50%);
border-radius: 20px;
height: 4px;
width: 32px;
background-color: rgba(0, 0, 0, 0.12);
margin-top: 8px;
`;
| Make bottom sheet animation faster | Make bottom sheet animation faster
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -11,7 +11,7 @@
border-top-right-radius: 8px;
left: 50%;
transform: translateX(-50%);
- transition: 0.3s top;
+ transition: 0.2s top;
width: 700px;
color: black;
box-shadow: ${shadows(4)}; |
80affb69aa87518b30261aabf474103a422e385e | src/utils/comments/commentPatterns.ts | src/utils/comments/commentPatterns.ts | const BY_LANGUAGE = {
xml: "<!-- %s -->",
hash: "# %s",
bat: "REM %s",
percent: "% %s",
handlebars: "{{!-- %s --}}",
doubleDash: "-- %s",
block: "/* %s */",
doubleLine: "-- %s",
pug: "//- %s",
common: "// %s"
};
const BY_PATTERN = {
block: ["css"],
hash: [
"python",
"shellscript",
"dockerfile",
"ruby",
"coffeescript",
"dockerfile",
"elixir",
"julia",
"makefile",
"perl",
"yaml"
],
xml: ["xml", "xsl", "html", "markdown"],
percent: ["tex", "prolog"],
pug: ["pug", "jade"],
doubleDash: ["lua", "sql", "haskell", "cabal"],
doubleLine: ["sql", "ada", "haskell", "lua", "pig"],
common: [
"javascript",
"javascriptreact",
"typescript",
"java",
"c",
"cpp",
"d"
]
};
function computePatternByLanguage(): { [s: string]: string } {
let result: { [s: string]: string } = {};
for (let [pattern, languages] of Object.entries(BY_PATTERN)) {
languages.forEach(language => {
result[language] = BY_LANGUAGE[pattern];
});
}
return result;
}
const patterns = computePatternByLanguage();
export default patterns;
| // TODO: add all languages from https://code.visualstudio.com/docs/languages/identifiers
const BY_LANGUAGE = {
xml: "<!-- %s -->",
hash: "# %s",
bat: "REM %s",
percent: "% %s",
handlebars: "{{!-- %s --}}",
doubleDash: "-- %s",
block: "/* %s */",
doubleLine: "-- %s",
pug: "//- %s",
common: "// %s"
};
const BY_PATTERN = {
block: ["css"],
hash: [
"python",
"shellscript",
"dockerfile",
"ruby",
"coffeescript",
"dockerfile",
"elixir",
"julia",
"makefile",
"perl",
"yaml"
],
xml: ["xml", "xsl", "html", "markdown"],
percent: ["tex", "prolog"],
pug: ["pug", "jade"],
doubleDash: ["lua", "sql", "haskell", "cabal"],
doubleLine: ["sql", "ada", "haskell", "lua", "pig"],
common: [
"javascript",
"javascriptreact",
"typescript",
"java",
"c",
"c#",
"cpp",
"d"
]
};
function computePatternByLanguage(): { [s: string]: string } {
let result: { [s: string]: string } = {};
for (let [pattern, languages] of Object.entries(BY_PATTERN)) {
languages.forEach(language => {
result[language] = BY_LANGUAGE[pattern];
});
}
return result;
}
const patterns = computePatternByLanguage();
export default patterns;
| Add TODO to comment patterns config to add all language ids | Add TODO to comment patterns config to add all language ids
| TypeScript | mit | guywald1/vscode-prismo | ---
+++
@@ -1,3 +1,5 @@
+// TODO: add all languages from https://code.visualstudio.com/docs/languages/identifiers
+
const BY_LANGUAGE = {
xml: "<!-- %s -->",
hash: "# %s",
@@ -37,6 +39,7 @@
"typescript",
"java",
"c",
+ "c#",
"cpp",
"d"
] |
ebdd09eff48d7cf753e7a4b888f76c1c03ac8a5b | src/app/createApp.ts | src/app/createApp.ts | import express, {Application} from 'express'
import helmet from 'helmet'
import cors from 'cors'
import bodyParser from 'body-parser'
import routes from '../routes'
import connectDb from './connectDb'
import {httpLoggerMiddleware as httpLogger} from './logger'
export default async (): Promise<Application> => {
const app = express()
app.use(helmet())
app.use(cors())
app.use(bodyParser.json({limit: '1mb'}))
app.use(httpLogger)
await connectDb()
app.use('/', routes)
return app
}
| import express, {Application} from 'express'
import helmet from 'helmet'
import cors from 'cors'
import bodyParser from 'body-parser'
import routes from '../routes'
import connectDb from './connectDb'
import {httpLoggerMiddleware as httpLogger} from './logger'
export default async (): Promise<Application> => {
const app = express()
app.use(helmet())
app.use(cors())
app.use(bodyParser.json())
app.use(httpLogger)
await connectDb()
app.use('/', routes)
return app
}
| Reset body limit to default | Reset body limit to default
| TypeScript | mit | ericnishio/express-boilerplate,ericnishio/express-boilerplate,ericnishio/express-boilerplate | ---
+++
@@ -12,7 +12,7 @@
app.use(helmet())
app.use(cors())
- app.use(bodyParser.json({limit: '1mb'}))
+ app.use(bodyParser.json())
app.use(httpLogger)
await connectDb() |
0188ed897afa488a669e7589af5c1330bab732c2 | src/utils/dates.ts | src/utils/dates.ts | /**
* Expects a string in MTurk's URL encoded date format
* (e.g. '09262017' would be converted into a Date object for
* September 26th, 2017)
* @param encodedDate string in described format
*/
export const encodedDateStringToDate = (encodedDate: string): Date => {
const parseableDateString =
encodedDate.slice(0, 2) +
' ' +
encodedDate.slice(2, 4) +
' ' +
encodedDate.slice(4);
return new Date(Date.parse(parseableDateString));
};
| /**
* Expects a string in MTurk's URL encoded date format
* (e.g. '09262017' would be converted into a Date object for
* September 26th, 2017)
* @param encodedDate string in described format
*/
export const encodedDateStringToDate = (encodedDate: string): Date => {
const parseableDateString =
encodedDate.slice(0, 2) +
' ' +
encodedDate.slice(2, 4) +
' ' +
encodedDate.slice(4);
return new Date(Date.parse(parseableDateString));
};
/**
* Converts Date objects to MTurk formatted date strings.
* (e.g. Date object for September 26th, 2017 would be converted to '09262017')
* @param date
*/
export const dateToEncodedDateString = (date: Date): string => {
const day = padTwoDigits(date.getDay());
const month = padTwoDigits(date.getMonth());
const year = date.getFullYear().toString();
return month + day + year;
};
const padTwoDigits = (num: number): string => {
return num < 10 ? '0' + num.toString() : num.toString();
};
| Add utility function for converting date objects to Mturk formatted date strings. | Add utility function for converting date objects to Mturk formatted date strings.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -14,3 +14,19 @@
return new Date(Date.parse(parseableDateString));
};
+
+/**
+ * Converts Date objects to MTurk formatted date strings.
+ * (e.g. Date object for September 26th, 2017 would be converted to '09262017')
+ * @param date
+ */
+export const dateToEncodedDateString = (date: Date): string => {
+ const day = padTwoDigits(date.getDay());
+ const month = padTwoDigits(date.getMonth());
+ const year = date.getFullYear().toString();
+ return month + day + year;
+};
+
+const padTwoDigits = (num: number): string => {
+ return num < 10 ? '0' + num.toString() : num.toString();
+}; |
2cbcbd1480af851b4ab0e3c6caf5044a78ab05e5 | desktop/app/src/utils/info.tsx | desktop/app/src/utils/info.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import os from 'os';
export type Info = {
arch: string;
platform: string;
unixname: string;
versions: {
[key: string]: string | undefined;
};
};
/**
* This method builds up some metadata about the users environment that we send
* on bug reports, analytic events, errors etc.
*/
export function getInfo(): Info {
return {
arch: process.arch,
platform: process.platform,
unixname: os.userInfo().username,
versions: {
electron: process.versions.electron,
node: process.versions.node,
},
};
}
export function stringifyInfo(info: Info): string {
const lines = [
`Platform: ${info.platform} ${info.arch}`,
`Unixname: ${info.unixname}`,
`Versions:`,
];
for (const key in info.versions) {
lines.push(` ${key}: ${String(info.versions[key])}`);
}
return lines.join('\n');
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import os from 'os';
export type Info = {
arch: string;
platform: string;
unixname: string;
versions: {
[key: string]: string | undefined;
};
};
/**
* This method builds up some metadata about the users environment that we send
* on bug reports, analytic events, errors etc.
*/
export function getInfo(): Info {
return {
arch: process.arch,
platform: process.platform,
unixname: os.userInfo().username,
versions: {
electron: process.versions.electron,
node: process.versions.node,
platform: os.release(),
},
};
}
export function stringifyInfo(info: Info): string {
const lines = [
`Platform: ${info.platform} ${info.arch}`,
`Unixname: ${info.unixname}`,
`Versions:`,
];
for (const key in info.versions) {
lines.push(` ${key}: ${String(info.versions[key])}`);
}
return lines.join('\n');
}
| Include os version in metrics | Include os version in metrics
Summary: May be useful for stability signals, or general bug correlation down the line.
Reviewed By: nikoant
Differential Revision: D23904843
fbshipit-source-id: ca31722b58d4657a9600fe5ce16ea3b5efd2c870
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -30,6 +30,7 @@
versions: {
electron: process.versions.electron,
node: process.versions.node,
+ platform: os.release(),
},
};
} |
8e76ee934b650be5143fea08523bff40d6125349 | lib/ts/index.ts | lib/ts/index.ts | import * as slicer from "./advanced_slicer";
import * as three_d from "./core_threed";
import * as printer from "./printer_config";
import * as slicer_job from "./slicer_job";
import * as units from "./units";
export {
slicer, three_d, printer, slicer_job, units
} | import * as slicer from "./advanced_slicer";
import * as three_d from "./core_threed";
import * as printer from "./printer_config";
import * as slicer_job from "./slicer_job";
import * as units from "./units";
console.debug("Microtome Slicing Library loaded.");
export {
slicer, three_d, printer, slicer_job, units
} | Add simple message to confirm library loading was successful | Add simple message to confirm library loading was successful
| TypeScript | apache-2.0 | Microtome/microtome,DanielJoyce/microtome,Microtome/microtome,Microtome/microtome,DanielJoyce/microtome,DanielJoyce/microtome,DanielJoyce/microtome | ---
+++
@@ -4,6 +4,8 @@
import * as slicer_job from "./slicer_job";
import * as units from "./units";
+console.debug("Microtome Slicing Library loaded.");
+
export {
slicer, three_d, printer, slicer_job, units
} |
35b84da79e1bdd816500131f8e3dc5959c7ac66f | demo/App.tsx | demo/App.tsx | import * as React from "react";
import ReactMde, {ReactMdeTypes} from "../src";
import * as Showdown from "showdown";
export interface AppState {
mdeState: ReactMdeTypes.MdeState;
}
export class App extends React.Component<{}, AppState> {
converter: Showdown.Converter;
constructor(props) {
super(props);
this.state = {
mdeState: {
markdown: "**Hello world!!!**",
},
};
this.converter = new Showdown.Converter({tables: true, simplifiedAutoLink: true});
}
handleValueChange = (mdeState: ReactMdeTypes.MdeState) => {
this.setState({mdeState});
}
render() {
return (
<div className="container">
<ReactMde
onChange={this.handleValueChange}
editorState={this.state.mdeState}
generateMarkdownPreview={(markdown) => Promise.resolve(this.converter.makeHtml(markdown))}
/>
</div>
);
}
}
| import * as React from "react";
import ReactMde, {ReactMdeTypes} from "../src";
import * as Showdown from "showdown";
export interface AppState {
mdeState: ReactMdeTypes.MdeState;
}
export class App extends React.Component<{}, AppState> {
converter: Showdown.Converter;
constructor(props) {
super(props);
this.state = {
mdeState: {
markdown: "**Hello world!!!**",
},
};
this.converter = new Showdown.Converter({
tables: true,
simplifiedAutoLink: true,
strikethrough: true,
});
}
handleValueChange = (mdeState: ReactMdeTypes.MdeState) => {
this.setState({mdeState});
}
render() {
return (
<div className="container">
<ReactMde
onChange={this.handleValueChange}
editorState={this.state.mdeState}
generateMarkdownPreview={(markdown) => Promise.resolve(this.converter.makeHtml(markdown))}
/>
</div>
);
}
}
| Add strikethrough as an option to the demo Showdown config | Add strikethrough as an option to the demo Showdown config
| TypeScript | mit | andrerpena/react-mde,andrerpena/react-mde,andrerpena/react-mde | ---
+++
@@ -17,7 +17,11 @@
markdown: "**Hello world!!!**",
},
};
- this.converter = new Showdown.Converter({tables: true, simplifiedAutoLink: true});
+ this.converter = new Showdown.Converter({
+ tables: true,
+ simplifiedAutoLink: true,
+ strikethrough: true,
+ });
}
handleValueChange = (mdeState: ReactMdeTypes.MdeState) => { |
840416d8bd5cf9a693dec62b9a45afb1ece4e060 | src/app/app.component.ts | src/app/app.component.ts | import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private readonly links = [{
path: 'datasets',
label: 'Datasets',
},{
path: 'analyses',
label: 'Analyses',
},{
path: 'api',
label: 'API',
}];
readonly linkActive$ = this.router.events
.filter(event => event instanceof NavigationEnd)
.map((event: NavigationEnd) => {
return this.links.map(link => link.path)
.includes(event.urlAfterRedirects.substr(1));
});
constructor(private readonly router: Router) {}
}
| import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private readonly links = [{
path: 'datasets',
label: 'Datasets',
}, {
path: 'analyses',
label: 'Analyses',
}, {
path: 'api',
label: 'API',
}];
readonly linkActive$ = this.router.events
.filter(event => event instanceof NavigationEnd)
.map((event: NavigationEnd) => {
return this.links.map(link => link.path)
.includes(event.urlAfterRedirects.substr(1));
});
constructor(private readonly router: Router) {}
}
| Fix linting errors in AppComponent | Fix linting errors in AppComponent
| TypeScript | bsd-3-clause | cumulous/web,cumulous/web,cumulous/web,cumulous/web | ---
+++
@@ -13,10 +13,10 @@
private readonly links = [{
path: 'datasets',
label: 'Datasets',
- },{
+ }, {
path: 'analyses',
label: 'Analyses',
- },{
+ }, {
path: 'api',
label: 'API',
}]; |
0bfc4ecdf0d4115f32f1dff198cbbd94dd5e034e | src/app/home/home.e2e.ts | src/app/home/home.e2e.ts | import { browser } from 'protractor';
import { HomePage } from './home.po';
import 'tslib';
describe('Home', function() {
let home: HomePage;
beforeEach(() => {
home = new HomePage();
home.navigateTo();
});
/* Protractor was not waiting for the page to fully load
thus, 'async' and 'await' is used throughtout the test.
*/
it('Should check title', async function() {
await expect(home.getPageTitleText()).toEqual('VA Website!');
});
it('Should navigate to Patient Login page', async function() {
await home.getPatientCheckInBtn().click();
await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/login');
});
// Fail on purpose to show that the test was properly checking elements
it('Should navigate to Audiologist Login page', async function() {
await home.getAudiologistLoginBtn().click();
await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/FAIL');
});
});
| import { browser } from 'protractor';
import { HomePage } from './home.po';
import 'tslib';
describe('Home', function() {
let home: HomePage;
beforeEach(() => {
home = new HomePage();
home.navigateTo();
});
/* Protractor was not waiting for the page to fully load
thus, 'async' and 'await' is used throughtout the test.
*/
it('Should show title text', async function() {
await expect(home.getPageTitleText()).toEqual('VA Website!');
});
/* Both Patient Check In and Audiologist Login uses the same component
so, only the two buttons functionalies are tested
*/
it('Should navigate to Patient Login page', async function() {
await home.getPatientCheckInBtn().click();
await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/login');
});
it('Should navigate to Audiologist Login page', async function() {
await home.getAudiologistLoginBtn().click();
await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/login');
});
});
| Add new functional test file and test cases for THS component | Add new functional test file and test cases for THS component
| TypeScript | mit | marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website | ---
+++
@@ -14,19 +14,21 @@
/* Protractor was not waiting for the page to fully load
thus, 'async' and 'await' is used throughtout the test.
*/
- it('Should check title', async function() {
+ it('Should show title text', async function() {
await expect(home.getPageTitleText()).toEqual('VA Website!');
});
+ /* Both Patient Check In and Audiologist Login uses the same component
+ so, only the two buttons functionalies are tested
+ */
it('Should navigate to Patient Login page', async function() {
await home.getPatientCheckInBtn().click();
await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/login');
});
- // Fail on purpose to show that the test was properly checking elements
it('Should navigate to Audiologist Login page', async function() {
await home.getAudiologistLoginBtn().click();
- await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/FAIL');
+ await expect(browser.getCurrentUrl()).toEqual('http://localhost:3000/login');
});
}); |
7df95e343655463140eedc6fc7addf80a06648e8 | index.d.ts | index.d.ts | import * as feathers from 'feathers';
declare module 'feathers' {
interface Service<T> {
before(hooks: hooks.HookMap);
after(hooks: hooks.HookMap);
hooks(hooks: hooks.HooksObject);
}
}
declare function hooks(): () => void;
declare namespace hooks {
interface Hook {
<T>(hook: HookProps<T>): Promise<any> | void;
}
interface HookProps<T> {
method?: string;
type: 'before' | 'after' | 'error';
params?: any;
data?: T;
result?: T;
app?: feathers.Application;
}
interface HookMap {
all?: Hook | Hook[];
find?: Hook | Hook[];
get?: Hook | Hook[];
create?: Hook | Hook[];
update?: Hook | Hook[];
patch?: Hook | Hook[];
remove?: Hook | Hook[];
}
interface HooksObject {
before?: HookMap;
after?: HookMap;
error?: HookMap;
}
}
export = hooks;
| import * as feathers from 'feathers';
declare module 'feathers' {
interface Service<T> {
before(hooks: hooks.HookMap):any;
after(hooks: hooks.HookMap):any;
hooks(hooks: hooks.HooksObject):any;
}
}
declare function hooks(): () => void;
declare namespace hooks {
interface Hook {
<T>(hook: HookProps<T>): Promise<any> | void;
}
interface HookProps<T> {
method?: string;
type: 'before' | 'after' | 'error';
params?: any;
data?: T;
result?: T;
app?: feathers.Application;
}
interface HookMap {
all?: Hook | Hook[];
find?: Hook | Hook[];
get?: Hook | Hook[];
create?: Hook | Hook[];
update?: Hook | Hook[];
patch?: Hook | Hook[];
remove?: Hook | Hook[];
}
interface HooksObject {
before?: HookMap;
after?: HookMap;
error?: HookMap;
}
}
export = hooks;
| Define return type for hooks | Define return type for hooks | TypeScript | mit | feathersjs/feathers-hooks | ---
+++
@@ -2,9 +2,9 @@
declare module 'feathers' {
interface Service<T> {
- before(hooks: hooks.HookMap);
- after(hooks: hooks.HookMap);
- hooks(hooks: hooks.HooksObject);
+ before(hooks: hooks.HookMap):any;
+ after(hooks: hooks.HookMap):any;
+ hooks(hooks: hooks.HooksObject):any;
}
}
|
72ce7dcc5d22f8a67ec928b61e879e1ded7a0869 | index.d.ts | index.d.ts | declare const observableSymbol: symbol;
export default observableSymbol;
declare global {
export interface SymbolConstructor {
readonly observable: unique symbol;
}
}
| declare const observableSymbol: symbol;
export default observableSymbol;
declare global {
export interface SymbolConstructor {
readonly observable: symbol;
}
}
| Revert to `symbol` from `unique symbol`. | refactor: Revert to `symbol` from `unique symbol`.
BREAKING CHANGE: Following the advice of the TypeScript team, the type for `Symbol.observable` is reverted back to `symbol` from `unique symbol`. This is to improve compatibility with other libraries using this module. Sincerely sorry for the trashing. Getting the types right for modules is hard. If this continues to cause issues for you, please file an issue with the [TypeScript project](https://github.com/microsoft/typescript).
| TypeScript | mit | sindresorhus/symbol-observable | ---
+++
@@ -3,6 +3,6 @@
declare global {
export interface SymbolConstructor {
- readonly observable: unique symbol;
+ readonly observable: symbol;
}
} |
d86314b658349e4537025973aa10468145eff9ef | src/nerdbank-gitversioning.npm/ts/asyncprocess.ts | src/nerdbank-gitversioning.npm/ts/asyncprocess.ts | import {exec} from 'child_process';
export function execAsync(command: string) {
return new Promise<any>(
(resolve, reject) => exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
}));
};
| import {exec} from 'child_process';
export interface IExecAsyncResult {
stdout: string;
stderr: string;
}
export function execAsync(command: string) {
return new Promise<IExecAsyncResult>(
(resolve, reject) => exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout: stdout, stderr: stderr });
}
}));
};
| Add interface for execAsync result | Add interface for execAsync result
| TypeScript | mit | AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning | ---
+++
@@ -1,7 +1,12 @@
import {exec} from 'child_process';
+export interface IExecAsyncResult {
+ stdout: string;
+ stderr: string;
+}
+
export function execAsync(command: string) {
- return new Promise<any>(
+ return new Promise<IExecAsyncResult>(
(resolve, reject) => exec(command, (error, stdout, stderr) => {
if (error) {
reject(error); |
6cc81ab0eb748f9262472bdc6844daac8492e5dd | packages/@sanity/components/src/portal/context.ts | packages/@sanity/components/src/portal/context.ts | import {createContext} from 'react'
export interface PortalContextInterface {
element: HTMLElement
}
export const PortalContext = createContext<PortalContextInterface | null>(null)
| import {createContext} from 'react'
export interface PortalContextInterface {
element: HTMLElement
}
let globalElement: HTMLDivElement | null = null
const defaultContextValue = {
get element() {
if (globalElement) return globalElement
globalElement = document.createElement('div')
globalElement.setAttribute('data-portal', 'default')
document.body.appendChild(globalElement)
return globalElement
}
}
export const PortalContext = createContext<PortalContextInterface>(defaultContextValue)
| Add default value for PortalContext | [components] Add default value for PortalContext
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -4,4 +4,16 @@
element: HTMLElement
}
-export const PortalContext = createContext<PortalContextInterface | null>(null)
+let globalElement: HTMLDivElement | null = null
+
+const defaultContextValue = {
+ get element() {
+ if (globalElement) return globalElement
+ globalElement = document.createElement('div')
+ globalElement.setAttribute('data-portal', 'default')
+ document.body.appendChild(globalElement)
+ return globalElement
+ }
+}
+
+export const PortalContext = createContext<PortalContextInterface>(defaultContextValue) |
18ca6ebffbb94a1430a4a924d99bbcba9051b857 | packages/react-day-picker/src/components/Table/Table.tsx | packages/react-day-picker/src/components/Table/Table.tsx | import * as React from 'react';
import { Head, Row } from '../../components';
import { useDayPicker } from '../../hooks';
import { UIElement } from '../../types';
import { getWeeks } from './utils/getWeeks';
/**
* The props for the [[Table]] component.
*/
export interface TableProps {
/** The month used to render the table */
displayMonth: Date;
}
/**
* Render the table with the calendar.
*/
export function Table(props: TableProps): JSX.Element {
const { locale, fixedWeeks, classNames, styles, hideHead } = useDayPicker();
const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks });
return (
<table
className={classNames?.[UIElement.Table]}
style={styles?.[UIElement.Table]}
>
{!hideHead && <Head />}
<tbody
className={classNames?.[UIElement.TBody]}
style={styles?.[UIElement.TBody]}
>
{Object.keys(weeks).map((weekNumber) => (
<Row
displayMonth={props.displayMonth}
key={weekNumber}
dates={weeks[weekNumber]}
weekNumber={Number(weekNumber)}
/>
))}
</tbody>
</table>
);
}
| import * as React from 'react';
import { Head } from '../../components';
import { useDayPicker } from '../../hooks';
import { UIElement } from '../../types';
import { getWeeks } from './utils/getWeeks';
/**
* The props for the [[Table]] component.
*/
export interface TableProps {
/** The month used to render the table */
displayMonth: Date;
}
/**
* Render the table with the calendar.
*/
export function Table(props: TableProps): JSX.Element {
const {
locale,
fixedWeeks,
classNames,
styles,
hideHead,
components: { Row }
} = useDayPicker();
const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks });
return (
<table
className={classNames?.[UIElement.Table]}
style={styles?.[UIElement.Table]}
>
{!hideHead && <Head />}
<tbody
className={classNames?.[UIElement.TBody]}
style={styles?.[UIElement.TBody]}
>
{Object.keys(weeks).map((weekNumber) => (
<Row
displayMonth={props.displayMonth}
key={weekNumber}
dates={weeks[weekNumber]}
weekNumber={Number(weekNumber)}
/>
))}
</tbody>
</table>
);
}
| Enable use of Row custom component | Enable use of Row custom component
| TypeScript | mit | gpbl/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -1,6 +1,6 @@
import * as React from 'react';
-import { Head, Row } from '../../components';
+import { Head } from '../../components';
import { useDayPicker } from '../../hooks';
import { UIElement } from '../../types';
import { getWeeks } from './utils/getWeeks';
@@ -17,7 +17,14 @@
* Render the table with the calendar.
*/
export function Table(props: TableProps): JSX.Element {
- const { locale, fixedWeeks, classNames, styles, hideHead } = useDayPicker();
+ const {
+ locale,
+ fixedWeeks,
+ classNames,
+ styles,
+ hideHead,
+ components: { Row }
+ } = useDayPicker();
const weeks = getWeeks(props.displayMonth, { locale, fixedWeeks });
return ( |
0b04dc293b7d9bb203d533767742f20cb9a87283 | source/WebApp/scripts/shared.ts | source/WebApp/scripts/shared.ts | import path from 'path';
import execa from 'execa';
export const inputRoot = path.resolve(__dirname, '..');
export const outputSharedRoot = `${inputRoot}/public`;
const outputVersion = process.env.NODE_ENV === 'ci'
? (process.env.SHARPLAB_WEBAPP_BUILD_VERSION ?? (() => { throw 'SHARPLAB_WEBAPP_BUILD_VERSION was not provided.'; })())
: Date.now();
export const outputVersionRoot = `${outputSharedRoot}/${outputVersion}`;
// TODO: expose in oldowan
export const exec2 = (command: string, args: ReadonlyArray<string>, options?: {
env?: NodeJS.ProcessEnv;
}) => execa(command, args, {
preferLocal: true,
stdout: process.stdout,
stderr: process.stderr,
env: options?.env
}); | import path from 'path';
import execa from 'execa';
export const inputRoot = path.resolve(__dirname, '..');
export const outputSharedRoot = `${inputRoot}/public`;
const outputVersion = process.env.NODE_ENV === 'production'
? (process.env.SHARPLAB_WEBAPP_BUILD_VERSION ?? (() => { throw 'SHARPLAB_WEBAPP_BUILD_VERSION was not provided.'; })())
: Date.now();
export const outputVersionRoot = `${outputSharedRoot}/${outputVersion}`;
// TODO: expose in oldowan
export const exec2 = (command: string, args: ReadonlyArray<string>, options?: {
env?: NodeJS.ProcessEnv;
}) => execa(command, args, {
preferLocal: true,
stdout: process.stdout,
stderr: process.stderr,
env: options?.env
}); | Fix WebApp version folder name | Fix WebApp version folder name
| TypeScript | bsd-2-clause | ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab | ---
+++
@@ -4,7 +4,7 @@
export const inputRoot = path.resolve(__dirname, '..');
export const outputSharedRoot = `${inputRoot}/public`;
-const outputVersion = process.env.NODE_ENV === 'ci'
+const outputVersion = process.env.NODE_ENV === 'production'
? (process.env.SHARPLAB_WEBAPP_BUILD_VERSION ?? (() => { throw 'SHARPLAB_WEBAPP_BUILD_VERSION was not provided.'; })())
: Date.now();
export const outputVersionRoot = `${outputSharedRoot}/${outputVersion}`; |
988927c8fb25e457a0564d2c7956138c4c2259ed | src/crystalConfiguration.ts | src/crystalConfiguration.ts | 'use strict';
export const crystalConfiguration = {
// Add indentation rules for crystal language
indentationRules: {
// /^.*(
// ((
// ((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|
// (end\.)
// ).*)|
// ((begin|else|ensure|do|rescue)\b)
// )
// $/
increaseIndentPattern: /^.*(((((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|(end\.)).*)|((begin|else|ensure|do|rescue)\b))$/,
// /^\s*(
// ((rescue|ensure|else)\b)|
// (elsif\s.*)|
// (end(\..*|\b))
// )
// $/
decreaseIndentPattern: /^\s*(((rescue|ensure|else)\b)|(elsif\s.*)|(end(\..*|\b)))$/
}
} | 'use strict'
import * as vscode from "vscode"
// Add crystal process limit
export class CrystalLimit {
static processes = 0
static limit() {
let config = vscode.workspace.getConfiguration('crystal-lang')
return config['processesLimit']
}
}
// Add current workspace to crystal path
const CRENV = Object.create(process.env)
CRENV.CRYSTAL_PATH = `${vscode.workspace.rootPath}/lib:/usr/lib/crystal`
export const ENV = CRENV
export const crystalConfiguration = {
// Add indentation rules for crystal language
indentationRules: {
// /^[^#]*(
// ((
// ((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|
// (end\.)
// ).*)|
// ((begin|else|ensure|do|rescue)\b)
// )
// $/
increaseIndentPattern: /^[^#]*(((((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|(end\.)).*)|((begin|else|ensure|do|rescue)\b))$/,
// /^\s*(
// ((rescue|ensure|else)\b)|
// (elsif\s.*)|
// (end(\..*|\b))
// )
// $/
decreaseIndentPattern: /^\s*(((rescue|ensure|else)\b)|(elsif\s.*)|(end(\..*|\b)))$/
}
} | Add processes limit and CRYSTAL_PATH | Add processes limit and CRYSTAL_PATH
| TypeScript | mit | faustinoaq/vscode-crystal-lang,faustinoaq/vscode-crystal-lang | ---
+++
@@ -1,9 +1,24 @@
-'use strict';
+'use strict'
+import * as vscode from "vscode"
+
+// Add crystal process limit
+export class CrystalLimit {
+ static processes = 0
+ static limit() {
+ let config = vscode.workspace.getConfiguration('crystal-lang')
+ return config['processesLimit']
+ }
+}
+
+// Add current workspace to crystal path
+const CRENV = Object.create(process.env)
+CRENV.CRYSTAL_PATH = `${vscode.workspace.rootPath}/lib:/usr/lib/crystal`
+export const ENV = CRENV
export const crystalConfiguration = {
// Add indentation rules for crystal language
indentationRules: {
- // /^.*(
+ // /^[^#]*(
// ((
// ((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|
// (end\.)
@@ -11,7 +26,7 @@
// ((begin|else|ensure|do|rescue)\b)
// )
// $/
- increaseIndentPattern: /^.*(((((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|(end\.)).*)|((begin|else|ensure|do|rescue)\b))$/,
+ increaseIndentPattern: /^[^#]*(((((if|elsif|lib|fun|module|struct|class|def|macro|do|rescue)\s)|(end\.)).*)|((begin|else|ensure|do|rescue)\b))$/,
// /^\s*(
// ((rescue|ensure|else)\b)|
// (elsif\s.*)| |
730924633f7c77d6814e987f32667f29959ed0fd | test/AbstractVueTransitionController.spec.ts | test/AbstractVueTransitionController.spec.ts | import {} from 'mocha';
import { getApplication, getTransitionController } from './util/app/App';
describe('AbstractTransitionControllerSpec', () => {
// TODO: Create tests
});
| import { TransitionDirection } from 'transition-controller';
import {} from 'mocha';
import { expect } from 'chai';
import { getMountedComponent } from './util/App';
import { getApplication, getTransitionController } from './util/app/App';
import ChildComponentA from './util/ChildComponentA/ChildComponentA';
import IAbstractTransitionComponent from 'lib/interface/IAbstractTransitionComponent';
describe('AbstractTransitionControllerSpec', () => {
describe('getSubTimelineByComponent', () => {
it('should get the subtimeline by the component reference', () => {
const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
return component.$_allComponentsReady
.then(() => component.transitionController.getSubTimelineByComponent('ChildComponentB'))
.then(component => expect(component).to.not.be.undefined)
});
it('should get the subtimeline by the component instance', () => {
const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
return component.$_allComponentsReady
.then(() => component.transitionController.getSubTimelineByComponent(component.$refs.ChildComponentB))
.then(component => expect(component).to.not.be.undefined)
});
it('should get the subtimeline by the element', () => {
const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
return component.$_allComponentsReady
.then(() => component.transitionController.getSubTimelineByComponent(component.$refs.ChildComponentB.$el))
.then(component => expect(component).to.not.be.undefined)
});
it('should get the subtimeline by the component reference, in the in direction', () => {
const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
return component.$_allComponentsReady
.then(() => component.transitionController.getSubTimelineByComponent('ChildComponentB', TransitionDirection.IN))
.then(component => expect(component).to.not.be.undefined)
});
it('should try to get the subtimeline but fail because it does not exist', () => {
const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
return component.$_allComponentsReady
.then(() => expect(() => component.transitionController.getSubTimelineByComponent('Foo')).to.throw(Error))
});
});
});
| Add tests for the AbstractVueTransitionController | Add tests for the AbstractVueTransitionController
| TypeScript | mit | larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component,larsvanbraam/vue-transition-component | ---
+++
@@ -1,6 +1,46 @@
+import { TransitionDirection } from 'transition-controller';
import {} from 'mocha';
+import { expect } from 'chai';
+import { getMountedComponent } from './util/App';
import { getApplication, getTransitionController } from './util/app/App';
+import ChildComponentA from './util/ChildComponentA/ChildComponentA';
+import IAbstractTransitionComponent from 'lib/interface/IAbstractTransitionComponent';
describe('AbstractTransitionControllerSpec', () => {
- // TODO: Create tests
+ describe('getSubTimelineByComponent', () => {
+
+ it('should get the subtimeline by the component reference', () => {
+ const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
+ return component.$_allComponentsReady
+ .then(() => component.transitionController.getSubTimelineByComponent('ChildComponentB'))
+ .then(component => expect(component).to.not.be.undefined)
+ });
+
+ it('should get the subtimeline by the component instance', () => {
+ const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
+ return component.$_allComponentsReady
+ .then(() => component.transitionController.getSubTimelineByComponent(component.$refs.ChildComponentB))
+ .then(component => expect(component).to.not.be.undefined)
+ });
+
+ it('should get the subtimeline by the element', () => {
+ const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
+ return component.$_allComponentsReady
+ .then(() => component.transitionController.getSubTimelineByComponent(component.$refs.ChildComponentB.$el))
+ .then(component => expect(component).to.not.be.undefined)
+ });
+
+ it('should get the subtimeline by the component reference, in the in direction', () => {
+ const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
+ return component.$_allComponentsReady
+ .then(() => component.transitionController.getSubTimelineByComponent('ChildComponentB', TransitionDirection.IN))
+ .then(component => expect(component).to.not.be.undefined)
+ });
+
+ it('should try to get the subtimeline but fail because it does not exist', () => {
+ const component = <IAbstractTransitionComponent>getMountedComponent(ChildComponentA);
+ return component.$_allComponentsReady
+ .then(() => expect(() => component.transitionController.getSubTimelineByComponent('Foo')).to.throw(Error))
+ });
+ });
}); |
d51401210b8ac4bba52f5b8d090110999ad74a96 | app/src/lib/git/reset.ts | app/src/lib/git/reset.ts | import { git } from './core'
import { Repository } from '../../models/repository'
import { assertNever } from '../fatal-error'
/** The reset modes which are supported. */
export const enum GitResetMode {
Hard = 0,
Soft,
Mixed,
}
function resetModeToFlag(mode: GitResetMode): string {
switch (mode) {
case GitResetMode.Hard: return '--hard'
case GitResetMode.Mixed: return '--mixed'
case GitResetMode.Soft: return '--soft'
default: return assertNever(mode, `Unknown reset mode: ${mode}`)
}
}
/** Reset with the mode to the ref. */
export async function reset(repository: Repository, mode: GitResetMode, ref: string): Promise<true> {
const modeFlag = resetModeToFlag(mode)
await git([ 'reset', modeFlag, ref, '--' ], repository.path, 'reset')
return true
}
/** Unstage all paths. */
export async function unstageAll(repository: Repository): Promise<true> {
await git([ 'reset', '--', '.' ], repository.path, 'unstage')
return true
}
| import { git } from './core'
import { Repository } from '../../models/repository'
import { assertNever } from '../fatal-error'
/** The reset modes which are supported. */
export const enum GitResetMode {
Hard = 0,
Soft,
Mixed,
}
function resetModeToFlag(mode: GitResetMode): string {
switch (mode) {
case GitResetMode.Hard: return '--hard'
case GitResetMode.Mixed: return '--mixed'
case GitResetMode.Soft: return '--soft'
default: return assertNever(mode, `Unknown reset mode: ${mode}`)
}
}
/** Reset with the mode to the ref. */
export async function reset(repository: Repository, mode: GitResetMode, ref: string): Promise<true> {
const modeFlag = resetModeToFlag(mode)
await git([ 'reset', modeFlag, ref, '--' ], repository.path, 'reset')
return true
}
/** Unstage all paths. */
export async function unstageAll(repository: Repository): Promise<true> {
await git([ 'reset', '--', '.' ], repository.path, 'unstageAll')
return true
}
| Update the git function name | Update the git function name
| TypeScript | mit | hjobrien/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,BugTesterTest/desktops,artivilla/desktop,shiftkey/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,desktop/desktop,kactus-io/kactus,gengjiawen/desktop,desktop/desktop,shiftkey/desktop,BugTesterTest/desktops,kactus-io/kactus,gengjiawen/desktop,hjobrien/desktop,hjobrien/desktop,BugTesterTest/desktops,kactus-io/kactus,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,gengjiawen/desktop,shiftkey/desktop,BugTesterTest/desktops,say25/desktop,artivilla/desktop,gengjiawen/desktop,desktop/desktop,hjobrien/desktop | ---
+++
@@ -27,6 +27,6 @@
/** Unstage all paths. */
export async function unstageAll(repository: Repository): Promise<true> {
- await git([ 'reset', '--', '.' ], repository.path, 'unstage')
+ await git([ 'reset', '--', '.' ], repository.path, 'unstageAll')
return true
} |
fb3a21a92a6193dcf5309738c7aab90faf29c1f5 | src/maas.ts | src/maas.ts | import * as express from "express";
import * as bodyParser from "body-parser";
import * as http from "http";
import ConfigurationChooser from "./config/configurationChooser";
import Configuration from "./config/configuration";
import * as routes from "./routes/routerFacade";
// Initializing app
let app : express.Express = express();
let configuration : Configuration = ConfigurationChooser.getConfig();
// Allow to get data from body in JSON format
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes' require
app.use("/api", routes);
// Starting the server
app.set("port", process.env.PORT || 3000);
let server : http.Server = app.listen(app.get("port"), function () : void {
console.log("Express server is listening on port " + server.address().port +
" in " + configuration.getEnvName() + " environment.");
});
| import * as express from "express";
import * as bodyParser from "body-parser";
import * as http from "http";
import * as helmet from "helmet";
import ConfigurationChooser from "./config/configurationChooser";
import Configuration from "./config/configuration";
import * as routes from "./routes/routerFacade";
// Initializing app
let app : express.Express = express();
let configuration : Configuration = ConfigurationChooser.getConfig();
// Allow to get data from body in JSON format
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Set helmet for security checks
app.use(helmet());
app.use(function (req : express.Request,
res : express.Response,
next : express.NextFunction) : void {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Routes' require
app.use("/api", routes);
// Starting the server
app.set("port", process.env.PORT || 3000);
let server : http.Server = app.listen(app.get("port"), function () : void {
console.log("Express server is listening on port " + server.address().port +
" in " + configuration.getEnvName() + " environment.");
});
| Add helment and cross platform | Add helment and cross platform
| TypeScript | mit | BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS,BugBusterSWE/MaaS | ---
+++
@@ -1,6 +1,7 @@
import * as express from "express";
import * as bodyParser from "body-parser";
import * as http from "http";
+import * as helmet from "helmet";
import ConfigurationChooser from "./config/configurationChooser";
import Configuration from "./config/configuration";
import * as routes from "./routes/routerFacade";
@@ -13,6 +14,18 @@
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
+// Set helmet for security checks
+app.use(helmet());
+
+app.use(function (req : express.Request,
+ res : express.Response,
+ next : express.NextFunction) : void {
+ res.header("Access-Control-Allow-Origin", "*");
+ res.header("Access-Control-Allow-Headers",
+ "Origin, X-Requested-With, Content-Type, Accept");
+ next();
+});
+
// Routes' require
app.use("/api", routes);
|
d884107059024291c1da43e7886f04a5dc102e6e | src/app/services/app.service.ts | src/app/services/app.service.ts | import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
_state: InternalStateType = {};
constructor() {
}
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` directly');
}
get(prop?: any) {
// use our state getter for the clone
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
set(prop: string, value: any) {
// internally mutate our state
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
// simple object clone
return JSON.parse(JSON.stringify(object));
}
}
| import { Injectable } from '@angular/core';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
_state: InternalStateType = {};
constructor() {
}
// already return a clone of the current state
get state() {
return this._state = this._clone(this._state);
}
// never allow mutation
set state(value) {
throw new Error('do not mutate the `.state` directly');
}
get(prop?: string) {
// use our state getter for the clone
const state = this.state;
return state[prop];
}
set(prop: string, value: any) {
// internally mutate our state
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
// simple object clone
return JSON.parse(JSON.stringify(object));
}
}
| Return just the prop even if it doesn't exist, not the full state | Return just the prop even if it doesn't exist, not the full state
| TypeScript | mit | johndi9/ng2-web,johndi9/ng2-web,johndi9/ng2-web | ---
+++
@@ -21,10 +21,10 @@
throw new Error('do not mutate the `.state` directly');
}
- get(prop?: any) {
+ get(prop?: string) {
// use our state getter for the clone
const state = this.state;
- return state.hasOwnProperty(prop) ? state[prop] : state;
+ return state[prop];
}
set(prop: string, value: any) { |
00d31f8c38d21473fabba7188f5ae6f9d52594e0 | test/sample.ts | test/sample.ts | import test from 'ava'
test('1 + 2 = 3', t => {
t.is(1 + 2, 3)
})
| import test from 'ava'
function add (x: number, y: number): number {
return x + y
}
test('add(1, 2) = 3', t => {
t.is(add(1, 2), 3)
})
| Add some types to test case | Add some types to test case
| TypeScript | mit | andywer/ava-ts,andywer/ava-ts | ---
+++
@@ -1,5 +1,9 @@
import test from 'ava'
-test('1 + 2 = 3', t => {
- t.is(1 + 2, 3)
+function add (x: number, y: number): number {
+ return x + y
+}
+
+test('add(1, 2) = 3', t => {
+ t.is(add(1, 2), 3)
}) |
750a159a6a7f6ac22ff6239b37019f42f554dc1d | packages/components/containers/topBanners/TopBanner.tsx | packages/components/containers/topBanners/TopBanner.tsx | import { ReactNode } from 'react';
import { c } from 'ttag';
import { classnames } from '../../helpers';
import Icon from '../../components/icon/Icon';
import { Button } from '../../components';
interface Props {
children: ReactNode;
className?: string;
onClose?: () => void;
}
const TopBanner = ({ children, className, onClose }: Props) => {
return (
<div
className={classnames([
'flex flex-item-noshrink flex-nowrap text-center relative text-bold no-print',
className,
])}
>
<div className="flex-item-fluid p0-5">{children}</div>
{onClose ? (
<Button
icon
shape="ghost"
className="flex-item-noshrink"
onClick={onClose}
title={c('Action').t`Close this banner`}
>
<Icon name="xmark" alt={c('Action').t`Close this banner`} />
</Button>
) : null}
</div>
);
};
export default TopBanner;
| import { ReactNode } from 'react';
import { c } from 'ttag';
import { classnames } from '../../helpers';
import Icon from '../../components/icon/Icon';
import { Button } from '../../components';
interface Props {
children: ReactNode;
className?: string;
onClose?: () => void;
}
const TopBanner = ({ children, className, onClose }: Props) => {
return (
<div
className={classnames([
'flex flex-item-noshrink flex-nowrap text-center relative text-bold no-print',
className,
])}
>
<div className="flex-item-fluid p0-5">{children}</div>
{onClose ? (
<Button
icon
shape="ghost"
className="flex-item-noshrink rounded-none"
onClick={onClose}
title={c('Action').t`Close this banner`}
>
<Icon name="xmark" alt={c('Action').t`Close this banner`} />
</Button>
) : null}
</div>
);
};
export default TopBanner;
| Fix - No rounded top banner button | Fix - No rounded top banner button
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -24,7 +24,7 @@
<Button
icon
shape="ghost"
- className="flex-item-noshrink"
+ className="flex-item-noshrink rounded-none"
onClick={onClose}
title={c('Action').t`Close this banner`}
> |
328f584d5205e5614a774cd9f4c9f30b32faba94 | src/index.tsx | src/index.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
declare var require;
const DevTools = require('mobx-react-devtools').default; // Use import see #6, add typings
class AppState {
@observable timer = 0;
constructor() {
setInterval(() => {
appState.timer += 1;
}, 1000);
}
resetTimer() {
this.timer = 0;
}
}
@observer
class TimerView extends React.Component<{appState: AppState}, {}> {
render() {
return (
<div>
<button onClick={this.onReset}>
Seconds passed: {this.props.appState.timer}
</button>
<DevTools />
</div>
);
}
onReset = () => {
this.props.appState.resetTimer();
}
};
const appState = new AppState();
ReactDOM.render(<TimerView appState={appState} />, document.getElementById('root')); | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
declare var require;
const DevTools = require('mobx-react-devtools').default; // Use import see #6, add typings
class AppState {
@observable timer = 0;
constructor() {
setInterval(() => {
this.timer += 1;
}, 1000);
}
resetTimer() {
this.timer = 0;
}
}
@observer
class TimerView extends React.Component<{appState: AppState}, {}> {
render() {
return (
<div>
<button onClick={this.onReset}>
Seconds passed: {this.props.appState.timer}
</button>
<DevTools />
</div>
);
}
onReset = () => {
this.props.appState.resetTimer();
}
};
const appState = new AppState();
ReactDOM.render(<TimerView appState={appState} />, document.getElementById('root'));
| Use `this` in AppState constructor for updating timer | Use `this` in AppState constructor for updating timer | TypeScript | mit | mweststrate/mobservable-react-typescript,mweststrate/mobservable-react-typescript,mweststrate/mobservable-react-typescript | ---
+++
@@ -11,7 +11,7 @@
constructor() {
setInterval(() => {
- appState.timer += 1;
+ this.timer += 1;
}, 1000);
}
|
0f3444b4c62a205f045bbd721964dad8bea9f850 | server/custom_typings/scrypt.d.ts | server/custom_typings/scrypt.d.ts | declare module 'scrypt' {
interface ErrorCallback<O> {
(err, obj: O);
}
interface ParamsObject {}
export function params(maxtime: number, maxmem?: number, max_memefrac?: number, cb?: ErrorCallback<ParamsObject>);
export function params(maxtime: number, maxmem?: number, max_memefrac?: number): Promise<ParamsObject>;
export function paramsSync(maxtime: number, maxmem?: number, max_memefrac?: number): ParamsObject;
export function verifyKdf(kdf: Buffer, key: string | Buffer, cb: ErrorCallback<boolean>);
export function verifyKdf(kdf: Buffer, key: string | Buffer): Promise<boolean>;
export function verifyKdfSync(kdf: Buffer, key: string | Buffer): boolean;
export function kdf(key: string | Buffer, paramsObject: ParamsObject, cb: ErrorCallback<Buffer>);
export function kdf(key: string | Buffer, paramsObject: ParamsObject): Promise<Buffer>;
export function kdfSync(key: string | Buffer, paramsObject: ParamsObject): Buffer;
export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer, cb: ErrorCallback<Buffer>);
export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Promise<Buffer>;
export function hashSync(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Buffer;
}
| declare module 'scrypt' {
interface ErrorCallback<O> {
(err: any, obj: O): void;
}
interface ParamsObject {}
export function params(maxtime: number, maxmem?: number, max_memefrac?: number, cb?: ErrorCallback<ParamsObject>): void;
export function params(maxtime: number, maxmem?: number, max_memefrac?: number): Promise<ParamsObject>;
export function paramsSync(maxtime: number, maxmem?: number, max_memefrac?: number): ParamsObject;
export function verifyKdf(kdf: Buffer, key: string | Buffer, cb: ErrorCallback<boolean>): void;
export function verifyKdf(kdf: Buffer, key: string | Buffer): Promise<boolean>;
export function verifyKdfSync(kdf: Buffer, key: string | Buffer): boolean;
export function kdf(key: string | Buffer, paramsObject: ParamsObject, cb: ErrorCallback<Buffer>): void;
export function kdf(key: string | Buffer, paramsObject: ParamsObject): Promise<Buffer>;
export function kdfSync(key: string | Buffer, paramsObject: ParamsObject): Buffer;
export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer, cb: ErrorCallback<Buffer>): void;
export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Promise<Buffer>;
export function hashSync(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Buffer;
}
| Fix compile error on server after rebase. | Fix compile error on server after rebase.
| TypeScript | mit | GreenPix/dilia,Nemikolh/dilia,GreenPix/dilia,GreenPix/dilia,Nemikolh/dilia,GreenPix/editor,GreenPix/editor,GreenPix/editor,GreenPix/dilia,GreenPix/editor,Nemikolh/dilia,Nemikolh/dilia | ---
+++
@@ -1,24 +1,24 @@
declare module 'scrypt' {
interface ErrorCallback<O> {
- (err, obj: O);
+ (err: any, obj: O): void;
}
interface ParamsObject {}
- export function params(maxtime: number, maxmem?: number, max_memefrac?: number, cb?: ErrorCallback<ParamsObject>);
+ export function params(maxtime: number, maxmem?: number, max_memefrac?: number, cb?: ErrorCallback<ParamsObject>): void;
export function params(maxtime: number, maxmem?: number, max_memefrac?: number): Promise<ParamsObject>;
export function paramsSync(maxtime: number, maxmem?: number, max_memefrac?: number): ParamsObject;
- export function verifyKdf(kdf: Buffer, key: string | Buffer, cb: ErrorCallback<boolean>);
+ export function verifyKdf(kdf: Buffer, key: string | Buffer, cb: ErrorCallback<boolean>): void;
export function verifyKdf(kdf: Buffer, key: string | Buffer): Promise<boolean>;
export function verifyKdfSync(kdf: Buffer, key: string | Buffer): boolean;
- export function kdf(key: string | Buffer, paramsObject: ParamsObject, cb: ErrorCallback<Buffer>);
+ export function kdf(key: string | Buffer, paramsObject: ParamsObject, cb: ErrorCallback<Buffer>): void;
export function kdf(key: string | Buffer, paramsObject: ParamsObject): Promise<Buffer>;
export function kdfSync(key: string | Buffer, paramsObject: ParamsObject): Buffer;
- export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer, cb: ErrorCallback<Buffer>);
+ export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer, cb: ErrorCallback<Buffer>): void;
export function hash(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Promise<Buffer>;
export function hashSync(key: string | Buffer, paramsObject: ParamsObject, output_length: number, salt: string | Buffer): Buffer;
} |
683a01555d5081876624143c193d48b06798d4b2 | packages/lesswrong/server/emails/emailCron.ts | packages/lesswrong/server/emails/emailCron.ts | import { addCronJob } from '../cronUtil';
export const releaseEmailBatches = ({now}) => {
}
addCronJob({
name: "Hourly notification batch",
schedule(parser) {
return parser.cron('0 ? * * *');
},
job() {
console.log("Hourly notification batch"); //eslint-disable-line no-console
releaseEmailBatches({ now: new Date() });
console.log("Done with hourly notification batch"); //eslint-disable-line no-console
}
});
| import { addCronJob } from '../cronUtil';
export const releaseEmailBatches = ({now}) => {
}
addCronJob({
name: "Hourly notification batch",
schedule(parser) {
return parser.cron('0 ? * * *');
},
job() {
releaseEmailBatches({ now: new Date() });
}
});
| Remove a duplicate console log for cronjob start/end | Remove a duplicate console log for cronjob start/end
| TypeScript | mit | Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope | ---
+++
@@ -9,8 +9,6 @@
return parser.cron('0 ? * * *');
},
job() {
- console.log("Hourly notification batch"); //eslint-disable-line no-console
releaseEmailBatches({ now: new Date() });
- console.log("Done with hourly notification batch"); //eslint-disable-line no-console
}
}); |
62e2e731991a1f6bd530d1d48607a65bfffd5757 | src/Parsing/Inline/MediaConventions.ts | src/Parsing/Inline/MediaConventions.ts | import { Convention } from './Convention'
import { TokenMeaning } from './Token'
import { MediaSyntaxNodeType } from '../../SyntaxNodes/MediaSyntaxNode'
import { MediaConvention } from './MediaConvention'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
const AUDIO = new MediaConvention('audio', AudioNode, TokenMeaning.AudioStartAndAudioDescription, TokenMeaning.AudioUrlAndAudioEnd)
const IMAGE = new MediaConvention('image', ImageNode, TokenMeaning.ImageStartAndAudioDescription, TokenMeaning.ImageUrlAndAudioEnd)
const VIDEO = new MediaConvention('video', VideoNode, TokenMeaning.VideoStartAndAudioDescription, TokenMeaning.VideoUrlAndAudioEnd)
export {
AUDIO,
IMAGE,
VIDEO
}
| import { MediaConvention } from './MediaConvention'
import { AudioToken } from './Tokens/AudioToken'
import { ImageToken } from './Tokens/ImageToken'
import { VideoToken } from './Tokens/VideoToken'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
const AUDIO = new MediaConvention('audio', AudioNode, AudioToken)
const IMAGE = new MediaConvention('image', ImageNode, ImageToken)
const VIDEO = new MediaConvention('video', VideoNode, VideoToken)
export {
AUDIO,
IMAGE,
VIDEO
}
| Update media cons. to use new token types | [Broken] Update media cons. to use new token types
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,14 +1,14 @@
-import { Convention } from './Convention'
-import { TokenMeaning } from './Token'
-import { MediaSyntaxNodeType } from '../../SyntaxNodes/MediaSyntaxNode'
import { MediaConvention } from './MediaConvention'
+import { AudioToken } from './Tokens/AudioToken'
+import { ImageToken } from './Tokens/ImageToken'
+import { VideoToken } from './Tokens/VideoToken'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
-const AUDIO = new MediaConvention('audio', AudioNode, TokenMeaning.AudioStartAndAudioDescription, TokenMeaning.AudioUrlAndAudioEnd)
-const IMAGE = new MediaConvention('image', ImageNode, TokenMeaning.ImageStartAndAudioDescription, TokenMeaning.ImageUrlAndAudioEnd)
-const VIDEO = new MediaConvention('video', VideoNode, TokenMeaning.VideoStartAndAudioDescription, TokenMeaning.VideoUrlAndAudioEnd)
+const AUDIO = new MediaConvention('audio', AudioNode, AudioToken)
+const IMAGE = new MediaConvention('image', ImageNode, ImageToken)
+const VIDEO = new MediaConvention('video', VideoNode, VideoToken)
export {
AUDIO, |
be441b4ce3fef5966243b1cd1d5d5e44a0bb372e | api/hooks/archive-item.ts | api/hooks/archive-item.ts | import { decrementByDot, getByDot, setByDot } from './helper';
/**
* updates the unlock countdown on a stat
* @export
* @returns
*/
export function updateUnlockCountdown(pathToStat = 'data.stat', pathToUser = 'stat.user') {
return hook => {
let stat = getByDot(hook, pathToStat);
let user = getByDot(hook, pathToUser);
// decrement countdown
let atZero = decrementByDot(stat, 'countdown');
if (atZero) {
// Awesome! unlock the next archive item
hook.app.service('archive-items').create({user});
// magic equation for calcuating item unlocks;
const nextUnlock = Math.floor(Math.pow(stat.answeredCount + 4, 2 / 3));
setByDot(stat, 'countdown', nextUnlock);
}
return hook;
};
}
| import { decrementByDot, getByDot, setByDot } from './helper';
/**
* updates the unlock countdown on a stat
* @export
* @returns
*/
export function updateUnlockCountdown(pathToStat = 'data.stat', pathToUser = 'params.user._id') {
return hook => {
let stat = getByDot(hook, pathToStat);
let user = getByDot(hook, pathToUser);
// decrement countdown
let atZero = decrementByDot(stat, 'countdown');
if (atZero) {
// Awesome! unlock the next archive item
hook.app.service('archive-items').create({user});
// magic equation for calcuating item unlocks;
const nextUnlock = Math.floor(Math.pow(stat.answeredCount + 4, 2 / 3));
setByDot(stat, 'countdown', nextUnlock);
}
return hook;
};
}
| Fix archive item user access | Fix archive item user access
| TypeScript | mit | knowledgeplazza/knowledgeplazza,knowledgeplazza/knowledgeplazza,knowledgeplazza/knowledgeplazza | ---
+++
@@ -5,7 +5,7 @@
* @export
* @returns
*/
-export function updateUnlockCountdown(pathToStat = 'data.stat', pathToUser = 'stat.user') {
+export function updateUnlockCountdown(pathToStat = 'data.stat', pathToUser = 'params.user._id') {
return hook => {
let stat = getByDot(hook, pathToStat);
let user = getByDot(hook, pathToUser); |
acfe809b3251a99449af591e85765046ce95d36d | logger.ts | logger.ts | import * as fs from 'fs';
class Logger {
fileName: string;
constructor(fileName: string) {
this.fileName = fileName;
}
appendLine(line: string) {
fs.appendFile(`./logs/${this.fileName}`, `${new Date()}: ${line}\n`, function (err) {
console.log(`Logger Error: ${err}`);
});
}
}
export default Logger; | import * as fs from 'fs';
class Logger {
fileName: string;
constructor(fileName: string) {
this.fileName = fileName;
}
appendLine(line: string) {
fs.appendFile(`logs/${this.fileName}`, `${new Date()}: ${line}\n`, function (err) {
if (err !== null) {
console.log(`Logger Error: ${err}`);
}
});
}
}
export default Logger; | Fix logging null to console | Fix logging null to console
| TypeScript | mit | popstarfreas/Dimensions,popstarfreas/Dimensions,popstarfreas/Dimensions | ---
+++
@@ -7,8 +7,10 @@
}
appendLine(line: string) {
- fs.appendFile(`./logs/${this.fileName}`, `${new Date()}: ${line}\n`, function (err) {
- console.log(`Logger Error: ${err}`);
+ fs.appendFile(`logs/${this.fileName}`, `${new Date()}: ${line}\n`, function (err) {
+ if (err !== null) {
+ console.log(`Logger Error: ${err}`);
+ }
});
}
} |
ca5b6cb4dae32b4a084fc356558bd828a4a3d5c6 | bokehjs/src/coffee/models/tools/toolbar_template.tsx | bokehjs/src/coffee/models/tools/toolbar_template.tsx | import * as DOM from "../../core/util/dom";
interface ToolbarProps {
location: "above" | "below" | "left" | "right";
sticky: "sticky" | "non-sticky";
logo?: "normal" | "grey";
}
export default (props: ToolbarProps): HTMLElement => {
let logo;
if (props.logo != null) {
const cls = props.logo === "grey" ? "bk-grey" : null;
logo = <a href="http://bokeh.pydata.org/" target="_blank" class={["bk-logo", "bk-logo-small", cls]}></a>
}
return (
<div class={[`bk-toolbar-${props.location}`, `bk-toolbar-${props.sticky}`]}>
<div class='bk-button-bar'>
{logo}
<div class='bk-button-bar-list' type="pan" />
<div class='bk-button-bar-list' type="scroll" />
<div class='bk-button-bar-list' type="pinch" />
<div class='bk-button-bar-list' type="tap" />
<div class='bk-button-bar-list' type="press" />
<div class='bk-button-bar-list' type="rotate" />
<div class='bk-button-bar-list' type="actions" />
<div class='bk-button-bar-list' type="inspectors" />
<div class='bk-button-bar-list' type="help" />
</div>
</div>
)
}
| import * as DOM from "../../core/util/dom";
interface ToolbarProps {
location: "above" | "below" | "left" | "right";
sticky: "sticky" | "non-sticky";
logo?: "normal" | "grey";
}
export default (props: ToolbarProps): HTMLElement => {
let logo;
if (props.logo != null) {
const cls = props.logo === "grey" ? "bk-grey" : null;
logo = <a href="http://bokeh.pydata.org/" target="_blank" class={["bk-logo", "bk-logo-small", cls]}></a>
}
return (
<div class={[`bk-toolbar-${props.location}`, `bk-toolbar-${props.sticky}`]}>
{logo}
<div class='bk-button-bar'>
<div class='bk-button-bar-list' type="pan" />
<div class='bk-button-bar-list' type="scroll" />
<div class='bk-button-bar-list' type="pinch" />
<div class='bk-button-bar-list' type="tap" />
<div class='bk-button-bar-list' type="press" />
<div class='bk-button-bar-list' type="rotate" />
<div class='bk-button-bar-list' type="actions" />
<div class='bk-button-bar-list' type="inspectors" />
<div class='bk-button-bar-list' type="help" />
</div>
</div>
)
}
| Fix toolbar's logo placement in toolbar's template | Fix toolbar's logo placement in toolbar's template
| TypeScript | bsd-3-clause | percyfal/bokeh,percyfal/bokeh,DuCorey/bokeh,dennisobrien/bokeh,philippjfr/bokeh,mindriot101/bokeh,aiguofer/bokeh,timsnyder/bokeh,timsnyder/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,draperjames/bokeh,ericmjl/bokeh,percyfal/bokeh,bokeh/bokeh,rs2/bokeh,azjps/bokeh,schoolie/bokeh,dennisobrien/bokeh,aiguofer/bokeh,jakirkham/bokeh,philippjfr/bokeh,timsnyder/bokeh,schoolie/bokeh,mindriot101/bokeh,jakirkham/bokeh,bokeh/bokeh,draperjames/bokeh,azjps/bokeh,jakirkham/bokeh,bokeh/bokeh,schoolie/bokeh,aiguofer/bokeh,dennisobrien/bokeh,Karel-van-de-Plassche/bokeh,aavanian/bokeh,rs2/bokeh,timsnyder/bokeh,bokeh/bokeh,azjps/bokeh,rs2/bokeh,percyfal/bokeh,stonebig/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,stonebig/bokeh,percyfal/bokeh,draperjames/bokeh,ericmjl/bokeh,schoolie/bokeh,azjps/bokeh,philippjfr/bokeh,rs2/bokeh,aavanian/bokeh,rs2/bokeh,jakirkham/bokeh,DuCorey/bokeh,mindriot101/bokeh,philippjfr/bokeh,philippjfr/bokeh,bokeh/bokeh,aavanian/bokeh,draperjames/bokeh,schoolie/bokeh,ericmjl/bokeh,DuCorey/bokeh,azjps/bokeh,Karel-van-de-Plassche/bokeh,ericmjl/bokeh,dennisobrien/bokeh,aavanian/bokeh,aiguofer/bokeh,dennisobrien/bokeh,jakirkham/bokeh,ericmjl/bokeh,mindriot101/bokeh,Karel-van-de-Plassche/bokeh,aavanian/bokeh,stonebig/bokeh,DuCorey/bokeh,stonebig/bokeh,aiguofer/bokeh,draperjames/bokeh | ---
+++
@@ -15,8 +15,8 @@
return (
<div class={[`bk-toolbar-${props.location}`, `bk-toolbar-${props.sticky}`]}>
+ {logo}
<div class='bk-button-bar'>
- {logo}
<div class='bk-button-bar-list' type="pan" />
<div class='bk-button-bar-list' type="scroll" />
<div class='bk-button-bar-list' type="pinch" /> |
9e67398e9a8ccbefa67af34f31bedc5fbb14ecb7 | client/network/network.ts | client/network/network.ts | /* Copyright 2019 Google Inc. 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 { WS } from "../../lib/websocket.ts";
import * as info from "../util/info.ts";
import * as time from "../../lib/adjustable_time.ts";
export const socket = WS.clientWrapper(`ws://${location.host}/websocket`);
let ready: () => void;
const readyPromise = new Promise<void>((r) => ready = r);
/**
* Initializes the connection with the server & sets up the network layer.
*/
export function init() {
function sendHello() {
socket.send("client-start", {
offset: info.virtualOffset,
rect: info.virtualRectNoBezel.serialize(),
});
}
// When we reconnect after a disconnection, we need to tell the server
// about who we are all over again.
socket.on("connect", sendHello);
// Install our time listener.
socket.on("time", time.adjustTimeByReference);
// Tell the server who we are.
sendHello();
ready();
}
export const whenReady = readyPromise;
| /* Copyright 2019 Google Inc. 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 { WS } from "../../lib/websocket.ts";
import * as info from "../util/info.ts";
import * as time from "../../lib/adjustable_time.ts";
export const socket = WS.clientWrapper(`ws://${location.host}/websocket`);
let ready: () => void;
const readyPromise = new Promise<void>((r) => ready = r);
/**
* Initializes the connection with the server & sets up the network layer.
*/
export function init() {
function sendHello() {
socket.send("client-start", {
offset: info.virtualOffset,
rect: info.virtualRectNoBezel.serialize(),
});
}
// When we reconnect after a disconnection, we need to tell the server
// about who we are all over again.
socket.on("connect", () => {
sendHello();
ready();
});
// Install our time listener.
socket.on("time", time.adjustTimeByReference);
}
export const whenReady = readyPromise;
| Fix a bug where we double-inited our clients. - Our new websockets are way more reliable, and so we don't need to send two start messages. | Fix a bug where we double-inited our clients.
- Our new websockets are way more reliable, and so we don't need to send two start messages.
| TypeScript | apache-2.0 | google/chicago-brick,google/chicago-brick,google/chicago-brick,google/chicago-brick | ---
+++
@@ -34,14 +34,13 @@
// When we reconnect after a disconnection, we need to tell the server
// about who we are all over again.
- socket.on("connect", sendHello);
+ socket.on("connect", () => {
+ sendHello();
+ ready();
+ });
// Install our time listener.
socket.on("time", time.adjustTimeByReference);
-
- // Tell the server who we are.
- sendHello();
- ready();
}
export const whenReady = readyPromise; |
1d8588de4cb627ba18778c5eae62f4d831e7730a | src/Test/Ast/InlineDocument/OutlineConventions.ts | src/Test/Ast/InlineDocument/OutlineConventions.ts | import { expect } from 'chai'
import Up from'../../../index'
import { InlineUpDocument } from'../../../SyntaxNodes/InlineUpDocument'
import { PlainTextNode } from'../../../SyntaxNodes/PlainTextNode'
context('Inline documents completely ignore outline conventions. This includes:', () => {
specify('Outline separation streaks', () => {
expect(Up.toInlineDocument('#~#~#~#~#')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('#~#~#~#~#')
]))
})
specify('Ordered lists', () => {
expect(Up.toInlineDocument('1) I agree.')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('1) I agree.')
]))
})
specify('Unordered lists', () => {
expect(Up.toInlineDocument('* Prices and participation may vary')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('* Prices and participation may vary')
]))
})
specify('Blockquotes', () => {
expect(Up.toInlineDocument('> o_o <')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('> o_o <')
]))
})
specify('Code blocks', () => {
expect(Up.toInlineDocument('```')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('```')
]))
})
})
| import { expect } from 'chai'
import Up from'../../../index'
import { InlineUpDocument } from'../../../SyntaxNodes/InlineUpDocument'
import { PlainTextNode } from'../../../SyntaxNodes/PlainTextNode'
context('Inline documents completely ignore outline conventions. This includes:', () => {
specify('Outline separation streaks', () => {
expect(Up.toInlineDocument('#~#~#~#~#')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('#~#~#~#~#')
]))
})
specify('Ordered lists', () => {
expect(Up.toInlineDocument('1) I agree.')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('1) I agree.')
]))
})
specify('Unordered lists', () => {
expect(Up.toInlineDocument('* Prices and participation may vary')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('* Prices and participation may vary')
]))
})
specify('Blockquotes', () => {
expect(Up.toInlineDocument('> o_o <')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('> o_o <')
]))
})
specify('Code blocks', () => {
expect(Up.toInlineDocument('`````````')).to.be.eql(
new InlineUpDocument([
new PlainTextNode('`````````')
]))
})
})
| Clarify test (make it clearly about code blocks) | Clarify test (make it clearly about code blocks)
| TypeScript | mit | start/up,start/up | ---
+++
@@ -34,9 +34,9 @@
})
specify('Code blocks', () => {
- expect(Up.toInlineDocument('```')).to.be.eql(
+ expect(Up.toInlineDocument('`````````')).to.be.eql(
new InlineUpDocument([
- new PlainTextNode('```')
+ new PlainTextNode('`````````')
]))
})
}) |
496f74f1cec0a388af945fe435b0785a6dba48ad | app/datastore/fake-mediastore.ts | app/datastore/fake-mediastore.ts | import {Observable} from "rxjs/Observable";
import {Mediastore} from 'idai-components-2/datastore';
export class FakeMediastore implements Mediastore {
private basePath: string = 'store/';
constructor() {
console.log("fake")
}
/**
* @param key the identifier for the data
* @param data the binary data to be stored
* @returns {Promise<any>} resolve -> (),
* reject -> the error message
*/
public create(key: string, data: any): Promise<any> {
return null;
}
/**
* @param key the identifier for the data
* @returns {Promise<any>} resolve -> (data), the data read with the key,
* reject -> the error message
*/
public read(key: string): Promise<any> {
return null;
}
/**
* @param key the identifier for the data
* @param data the binary data to be stored
* @returns {Promise<any>} resolve -> (),
* reject -> the error message
*/
public update(key: string, data: any): Promise<any> {
return null;
}
/**
* @param key the identifier for the data to be removed
* @returns {Promise<any>} resolve -> (),
* reject -> the error message
*/
public remove(key: string): Promise<any> {
return null;
}
/**
* Subscription enables clients to get notified
* when files get modified via one of the accessor
* methods defined here.
*/
public objectChangesNotifications(): Observable<File> {
return null;
}
} | import {Observable} from "rxjs/Observable";
import {Mediastore} from 'idai-components-2/datastore';
/**
* @author Daniel de Oliveira
*/
export class FakeMediastore implements Mediastore {
public create(): Promise<any> {
return new Promise<any>((resolve)=>{resolve();});
}
public read(): Promise<any> {
return new Promise<any>((resolve)=>{resolve();});
}
public update(): Promise<any> {
return new Promise<any>((resolve)=>{resolve();});
}
public remove(): Promise<any> {
return new Promise<any>((resolve)=>{resolve();});
}
public objectChangesNotifications(): Observable<File> {
return Observable.create( () => {});
}
} | Return values as specified to prevent 'method of undefined' errors. | Return values as specified to prevent 'method of undefined' errors.
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,63 +1,28 @@
import {Observable} from "rxjs/Observable";
import {Mediastore} from 'idai-components-2/datastore';
-
+/**
+ * @author Daniel de Oliveira
+ */
export class FakeMediastore implements Mediastore {
- private basePath: string = 'store/';
-
- constructor() {
- console.log("fake")
- }
-
- /**
- * @param key the identifier for the data
- * @param data the binary data to be stored
- * @returns {Promise<any>} resolve -> (),
- * reject -> the error message
- */
- public create(key: string, data: any): Promise<any> {
- return null;
+ public create(): Promise<any> {
+ return new Promise<any>((resolve)=>{resolve();});
}
- /**
- * @param key the identifier for the data
- * @returns {Promise<any>} resolve -> (data), the data read with the key,
- * reject -> the error message
- */
- public read(key: string): Promise<any> {
-
- return null;
+ public read(): Promise<any> {
+ return new Promise<any>((resolve)=>{resolve();});
}
- /**
- * @param key the identifier for the data
- * @param data the binary data to be stored
- * @returns {Promise<any>} resolve -> (),
- * reject -> the error message
- */
- public update(key: string, data: any): Promise<any> {
-
- return null;
+ public update(): Promise<any> {
+ return new Promise<any>((resolve)=>{resolve();});
}
- /**
- * @param key the identifier for the data to be removed
- * @returns {Promise<any>} resolve -> (),
- * reject -> the error message
- */
- public remove(key: string): Promise<any> {
-
- return null;
+ public remove(): Promise<any> {
+ return new Promise<any>((resolve)=>{resolve();});
}
- /**
- * Subscription enables clients to get notified
- * when files get modified via one of the accessor
- * methods defined here.
- */
public objectChangesNotifications(): Observable<File> {
- return null;
+ return Observable.create( () => {});
}
-
} |
4546fe961461f891f81f63c4829cb0d19c7928d8 | src/base/b-remote-provider/b-remote-provider.ts | src/base/b-remote-provider/b-remote-provider.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import iData, { component, prop, watch } from 'super/i-data/i-data';
export * from 'super/i-data/i-data';
@component()
export default class bRemoteProvider<T extends Dictionary = Dictionary> extends iData<T> {
/**
* Field for setting to a component parent
*/
@prop({type: String, required: false})
readonly field?: string;
/**
* Synchronization for the db field
*
* @param [value]
* @emits change(db: T)
*/
@watch('db')
protected syncDBWatcher(value: T): void {
if (this.field && this.$parent) {
this.$parent.setField(this.field, value);
}
this.emit('change', value);
}
}
| /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
import iData, { component, prop, watch } from 'super/i-data/i-data';
export * from 'super/i-data/i-data';
@component()
export default class bRemoteProvider<T extends Dictionary = Dictionary> extends iData<T> {
/** @override */
readonly remoteProvider: boolean = true;
/**
* Field for setting to a component parent
*/
@prop({type: String, required: false})
readonly field?: string;
/**
* Synchronization for the db field
*
* @param [value]
* @emits change(db: T)
*/
@watch('db')
protected syncDBWatcher(value: T): void {
if (this.field && this.$parent) {
this.$parent.setField(this.field, value);
}
this.emit('change', value);
}
}
| Set remoteProvider prop to true | :wrench: Set remoteProvider prop to true
| TypeScript | mit | V4Fire/Client,V4Fire/Client,V4Fire/Client,V4Fire/Client | ---
+++
@@ -11,6 +11,9 @@
@component()
export default class bRemoteProvider<T extends Dictionary = Dictionary> extends iData<T> {
+ /** @override */
+ readonly remoteProvider: boolean = true;
+
/**
* Field for setting to a component parent
*/ |
847830a5ca56404cee0e5edf28d9e3e0c9340748 | app/src/components/tree/tree.service.ts | app/src/components/tree/tree.service.ts | module app.tree {
export class TreeService {
static $inject = ['ElementsFactoryService'];
public elements : any = [];
constructor(elementsFactoryService: app.core.ElementsFactoryService){
var rootElement: any = elementsFactoryService.getNewElement("VerticalLayout");
rootElement.root = "root";
this.elements.push(rootElement);
}
exportUISchemaAsJSON() : string{
return JSON.stringify(this.elements[0], function(key, value){
if(value==""){
return undefined;
}
switch(key){
case "id":
case "acceptedElements":
case "$$hashKey":
case "root":
case "icon":
return undefined;
break;
}
return value;
});
}
}
angular.module('app.tree')
.service('TreeService', TreeService);
} | module app.tree {
export class TreeService {
static $inject = ['ElementsFactoryService'];
public elements : any = [];
constructor(elementsFactoryService: app.core.ElementsFactoryService){
var rootElement: any = elementsFactoryService.getNewElement("VerticalLayout");
rootElement.root = "root";
this.elements.push(rootElement);
}
exportUISchemaAsJSON() : string {
return JSON.stringify(this.elements[0], function(key, value){
if(value==""){
return undefined;
}
switch(key){
case "id":
case "acceptedElements":
case "$$hashKey":
case "root":
case "icon":
return undefined;
break;
}
return value;
}, 2 /* two spaces as indentation */);
}
}
angular.module('app.tree')
.service('TreeService', TreeService);
} | Format the UI Schema output: added two space indentation | Format the UI Schema output: added two space indentation
| TypeScript | mit | pancho111203/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,eclipsesource/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,eclipsesource/JsonFormsEditor,pancho111203/JsonFormsEditor | ---
+++
@@ -12,7 +12,7 @@
this.elements.push(rootElement);
}
- exportUISchemaAsJSON() : string{
+ exportUISchemaAsJSON() : string {
return JSON.stringify(this.elements[0], function(key, value){
if(value==""){
@@ -32,7 +32,7 @@
}
return value;
- });
+ }, 2 /* two spaces as indentation */);
}
} |
69f543229ff7b6c7e17af16b63fc689009a75463 | src/ui/document/renderer/ansi-renderer.ts | src/ui/document/renderer/ansi-renderer.ts | import { ipcRenderer } from 'electron'
import DocumentRenderer from './document-renderer'
export default class AnsiRenderer implements DocumentRenderer {
private ansiContainer = document.getElementById('ansi_container')!
public render(filePath: string): void {
this.ansiContainer.innerHTML = ''
const isRetina = window.devicePixelRatio > 1
// @ts-ignore: loaded in html
AnsiLove.splitRender(filePath, (canvases: HTMLCanvasElement[], _: any) => {
this.ansiContainer.style.width = canvases[0].style.width
canvases.forEach((canvas: HTMLCanvasElement) => {
canvas.style.verticalAlign = 'bottom'
canvas.style.display = 'block'
this.ansiContainer.appendChild(canvas)
})
ipcRenderer.send(
'window-size-changed',
this.ansiContainer.scrollWidth,
this.ansiContainer.clientHeight
)
}, 27, { 'bits': '8', '2x': isRetina ? 1 : 0 })
}
}
| import { ipcRenderer } from 'electron'
import DocumentRenderer from './document-renderer'
export default class AnsiRenderer implements DocumentRenderer {
private ansiContainer = document.getElementById('ansi_container')!
public render(filePath: string): void {
this.ansiContainer.innerHTML = ''
const isRetina = window.devicePixelRatio > 1
// @ts-ignore: loaded in html
AnsiLove.splitRender(escape(filePath), (canvases: HTMLCanvasElement[], _: any) => {
this.ansiContainer.style.width = canvases[0].style.width
canvases.forEach((canvas: HTMLCanvasElement) => {
canvas.style.verticalAlign = 'bottom'
canvas.style.display = 'block'
this.ansiContainer.appendChild(canvas)
})
ipcRenderer.send(
'window-size-changed',
this.ansiContainer.scrollWidth,
this.ansiContainer.clientHeight
)
}, 27, { 'bits': '8', '2x': isRetina ? 1 : 0 })
}
}
| Fix opening ans files with special symbols in filename | Fix opening ans files with special symbols in filename
| TypeScript | mit | nrlquaker/nfov,nrlquaker/nfov | ---
+++
@@ -8,7 +8,7 @@
this.ansiContainer.innerHTML = ''
const isRetina = window.devicePixelRatio > 1
// @ts-ignore: loaded in html
- AnsiLove.splitRender(filePath, (canvases: HTMLCanvasElement[], _: any) => {
+ AnsiLove.splitRender(escape(filePath), (canvases: HTMLCanvasElement[], _: any) => {
this.ansiContainer.style.width = canvases[0].style.width
canvases.forEach((canvas: HTMLCanvasElement) => {
canvas.style.verticalAlign = 'bottom' |
7b16cd3dbb82771c0b88f2d98bf471abac138c2c | openvidu-call/openvidu-call-back/src/config.ts | openvidu-call/openvidu-call-back/src/config.ts | export const SERVER_PORT = process.env.SERVER_PORT || 5000;
export const OPENVIDU_URL = process.env.OPENVIDU_URL || 'https://localhost:4443';
export const OPENVIDU_SECRET = process.env.OPENVIDU_SECRET || 'MY_SECRET';
export const CALL_OPENVIDU_CERTTYPE = process.env.CALL_OPENVIDU_CERTTYPE || 'selfsigned';
export const ADMIN_SECRET = process.env.ADMIN_SECRET || OPENVIDU_SECRET;
export const RECORDING = process.env.RECORDING || 'ENABLED';
| export const SERVER_PORT = process.env.SERVER_PORT || 5000;
export const OPENVIDU_URL = process.env.OPENVIDU_URL || 'http://localhost:4443';
export const OPENVIDU_SECRET = process.env.OPENVIDU_SECRET || 'MY_SECRET';
export const CALL_OPENVIDU_CERTTYPE = process.env.CALL_OPENVIDU_CERTTYPE || 'selfsigned';
export const ADMIN_SECRET = process.env.ADMIN_SECRET || OPENVIDU_SECRET;
export const RECORDING = process.env.RECORDING || 'ENABLED';
| Update openvidu-call OPENVIDU_URL deafault value | Update openvidu-call OPENVIDU_URL deafault value
| TypeScript | apache-2.0 | OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials,OpenVidu/openvidu-tutorials | ---
+++
@@ -1,5 +1,5 @@
export const SERVER_PORT = process.env.SERVER_PORT || 5000;
-export const OPENVIDU_URL = process.env.OPENVIDU_URL || 'https://localhost:4443';
+export const OPENVIDU_URL = process.env.OPENVIDU_URL || 'http://localhost:4443';
export const OPENVIDU_SECRET = process.env.OPENVIDU_SECRET || 'MY_SECRET';
export const CALL_OPENVIDU_CERTTYPE = process.env.CALL_OPENVIDU_CERTTYPE || 'selfsigned';
export const ADMIN_SECRET = process.env.ADMIN_SECRET || OPENVIDU_SECRET; |
bd01ff260d6a4eadd984340997ed80a01018873c | app/static/models/barcharts/timehistory.ts | app/static/models/barcharts/timehistory.ts | import {ExerciseHistory} from "./exercisehistory";
export class TimeHistory extends ExerciseHistory {
private distance: number;
private duration: number;
getHistoryId(): number {
return this.historyId;
}
getWidth(): number {
return this.distance;
}
setWidth(value: number): void {
this.distance = value;
}
getHeight(): number {
return this.duration;
}
setHeight(value: number): void {
this.duration = value;
}
getXOffset(): number {
return this.x_offset;
}
setXOffset(value: number): void {
this.x_offset = value;
}
getYOffset(): number {
return this.y_offset;
}
setYOffset(value: number): void {
this.y_offset = value;
}
getDatestamp(): string {
return this.dateStamp;
}
setDatestamp(value: string): void {
this.dateStamp = value;
}
getWidthBuffer(): number {
return 0;
}
getSets(): number {
return 1;
}
} | import {ExerciseHistory} from "./exercisehistory";
export class TimeHistory extends ExerciseHistory {
private distance: number;
private duration: number;
constructor(jsonObject: any) {
super(jsonObject);
this.distance = jsonObject.history_distance;
this.duration = jsonObject.history_duration;
}
getWidth(): number {
return this.distance;
}
setWidth(value: number): void {
this.distance = value;
}
getHeight(): number {
return this.duration;
}
setHeight(value: number): void {
this.duration = value;
}
getWidthBuffer(): number {
return 0;
}
getSets(): number {
return 1;
}
} | Add constructor to time history model | Add constructor to time history model
| TypeScript | mit | pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise,pbraunstein/trackercise | ---
+++
@@ -3,8 +3,10 @@
private distance: number;
private duration: number;
- getHistoryId(): number {
- return this.historyId;
+ constructor(jsonObject: any) {
+ super(jsonObject);
+ this.distance = jsonObject.history_distance;
+ this.duration = jsonObject.history_duration;
}
getWidth(): number {
@@ -23,30 +25,6 @@
this.duration = value;
}
- getXOffset(): number {
- return this.x_offset;
- }
-
- setXOffset(value: number): void {
- this.x_offset = value;
- }
-
- getYOffset(): number {
- return this.y_offset;
- }
-
- setYOffset(value: number): void {
- this.y_offset = value;
- }
-
- getDatestamp(): string {
- return this.dateStamp;
- }
-
- setDatestamp(value: string): void {
- this.dateStamp = value;
- }
-
getWidthBuffer(): number {
return 0;
} |
7f3aa3215b7bd7aa8d129801a1eb04bf66f5295e | framework/src/interfaces.ts | framework/src/interfaces.ts | import { HandleRequest } from './HandleRequest';
import { Jovo } from './Jovo';
import { PluginConfig } from './Plugin';
import { PersistableUserData } from './JovoUser';
import { PersistableSessionData } from './JovoSession';
import { ArrayElement } from './index';
export interface Data {
[key: string]: unknown;
}
export interface RequestData extends Data {}
export interface ComponentData extends Data {}
export interface SessionData extends Data {}
export interface UserData extends Data {}
export interface Entity {
[key: string]: unknown | undefined;
id?: string;
key?: string;
name?: string;
value?: unknown;
}
export type EntityMap = Record<string, Entity>;
export interface AsrData {
[key: string]: unknown;
text?: string;
}
export interface NluData {
[key: string]: unknown;
intent?: {
name: string;
};
entities?: EntityMap;
}
export interface Intent {
name: string;
global?: boolean;
}
export type JovoConditionFunction = (
handleRequest: HandleRequest,
jovo: Jovo,
) => boolean | Promise<boolean>;
type StoredElementType = keyof PersistableUserData | keyof PersistableSessionData;
export interface DbPluginConfig extends PluginConfig {
storedElements: {
$user: {
enabled: boolean;
};
$session: {
enabled: boolean;
};
};
}
| import { HandleRequest } from './HandleRequest';
import { Jovo } from './Jovo';
import { PersistableSessionData } from './JovoSession';
import { PersistableUserData } from './JovoUser';
import { PluginConfig } from './Plugin';
export interface Data {
[key: string]: any;
}
export interface RequestData extends Data {}
export interface ComponentData extends Data {}
export interface SessionData extends Data {}
export interface UserData extends Data {}
export interface Entity {
[key: string]: unknown | undefined;
id?: string;
key?: string;
name?: string;
value?: unknown;
}
export type EntityMap = Record<string, Entity>;
export interface AsrData {
[key: string]: unknown;
text?: string;
}
export interface NluData {
[key: string]: unknown;
intent?: {
name: string;
};
entities?: EntityMap;
}
export interface Intent {
name: string;
global?: boolean;
}
export type JovoConditionFunction = (
handleRequest: HandleRequest,
jovo: Jovo,
) => boolean | Promise<boolean>;
type StoredElementType = keyof PersistableUserData | keyof PersistableSessionData;
export interface DbPluginConfig extends PluginConfig {
storedElements: {
$user: {
enabled: boolean;
};
$session: {
enabled: boolean;
};
};
}
| Change Data-index-signature to have any as value-type for now | :label: Change Data-index-signature to have any as value-type for now
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -1,12 +1,11 @@
import { HandleRequest } from './HandleRequest';
import { Jovo } from './Jovo';
+import { PersistableSessionData } from './JovoSession';
+import { PersistableUserData } from './JovoUser';
import { PluginConfig } from './Plugin';
-import { PersistableUserData } from './JovoUser';
-import { PersistableSessionData } from './JovoSession';
-import { ArrayElement } from './index';
export interface Data {
- [key: string]: unknown;
+ [key: string]: any;
}
export interface RequestData extends Data {} |
fda5af3f7d9ecb4d792f97716954f5186c148dca | src/renderer/app/components/SearchBox/style.ts | src/renderer/app/components/SearchBox/style.ts | import styled from 'styled-components';
import { centerImage } from '~/shared/mixins';
import { icons } from '../../constants';
export const StyledSearchBox = styled.div`
position: absolute;
top: 15%;
left: 50%;
width: 700px;
z-index: 2;
background-color: white;
border-radius: 30px;
transform: translateX(-50%);
display: flex;
flex-flow: column;
`;
export const SearchIcon = styled.div`
${centerImage('16px', '16px')};
background-image: url(${icons.search});
height: 16px;
min-width: 16px;
margin-left: 16px;
`;
export const Input = styled.input`
height: 100%;
flex: 1;
background-color: transparent;
border: none;
outline: none;
color: black;
margin-left: 16px;
`;
export const InputContainer = styled.div`
display: flex;
align-items: center;
height: 42px;
`;
| import styled from 'styled-components';
import { centerImage } from '~/shared/mixins';
import { icons } from '../../constants';
export const StyledSearchBox = styled.div`
position: absolute;
top: 15%;
left: 50%;
width: 700px;
z-index: 2;
background-color: white;
border-radius: 20px;
transform: translateX(-50%);
display: flex;
flex-flow: column;
`;
export const SearchIcon = styled.div`
${centerImage('16px', '16px')};
background-image: url(${icons.search});
height: 16px;
min-width: 16px;
margin-left: 16px;
`;
export const Input = styled.input`
height: 100%;
flex: 1;
background-color: transparent;
border: none;
outline: none;
color: black;
margin-left: 16px;
`;
export const InputContainer = styled.div`
display: flex;
align-items: center;
height: 42px;
`;
| Fix border radius for SearchBox | Fix border radius for SearchBox
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -9,7 +9,7 @@
width: 700px;
z-index: 2;
background-color: white;
- border-radius: 30px;
+ border-radius: 20px;
transform: translateX(-50%);
display: flex;
flex-flow: column; |
2fa5007a899e5720441f0f75fbe5fc1820a9649c | src/Apps/Search/Components/SearchResultsSkeleton/Header.tsx | src/Apps/Search/Components/SearchResultsSkeleton/Header.tsx | import { Box, color, Separator } from "@artsy/palette"
import React from "react"
export const Header: React.SFC<any> = props => {
return (
<Box height={100} mb={30} mt={[40, 120]}>
<Box mb={40} background={color("black10")} width={320} height={20} />
<Box width={700}>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
</Box>
<Separator mt={10} />
</Box>
)
}
| import { Box, color, Separator } from "@artsy/palette"
import React from "react"
export const Header: React.SFC<any> = props => {
return (
<Box height={100} mb={30} mt={120}>
<Box mb={40} background={color("black10")} width={320} height={20} />
<Box width={700}>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
<Box
width={80}
height={12}
mr={3}
display="inline-block"
background={color("black10")}
/>
</Box>
<Separator mt={10} />
</Box>
)
}
| Adjust header margin on mobile search results skeleton | Adjust header margin on mobile search results skeleton
This commit accounts for a minor differences in placement between
Storybooks and Force.
| TypeScript | mit | artsy/reaction,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -3,7 +3,7 @@
export const Header: React.SFC<any> = props => {
return (
- <Box height={100} mb={30} mt={[40, 120]}>
+ <Box height={100} mb={30} mt={120}>
<Box mb={40} background={color("black10")} width={320} height={20} />
<Box width={700}>
<Box |
699d1b37dcea49c7f682118c5a4972b2a3afab72 | applications/drive/src/app/components/layout/DriveHeader.tsx | applications/drive/src/app/components/layout/DriveHeader.tsx | import { APPS } from 'proton-shared/lib/constants';
import React from 'react';
import {
PrivateHeader,
useActiveBreakpoint,
TopNavbarListItemContactsDropdown,
TopNavbarListItemSettingsButton,
} from 'react-components';
import { c } from 'ttag';
interface Props {
isHeaderExpanded: boolean;
toggleHeaderExpanded: () => void;
floatingPrimary: React.ReactNode;
logo: React.ReactNode;
title?: string;
}
const DriveHeader = ({
logo,
isHeaderExpanded,
toggleHeaderExpanded,
floatingPrimary,
title = c('Title').t`Drive`,
}: Props) => {
const { isNarrow } = useActiveBreakpoint();
return (
<PrivateHeader
logo={logo}
title={title}
contactsButton={<TopNavbarListItemContactsDropdown />}
settingsButton={<TopNavbarListItemSettingsButton to="/drive" toApp={APPS.PROTONACCOUNT} />}
expanded={isHeaderExpanded}
onToggleExpand={toggleHeaderExpanded}
isNarrow={isNarrow}
floatingButton={floatingPrimary}
/>
);
};
export default DriveHeader;
| import { APPS } from 'proton-shared/lib/constants';
import React from 'react';
import {
PrivateHeader,
useActiveBreakpoint,
TopNavbarListItemContactsDropdown,
TopNavbarListItemSettingsDropdown,
} from 'react-components';
import { c } from 'ttag';
interface Props {
isHeaderExpanded: boolean;
toggleHeaderExpanded: () => void;
floatingPrimary: React.ReactNode;
logo: React.ReactNode;
title?: string;
}
const DriveHeader = ({
logo,
isHeaderExpanded,
toggleHeaderExpanded,
floatingPrimary,
title = c('Title').t`Drive`,
}: Props) => {
const { isNarrow } = useActiveBreakpoint();
return (
<PrivateHeader
logo={logo}
title={title}
contactsButton={<TopNavbarListItemContactsDropdown />}
settingsButton={<TopNavbarListItemSettingsDropdown to="/drive" toApp={APPS.PROTONACCOUNT} />}
expanded={isHeaderExpanded}
onToggleExpand={toggleHeaderExpanded}
isNarrow={isNarrow}
floatingButton={floatingPrimary}
/>
);
};
export default DriveHeader;
| Rename settings button to settings dropdown | Rename settings button to settings dropdown
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -4,7 +4,7 @@
PrivateHeader,
useActiveBreakpoint,
TopNavbarListItemContactsDropdown,
- TopNavbarListItemSettingsButton,
+ TopNavbarListItemSettingsDropdown,
} from 'react-components';
import { c } from 'ttag';
@@ -29,7 +29,7 @@
logo={logo}
title={title}
contactsButton={<TopNavbarListItemContactsDropdown />}
- settingsButton={<TopNavbarListItemSettingsButton to="/drive" toApp={APPS.PROTONACCOUNT} />}
+ settingsButton={<TopNavbarListItemSettingsDropdown to="/drive" toApp={APPS.PROTONACCOUNT} />}
expanded={isHeaderExpanded}
onToggleExpand={toggleHeaderExpanded}
isNarrow={isNarrow} |
3b41560a91bfd1485a548929b33ffbfa97409715 | src/db/connector.ts | src/db/connector.ts | /*
Copyright 2018 matrix-appservice-discord
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export interface ISqlCommandParameters {
[paramKey: string]: number | boolean | string | Promise<number | boolean | string>;
}
export interface ISqlRow {
[key: string]: number | boolean | string;
}
export interface IDatabaseConnector {
Open(): void;
Get(sql: string, parameters?: ISqlCommandParameters): Promise<ISqlRow>;
All(sql: string, parameters?: ISqlCommandParameters): Promise<ISqlRow[]>;
Run(sql: string, parameters?: ISqlCommandParameters): Promise<void>;
Close(): Promise<void>;
Exec(sql: string): Promise<void>;
}
| /*
Copyright 2018 matrix-appservice-discord
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.
*/
type SQLTYPES = number | boolean | string | null;
export interface ISqlCommandParameters {
[paramKey: string]: SQLTYPES | Promise<SQLTYPES>;
}
export interface ISqlRow {
[key: string]: SQLTYPES;
}
export interface IDatabaseConnector {
Open(): void;
Get(sql: string, parameters?: ISqlCommandParameters): Promise<ISqlRow>;
All(sql: string, parameters?: ISqlCommandParameters): Promise<ISqlRow[]>;
Run(sql: string, parameters?: ISqlCommandParameters): Promise<void>;
Close(): Promise<void>;
Exec(sql: string): Promise<void>;
}
| Add a type for SQLTYPES | Add a type for SQLTYPES
| TypeScript | apache-2.0 | Half-Shot/matrix-appservice-discord | ---
+++
@@ -14,12 +14,14 @@
limitations under the License.
*/
+type SQLTYPES = number | boolean | string | null;
+
export interface ISqlCommandParameters {
- [paramKey: string]: number | boolean | string | Promise<number | boolean | string>;
+ [paramKey: string]: SQLTYPES | Promise<SQLTYPES>;
}
export interface ISqlRow {
- [key: string]: number | boolean | string;
+ [key: string]: SQLTYPES;
}
export interface IDatabaseConnector { |
1fa5302e723dd380c860e8d27ee2da3ba3ee932b | src/entry/import-names/name-list-entry.tsx | src/entry/import-names/name-list-entry.tsx | import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {translate} from 'react-i18next'
import ListItem from '@material-ui/core/ListItem'
import {setImportOpenAction, setPlayerNamesAction} from '../actions/set-entry-props'
import {showToastAction} from '../../toast-singleton/actions/show-toast'
import {Dispatch, ITranslateMixin} from '../../types'
const mapDispatchToProps = (dispatch: Dispatch) =>
bindActionCreators({
setImportOpen: setImportOpenAction,
showToast: showToastAction,
setPlayerNames: setPlayerNamesAction
}, dispatch)
type dispatchType = ReturnType<typeof mapDispatchToProps>
interface INameEntryProps {
name: string[]
}
export class NameListEntryImpl extends React.Component {
public props: INameEntryProps & dispatchType & ITranslateMixin
public render() {
return <ListItem onClick={this.setNames}>{this.props.name.join(', ')}</ListItem>
}
private setNames = () => {
const {name, setImportOpen, showToast, setPlayerNames, t} = this.props
setPlayerNames(name)
setImportOpen(false)
showToast(t('Imported names successfully'))
}
}
export const NameListEntry = flowRight(
translate(),
connect(null, mapDispatchToProps)
)(NameListEntryImpl) as React.ComponentType<INameEntryProps>
| import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {translate} from 'react-i18next'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import {setImportOpenAction, setPlayerNamesAction} from '../actions/set-entry-props'
import {showToastAction} from '../../toast-singleton/actions/show-toast'
import {Dispatch, ITranslateMixin} from '../../types'
const mapDispatchToProps = (dispatch: Dispatch) =>
bindActionCreators({
setImportOpen: setImportOpenAction,
showToast: showToastAction,
setPlayerNames: setPlayerNamesAction
}, dispatch)
type dispatchType = ReturnType<typeof mapDispatchToProps>
interface INameEntryProps {
name: string[]
}
export class NameListEntryImpl extends React.Component {
public props: INameEntryProps & dispatchType & ITranslateMixin
public render() {
return <ListItem button onClick={this.setNames}>
<ListItemText primary={this.props.name.join(', ')} />
</ListItem>
}
private setNames = () => {
const {name, setImportOpen, showToast, setPlayerNames, t} = this.props
setPlayerNames(name)
setImportOpen(false)
showToast(t('Imported names successfully'))
}
}
export const NameListEntry = flowRight(
translate(),
connect(null, mapDispatchToProps)
)(NameListEntryImpl) as React.ComponentType<INameEntryProps>
| Use button in name import list | Use button in name import list
| TypeScript | mit | Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc | ---
+++
@@ -4,6 +4,7 @@
import {connect} from 'react-redux'
import {translate} from 'react-i18next'
import ListItem from '@material-ui/core/ListItem'
+import ListItemText from '@material-ui/core/ListItemText'
import {setImportOpenAction, setPlayerNamesAction} from '../actions/set-entry-props'
import {showToastAction} from '../../toast-singleton/actions/show-toast'
import {Dispatch, ITranslateMixin} from '../../types'
@@ -25,7 +26,9 @@
public props: INameEntryProps & dispatchType & ITranslateMixin
public render() {
- return <ListItem onClick={this.setNames}>{this.props.name.join(', ')}</ListItem>
+ return <ListItem button onClick={this.setNames}>
+ <ListItemText primary={this.props.name.join(', ')} />
+ </ListItem>
}
private setNames = () => { |
68ddc9eced98d10e60dbdd7cc734ad9119adb10c | docs/src/Scenes/Documentation/Overview/Scenes/Start.tsx | docs/src/Scenes/Documentation/Overview/Scenes/Start.tsx | import * as React from 'react';
import * as Highlight from 'react-highlight';
import { Container } from './../../../../../../src/layout';
import { Title, Subtitle } from './../../../../../../src';
const Start = (props) => (
<Container>
<Title isSpaced>How to Start?</Title>
<Subtitle>1. Install via npm</Subtitle>
<div className='npm'><code><span className='is-unselectable'>$ </span>npm install bloomer</code></div>
<hr />
<div></div>
<Subtitle>2. Import and use Bloomer components.</Subtitle>
<Highlight className='javascript'>
{`import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Container, Box } from 'bloomer';
ReactDOM.render(
<Container>
<Box>Hello World!</Box>
</Container>,
document.getElementById('root')
)`}
</Highlight>
<Subtitle>You're done!</Subtitle>
<p>
Since <strong>Bloomer</strong> is written with Typescript, the library is ship with typings.
That means that you have the benefit of IntelliSense in your editor.
</p>
<p>Remember, with great power comes great responsibility.</p>
</Container>
)
export default Start; | import * as React from 'react';
import * as Highlight from 'react-highlight';
import { Container } from './../../../../../../src/layout';
import { Title, Subtitle } from './../../../../../../src';
const startExample = `import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Container, Box } from 'bloomer';
ReactDOM.render(
<Container>
<Box>Hello World!</Box>
</Container>,
document.getElementById('root')
)`;
const Start = (props) => (
<Container>
<Title isSpaced>How to Start?</Title>
<Subtitle>1. Install via npm</Subtitle>
<div className='npm'><code><span className='is-unselectable'>$ </span>npm install bloomer</code></div>
<hr />
<Subtitle>2. Make sure to import <a href='http://bulma.io/documentation/overview/start/'>Bulma</a> in your project.</Subtitle>
<hr/>
<Subtitle>3. Import and use Bloomer components.</Subtitle>
<Highlight className='javascript'>{startExample}</Highlight>
<hr/>
<Subtitle>You're done!</Subtitle>
<p>
Since <strong>Bloomer</strong> is written with Typescript, the library is ship with typings.
That means that you have the benefit of IntelliSense in your editor.
</p>
<p>Remember, with great power comes great responsibility.</p>
</Container>
)
export default Start; | Add instructions to import Bulma on Overview | Add instructions to import Bulma on Overview
| TypeScript | mit | AlgusDark/bloomer,AlgusDark/bloomer | ---
+++
@@ -4,16 +4,7 @@
import { Container } from './../../../../../../src/layout';
import { Title, Subtitle } from './../../../../../../src';
-const Start = (props) => (
- <Container>
- <Title isSpaced>How to Start?</Title>
- <Subtitle>1. Install via npm</Subtitle>
- <div className='npm'><code><span className='is-unselectable'>$ </span>npm install bloomer</code></div>
- <hr />
- <div></div>
- <Subtitle>2. Import and use Bloomer components.</Subtitle>
- <Highlight className='javascript'>
- {`import * as React from 'react';
+const startExample = `import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Container, Box } from 'bloomer';
@@ -22,12 +13,29 @@
<Box>Hello World!</Box>
</Container>,
document.getElementById('root')
-)`}
- </Highlight>
+)`;
+
+const Start = (props) => (
+ <Container>
+ <Title isSpaced>How to Start?</Title>
+ <Subtitle>1. Install via npm</Subtitle>
+ <div className='npm'><code><span className='is-unselectable'>$ </span>npm install bloomer</code></div>
+
+ <hr />
+
+ <Subtitle>2. Make sure to import <a href='http://bulma.io/documentation/overview/start/'>Bulma</a> in your project.</Subtitle>
+
+ <hr/>
+
+ <Subtitle>3. Import and use Bloomer components.</Subtitle>
+ <Highlight className='javascript'>{startExample}</Highlight>
+
+ <hr/>
+
<Subtitle>You're done!</Subtitle>
<p>
- Since <strong>Bloomer</strong> is written with Typescript, the library is ship with typings.
- That means that you have the benefit of IntelliSense in your editor.
+ Since <strong>Bloomer</strong> is written with Typescript, the library is ship with typings.
+ That means that you have the benefit of IntelliSense in your editor.
</p>
<p>Remember, with great power comes great responsibility.</p>
</Container> |
7e83957a9feeab01530a428d4385171fad86de04 | packages/toolchain/src/rules/__tests__/missingElse.ts | packages/toolchain/src/rules/__tests__/missingElse.ts | import { singleError } from '../../harness/parser'
import { MissingElseError } from '../missingElse'
it('detects missing Else case', () => {
singleError(
`
if (2 === 2) {
var x = 2;
}
`,
{
errorClass: MissingElseError,
explanation: /Missing.*else.*/
}
)
})
| import { singleError } from '../../harness/parser'
import { MissingElseError } from '../missingElse'
it('detects missing Else case', () => {
singleError(
`
if (2 === 2) {
var x = 2;
}
`,
{
errorClass: MissingElseError,
explanation: /Missing.*else.*/
}
)
})
it('detects missing Else case in if-elseif', () => {
singleError(
`
if (2 === 2) {
var x = 2;
} else if (2 === 1) {
var y = 2;
}
`,
{
errorClass: MissingElseError,
explanation: /Missing.*else.*/
}
)
})
| Add test for if-elseif for missing else | Add test for if-elseif for missing else
| TypeScript | mit | evansb/source-toolchain,evansb/source-toolchain | ---
+++
@@ -14,3 +14,19 @@
}
)
})
+
+it('detects missing Else case in if-elseif', () => {
+ singleError(
+ `
+ if (2 === 2) {
+ var x = 2;
+ } else if (2 === 1) {
+ var y = 2;
+ }
+ `,
+ {
+ errorClass: MissingElseError,
+ explanation: /Missing.*else.*/
+ }
+ )
+}) |
538fae9a507043e0019f76fdfdb349697ac9ca4d | src/shared/lib/handleLongUrls.ts | src/shared/lib/handleLongUrls.ts | import getBrowserWindow from "./getBrowserWindow";
import {parseCohortIds} from "../../pages/patientView/clinicalInformation/PatientViewPageStore";
export const NAVCASEIDS_PARAM = "navCaseIds";
export const NAVCASEIDS_REGEXP = new RegExp(`${NAVCASEIDS_PARAM}=([^&]*)`);
const PROP_NAME = "navCaseIdsCache";
export function handleLongUrls(){
const navCaseIdMatch = getBrowserWindow().location.hash.match(new RegExp(NAVCASEIDS_REGEXP));
// google analytics starts to crash when location.href gets too long
// this is a fairly arbitrary length at which point we need to store these caseIds in localStorage instead of in hash
if (navCaseIdMatch && navCaseIdMatch[1].length > 60000) {
// now delete from url so that we don't hurt google analytics
getBrowserWindow().location.hash = getBrowserWindow().location.hash.replace(NAVCASEIDS_REGEXP,"");
getBrowserWindow()[PROP_NAME] = navCaseIdMatch[1];
}
}
export function getNavCaseIdsCache(){
const data = getBrowserWindow()[PROP_NAME];
delete getBrowserWindow()[PROP_NAME];
return (data) ? parseCohortIds(data) : undefined;
} | import getBrowserWindow from "./getBrowserWindow";
export const NAVCASEIDS_PARAM = "navCaseIds";
export const NAVCASEIDS_REGEXP = new RegExp(`${NAVCASEIDS_PARAM}=([^&]*)`);
const PROP_NAME = "navCaseIdsCache";
export function parseCohortIds(concatenatedIds:string){
return concatenatedIds.split(',').map((entityId:string)=>{
return entityId.includes(':') ? entityId : this.studyId + ':' + entityId;
});
}
export function handleLongUrls(){
const navCaseIdMatch = getBrowserWindow().location.hash.match(new RegExp(NAVCASEIDS_REGEXP));
// google analytics starts to crash when location.href gets too long
// this is a fairly arbitrary length at which point we need to store these caseIds in localStorage instead of in hash
if (navCaseIdMatch && navCaseIdMatch[1].length > 60000) {
// now delete from url so that we don't hurt google analytics
getBrowserWindow().location.hash = getBrowserWindow().location.hash.replace(NAVCASEIDS_REGEXP,"");
getBrowserWindow()[PROP_NAME] = navCaseIdMatch[1];
}
}
export function getNavCaseIdsCache(){
const data = getBrowserWindow()[PROP_NAME];
delete getBrowserWindow()[PROP_NAME];
return (data) ? parseCohortIds(data) : undefined;
} | Fix dependency which is crashing in dev mode | Fix dependency which is crashing in dev mode
Signed-off-by: Abeshouse, Adam A./Sloan Kettering Institute <[email protected]>
Former-commit-id: 836b2f4833ccacd67c9d01c8a568e1ac5bde391b | TypeScript | agpl-3.0 | alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend | ---
+++
@@ -1,11 +1,16 @@
import getBrowserWindow from "./getBrowserWindow";
-import {parseCohortIds} from "../../pages/patientView/clinicalInformation/PatientViewPageStore";
export const NAVCASEIDS_PARAM = "navCaseIds";
export const NAVCASEIDS_REGEXP = new RegExp(`${NAVCASEIDS_PARAM}=([^&]*)`);
const PROP_NAME = "navCaseIdsCache";
+
+export function parseCohortIds(concatenatedIds:string){
+ return concatenatedIds.split(',').map((entityId:string)=>{
+ return entityId.includes(':') ? entityId : this.studyId + ':' + entityId;
+ });
+}
export function handleLongUrls(){
const navCaseIdMatch = getBrowserWindow().location.hash.match(new RegExp(NAVCASEIDS_REGEXP)); |
a6d22d9954dc04c3e299dcb175751305d1004b28 | src/deprecated.ts | src/deprecated.ts | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {onCLS as getCLS} from './onCLS.js';
export {onFCP as getFCP} from './onFCP.js';
export {onFID as getFID} from './onFID.js';
export {onINP as getINP} from './onINP.js';
export {onLCP as getLCP} from './onLCP.js';
export {onTTFB as getTFB} from './onTTFB.js';
| /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {onCLS as getCLS} from './onCLS.js';
export {onFCP as getFCP} from './onFCP.js';
export {onFID as getFID} from './onFID.js';
export {onINP as getINP} from './onINP.js';
export {onLCP as getLCP} from './onLCP.js';
export {onTTFB as getTTFB} from './onTTFB.js';
| Fix getTTFB not properly aliased to onTTFB | Fix getTTFB not properly aliased to onTTFB
| TypeScript | apache-2.0 | GoogleChrome/web-vitals,GoogleChrome/web-vitals | ---
+++
@@ -1,5 +1,5 @@
/*
- * Copyright 2020 Google LLC
+ * Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,4 +19,4 @@
export {onFID as getFID} from './onFID.js';
export {onINP as getINP} from './onINP.js';
export {onLCP as getLCP} from './onLCP.js';
-export {onTTFB as getTFB} from './onTTFB.js';
+export {onTTFB as getTTFB} from './onTTFB.js'; |
49537b35259c368c073180def9c504e15f63bda2 | client/components/NavigationDrawer/NavigationDrawerOpener.tsx | client/components/NavigationDrawer/NavigationDrawerOpener.tsx | // This is the root component for #search-page
import React from 'react'
import Emitter from '../../emitter'
import Crowi from 'client/util/Crowi'
import Icon from 'components/Common/Icon'
interface Props {
crowi: Crowi
}
interface State {
menuOpen: boolean
}
export default class NavigationDrawerOpener extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
menuOpen: false,
}
this.handleMenuOpen = this.handleMenuOpen.bind(this)
Emitter.on('closeSideMenu', () => {
this.closeMenu()
})
}
handleMenuOpen() {
const toMenuOpen = !this.state.menuOpen
Emitter.emit('sideMenuHandle', toMenuOpen)
this.setState({ menuOpen: toMenuOpen })
}
closeMenu() {
const toMenuOpen = false
Emitter.emit('sideMenuHandle', toMenuOpen)
this.setState({ menuOpen: toMenuOpen })
}
render() {
return (
<a onClick={this.handleMenuOpen}>
<Icon name="menu" />
</a>
)
}
}
| import React, { FC, useEffect, useCallback } from 'react'
import Emitter from '../../emitter'
import Crowi from 'client/util/Crowi'
import Icon from 'components/Common/Icon'
interface Props {
crowi: Crowi
}
const NavigationDrawerOpener: FC<Props> = props => {
const openMenu = useCallback(() => {
Emitter.emit('sideMenuHandle', true)
}, [])
const closeMenu = useCallback(() => {
Emitter.emit('sideMenuHandle', false)
}, [])
useEffect(() => {
Emitter.on('closeSideMenu', () => {
closeMenu()
})
})
return (
<a onClick={openMenu}>
<Icon name="menu" />
</a>
)
}
export default NavigationDrawerOpener
| Migrate to Stateful Functional Component | Migrate to Stateful Functional Component | TypeScript | mit | crowi/crowi,crowi/crowi,crowi/crowi | ---
+++
@@ -1,6 +1,4 @@
-// This is the root component for #search-page
-
-import React from 'react'
+import React, { FC, useEffect, useCallback } from 'react'
import Emitter from '../../emitter'
import Crowi from 'client/util/Crowi'
@@ -10,42 +8,26 @@
crowi: Crowi
}
-interface State {
- menuOpen: boolean
+const NavigationDrawerOpener: FC<Props> = props => {
+ const openMenu = useCallback(() => {
+ Emitter.emit('sideMenuHandle', true)
+ }, [])
+
+ const closeMenu = useCallback(() => {
+ Emitter.emit('sideMenuHandle', false)
+ }, [])
+
+ useEffect(() => {
+ Emitter.on('closeSideMenu', () => {
+ closeMenu()
+ })
+ })
+
+ return (
+ <a onClick={openMenu}>
+ <Icon name="menu" />
+ </a>
+ )
}
-export default class NavigationDrawerOpener extends React.Component<Props, State> {
- constructor(props: Props) {
- super(props)
-
- this.state = {
- menuOpen: false,
- }
-
- this.handleMenuOpen = this.handleMenuOpen.bind(this)
-
- Emitter.on('closeSideMenu', () => {
- this.closeMenu()
- })
- }
-
- handleMenuOpen() {
- const toMenuOpen = !this.state.menuOpen
- Emitter.emit('sideMenuHandle', toMenuOpen)
- this.setState({ menuOpen: toMenuOpen })
- }
-
- closeMenu() {
- const toMenuOpen = false
- Emitter.emit('sideMenuHandle', toMenuOpen)
- this.setState({ menuOpen: toMenuOpen })
- }
-
- render() {
- return (
- <a onClick={this.handleMenuOpen}>
- <Icon name="menu" />
- </a>
- )
- }
-}
+export default NavigationDrawerOpener |
90cb428697d4eadbad7b63aa4ad8cd4802231d86 | src/index.ts | src/index.ts | import * as assign from 'lodash/assign';
import { requestApi, Config as RequestApiConfig } from './utils/requestApi';
class SDK {
private config: FindifySDK.Config;
private requestApiConfig: RequestApiConfig;
private makeExtendedRequest(request: Request) {
return assign({}, {
user: this.config.user,
log: this.config.log,
t_client: (new Date()).getTime(),
}, request);
}
private makeRequestApiConfig() {
return {
host: 'https://api-v3.findify.io',
jsonpCallbackPrefix: 'findifyCallback',
method: this.config.method || 'jsonp',
key: this.config.key,
};
}
private throwUserArgError() {
throw new Error('`user` param should be provided at request or at library config');
}
public constructor(config: FindifySDK.Config) {
if (!config || typeof config.key === 'undefined') {
throw new Error('"key" param is required');
}
this.config = config;
this.requestApiConfig = this.makeRequestApiConfig();
}
public autocomplete(request: FindifySDK.AutocompleteRequest) {
const extendedRequest = this.makeExtendedRequest(request);
if (!extendedRequest.user) {
this.throwUserArgError();
}
return requestApi('/autocomplete', extendedRequest, this.requestApiConfig);
}
}
type ExtendedRequest<Request> = Request & {
user: FindifySDK.User,
t_client: number,
log?: boolean,
};
type Request = FindifySDK.AutocompleteRequest;
export default SDK;
| import * as assign from 'lodash/assign';
import { requestApi, Config as RequestApiConfig } from './utils/requestApi';
class SDK {
private config: FindifySDK.Config;
private requestApiConfig: RequestApiConfig;
private makeExtendedRequest(request: Request) {
const extendedRequest = assign({}, {
user: this.config.user,
log: this.config.log,
t_client: (new Date()).getTime(),
}, request);
if (!extendedRequest.user) {
throw new Error('`user` param should be provided at request or at library config');
}
return extendedRequest;
}
private makeRequestApiConfig() {
return {
host: 'https://api-v3.findify.io',
jsonpCallbackPrefix: 'findifyCallback',
method: this.config.method || 'jsonp',
key: this.config.key,
};
}
public constructor(config: FindifySDK.Config) {
if (!config || typeof config.key === 'undefined') {
throw new Error('"key" param is required');
}
this.config = config;
this.requestApiConfig = this.makeRequestApiConfig();
}
public autocomplete(request: FindifySDK.AutocompleteRequest) {
const extendedRequest = this.makeExtendedRequest(request);
return requestApi('/autocomplete', extendedRequest, this.requestApiConfig);
}
}
type ExtendedRequest<Request> = Request & {
user: FindifySDK.User,
t_client: number,
log?: boolean,
};
type Request = FindifySDK.AutocompleteRequest;
export default SDK;
| Move "user" param validation to "makeExtendedRequest" function | Move "user" param validation to "makeExtendedRequest" function
| TypeScript | mit | findify/javascript-sdk,findify/javascript-sdk | ---
+++
@@ -7,11 +7,17 @@
private requestApiConfig: RequestApiConfig;
private makeExtendedRequest(request: Request) {
- return assign({}, {
+ const extendedRequest = assign({}, {
user: this.config.user,
log: this.config.log,
t_client: (new Date()).getTime(),
}, request);
+
+ if (!extendedRequest.user) {
+ throw new Error('`user` param should be provided at request or at library config');
+ }
+
+ return extendedRequest;
}
private makeRequestApiConfig() {
@@ -21,10 +27,6 @@
method: this.config.method || 'jsonp',
key: this.config.key,
};
- }
-
- private throwUserArgError() {
- throw new Error('`user` param should be provided at request or at library config');
}
public constructor(config: FindifySDK.Config) {
@@ -39,10 +41,6 @@
public autocomplete(request: FindifySDK.AutocompleteRequest) {
const extendedRequest = this.makeExtendedRequest(request);
- if (!extendedRequest.user) {
- this.throwUserArgError();
- }
-
return requestApi('/autocomplete', extendedRequest, this.requestApiConfig);
}
} |
536e8653ade3f593f338c3b66a916c4e38e1c00c | server/serve.ts | server/serve.ts | const process = require('process');
const loadApp = require('./apps');
import config from './config';
const seed = require('./seeds/');
import logger from './apps/lib/logger';
(async () => {
if (process.env.SEED_ON_START === 'true') {
await seed();
}
const app = await loadApp;
const listener = app.listen((process.env.PORT || config.port), () => {
const port = listener.address().port;
if (config.verbose) {
logger.info('Express server listening on port ' + port);
}
if (process.send) {
process.send({
port,
dbPath: config.db.storage
});
}
});
})();
| const process = require('process');
import loadApp from './apps'
import config from './config';
const seed = require('./seeds/');
import logger from './apps/lib/logger';
import connect from './instances/sequelize';
connect().then(async () => {
if (process.env.SEED_ON_START === 'true') {
await seed();
}
const app = await loadApp();
const listener = app.listen((process.env.PORT || config.port), () => {
const port = listener.address().port;
if (config.verbose) {
logger.info('Express server listening on port ' + port);
}
if (process.send) {
process.send({
port,
dbPath: config.db.storage
});
}
});
});
| Add db connection to startup. | Add db connection to startup.
| TypeScript | mit | CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/CMPD-Holiday-Gift,CodeForCharlotte/cmpd-holiday-gift-backend,CodeForCharlotte/cmpd-holiday-gift-backend | ---
+++
@@ -1,17 +1,20 @@
const process = require('process');
-const loadApp = require('./apps');
+import loadApp from './apps'
+
import config from './config';
const seed = require('./seeds/');
import logger from './apps/lib/logger';
+import connect from './instances/sequelize';
-(async () => {
+connect().then(async () => {
+
if (process.env.SEED_ON_START === 'true') {
await seed();
}
- const app = await loadApp;
+ const app = await loadApp();
const listener = app.listen((process.env.PORT || config.port), () => {
const port = listener.address().port;
@@ -25,4 +28,4 @@
});
}
});
-})();
+}); |
9d8f88555608145be312980dbb39dd0847a691bf | src/lib/codec-wrappers/codec.ts | src/lib/codec-wrappers/codec.ts | export interface Encoder {
encode(data: ImageData): Promise<ArrayBuffer | SharedArrayBuffer>;
}
export interface Decoder {
decode(data: ArrayBuffer): Promise<ImageBitmap>;
}
| export interface Encoder {
encode(data: ImageData): Promise<ArrayBuffer>;
}
export interface Decoder {
decode(data: ArrayBuffer): Promise<ImageBitmap>;
}
| Remove `SharedArrayBuffer` as an option | Remove `SharedArrayBuffer` as an option
| TypeScript | apache-2.0 | GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh | ---
+++
@@ -1,5 +1,5 @@
export interface Encoder {
- encode(data: ImageData): Promise<ArrayBuffer | SharedArrayBuffer>;
+ encode(data: ImageData): Promise<ArrayBuffer>;
}
export interface Decoder { |
15a41d0060a2005799b1096b255a1f48d5cdd03f | typescript/run-length-encoding/run-length-encoding.ts | typescript/run-length-encoding/run-length-encoding.ts | interface IRunLengthEncoding {
encode(data: string): string
decode(encodedData: string): string
}
export default class RunLengthEncoding implements IRunLengthEncoding {
encode(data: string): string {
throw new Error("Method not implemented.")
}
decode(encodedData: string): string {
throw new Error("Method not implemented.")
}
}
| export default class RunLengthEncoding {
static encode(data: string): string {
throw new Error("Method not implemented.")
}
static decode(encodedData: string): string {
throw new Error("Method not implemented.")
}
}
| Remove interface because encod and decode are static | Remove interface because encod and decode are static
| TypeScript | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | ---
+++
@@ -1,15 +1,9 @@
-interface IRunLengthEncoding {
- encode(data: string): string
- decode(encodedData: string): string
-
-}
-
-export default class RunLengthEncoding implements IRunLengthEncoding {
- encode(data: string): string {
+export default class RunLengthEncoding {
+ static encode(data: string): string {
throw new Error("Method not implemented.")
}
- decode(encodedData: string): string {
+ static decode(encodedData: string): string {
throw new Error("Method not implemented.")
}
|
97bb64b3c49a65ad765b09166b4205a058ffeb8d | src/BloomBrowserUI/bookEdit/toolbox/toolboxBootstrap.ts | src/BloomBrowserUI/bookEdit/toolbox/toolboxBootstrap.ts | /// <reference path="../../typings/jquery/jquery.d.ts" />
import * as $ from 'jquery';
import {restoreToolboxSettings} from './toolbox';
import {ReaderToolsModel} from './decodablereader/readertoolsmodel'
export function canUndo() :boolean {
return ReaderToolsModel.model !== null && ReaderToolsModel.model.shouldHandleUndo() && ReaderToolsModel.model.canUndo();
}
export function undo() {
ReaderToolsModel.model.undo();
}
//this is currently inserted by c#. TODO: get settings via ajax
declare function GetToolboxSettings():any;
$(document).ready(function() {
restoreToolboxSettings(GetToolboxSettings());
}); | /// <reference path="../../typings/jquery/jquery.d.ts" />
import * as $ from 'jquery';
import {restoreToolboxSettings} from './toolbox';
import {ReaderToolsModel} from './decodablereader/readerToolsModel'
export function canUndo() :boolean {
return ReaderToolsModel.model !== null && ReaderToolsModel.model.shouldHandleUndo() && ReaderToolsModel.model.canUndo();
}
export function undo() {
ReaderToolsModel.model.undo();
}
//this is currently inserted by c#. TODO: get settings via ajax
declare function GetToolboxSettings():any;
$(document).ready(function() {
restoreToolboxSettings(GetToolboxSettings());
}); | Fix case problem on import | Fix case problem on import
| TypeScript | mit | JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork | ---
+++
@@ -2,7 +2,7 @@
import * as $ from 'jquery';
import {restoreToolboxSettings} from './toolbox';
-import {ReaderToolsModel} from './decodablereader/readertoolsmodel'
+import {ReaderToolsModel} from './decodablereader/readerToolsModel'
export function canUndo() :boolean {
return ReaderToolsModel.model !== null && ReaderToolsModel.model.shouldHandleUndo() && ReaderToolsModel.model.canUndo(); |
dfb41165a989b798c7840d30cebe8b26ba9929c0 | saleor/static/dashboard-next/hooks/useBulkActions.ts | saleor/static/dashboard-next/hooks/useBulkActions.ts | import { useEffect } from "react";
import { maybe } from "../misc";
import useListSelector from "./useListSelector";
interface ConnectionNode {
id: string;
}
function useBulkActions(list: ConnectionNode[]) {
const listSelectorFuncs = useListSelector();
useEffect(() => listSelectorFuncs.reset, [
maybe(() => list.reduce((acc, curr) => acc + curr.id, ""))
]);
return listSelectorFuncs;
}
export default useBulkActions;
| import { useEffect } from "react";
import useListSelector from "./useListSelector";
interface ConnectionNode {
id: string;
}
function useBulkActions(list: ConnectionNode[]) {
const listSelectorFuncs = useListSelector();
useEffect(() => listSelectorFuncs.reset, [list === undefined, list === null]);
return listSelectorFuncs;
}
export default useBulkActions;
| Reset state only if list is undefined or null | Reset state only if list is undefined or null
| TypeScript | bsd-3-clause | UITools/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -1,6 +1,5 @@
import { useEffect } from "react";
-import { maybe } from "../misc";
import useListSelector from "./useListSelector";
interface ConnectionNode {
@@ -8,9 +7,7 @@
}
function useBulkActions(list: ConnectionNode[]) {
const listSelectorFuncs = useListSelector();
- useEffect(() => listSelectorFuncs.reset, [
- maybe(() => list.reduce((acc, curr) => acc + curr.id, ""))
- ]);
+ useEffect(() => listSelectorFuncs.reset, [list === undefined, list === null]);
return listSelectorFuncs;
} |
eeafb13948b62e53cbe2fa6601a30805071c8db0 | src/v2/Apps/Conversation/routes.tsx | src/v2/Apps/Conversation/routes.tsx | import loadable from "@loadable/component"
import { RouteConfig } from "found"
import { graphql } from "react-relay"
export const conversationRoutes: RouteConfig[] = [
{
path: "/user/conversations",
displayFullPage: true,
getComponent: () => loadable(() => import("./ConversationApp")),
query: graphql`
query routes_ConversationQuery {
me {
...ConversationApp_me
}
}
`,
prepareVariables: (params, props) => {
return {
first: 30,
}
},
cacheConfig: {
force: true,
},
},
{
path: "/user/conversations/:conversationID",
displayFullPage: true,
getComponent: () => loadable(() => import("./Routes/Conversation")),
prepareVariables: (params, _props) => {
return {
conversationID: params.conversationID,
}
},
query: graphql`
query routes_DetailQuery($conversationID: String!) {
me {
...Conversation_me @arguments(conversationID: $conversationID)
}
}
`,
cacheConfig: {
force: true,
},
},
]
| import loadable from "@loadable/component"
import { RouteConfig } from "found"
import { graphql } from "react-relay"
export const conversationRoutes: RouteConfig[] = [
{
path: "/user/conversations",
displayFullPage: true,
getComponent: () => loadable(() => import("./ConversationApp")),
query: graphql`
query routes_ConversationQuery {
me {
...ConversationApp_me
}
}
`,
prepareVariables: (params, props) => {
return {
first: 30,
}
},
cacheConfig: {
force: true,
},
},
{
path: "/user/conversations/:conversationID",
displayFullPage: true,
getComponent: () => loadable(() => import("./Routes/Conversation")),
prepareVariables: (params, _props) => {
return {
conversationID: params.conversationID,
}
},
query: graphql`
query routes_DetailQuery($conversationID: String!) {
me {
...Conversation_me @arguments(conversationID: $conversationID)
}
}
`,
cacheConfig: {
force: true,
},
ignoreScrollBehavior: true,
},
]
| Disable scroll position updates from ScrollManager for conversation | Disable scroll position updates from ScrollManager for conversation
The scrolling to bottom behavior when the conversation page renders was
broken on Chrome (Safari was fine). It turns out ScrollManager
interfered with our custom scrolling on the app. This commit disabled
it.
The scrolling behavior when adding a new message was not affected.
| TypeScript | mit | eessex/force,artsy/force,eessex/force,joeyAghion/force,artsy/force-public,oxaudo/force,eessex/force,artsy/force,joeyAghion/force,oxaudo/force,joeyAghion/force,oxaudo/force,oxaudo/force,artsy/force,artsy/force,joeyAghion/force,artsy/force-public,eessex/force | ---
+++
@@ -42,5 +42,6 @@
cacheConfig: {
force: true,
},
+ ignoreScrollBehavior: true,
},
] |
843a70453bf252c01df29ca361f8f392969ae8ab | src/Apps/Artist/Routes/Overview/Components/Genes.tsx | src/Apps/Artist/Routes/Overview/Components/Genes.tsx | import { Sans, Spacer, Tags } from "@artsy/palette"
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import styled from "styled-components"
const GeneFamily = styled.div``
interface Props {
artist: Genes_artist
}
export class Genes extends Component<Props> {
render() {
const { related } = this.props.artist
const { genes } = related
if (genes.edges.length === 0) {
return null
}
const tags = genes.edges.map(edge => edge.node)
return (
<GeneFamily>
<Sans size="2" weight="medium">
Related Categories
</Sans>
<Spacer mb={1} />
<Tags tags={tags} displayNum={8} />
</GeneFamily>
)
}
}
export const GenesFragmentContainer = createFragmentContainer(Genes, {
artist: graphql`
fragment Genes_artist on Artist {
related {
genes {
edges {
node {
href
name
}
}
}
}
}
`,
})
| import { Sans, Spacer, Tags } from "@artsy/palette"
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { data as sd } from "sharify"
import styled from "styled-components"
const GeneFamily = styled.div``
interface Props {
artist: Genes_artist
}
export class Genes extends Component<Props> {
render() {
const { related } = this.props.artist
const { genes } = related
if (genes.edges.length === 0) {
return null
}
const tags = genes.edges.map(edge => {
return { name: edge.node.name, href: sd.APP_URL + edge.node.href }
})
return (
<GeneFamily>
<Sans size="2" weight="medium">
Related Categories
</Sans>
<Spacer mb={1} />
<Tags tags={tags} displayNum={8} />
</GeneFamily>
)
}
}
export const GenesFragmentContainer = createFragmentContainer(Genes, {
artist: graphql`
fragment Genes_artist on Artist {
related {
genes {
edges {
node {
href
name
}
}
}
}
}
`,
})
| Add `APP_URL` to gene href | Add `APP_URL` to gene href
| TypeScript | mit | artsy/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction | ---
+++
@@ -2,6 +2,7 @@
import { Genes_artist } from "__generated__/Genes_artist.graphql"
import React, { Component } from "react"
import { createFragmentContainer, graphql } from "react-relay"
+import { data as sd } from "sharify"
import styled from "styled-components"
const GeneFamily = styled.div``
@@ -17,7 +18,9 @@
if (genes.edges.length === 0) {
return null
}
- const tags = genes.edges.map(edge => edge.node)
+ const tags = genes.edges.map(edge => {
+ return { name: edge.node.name, href: sd.APP_URL + edge.node.href }
+ })
return (
<GeneFamily>
<Sans size="2" weight="medium"> |
6b007a02352118e2769235f7ac2b2b67a32b109d | src/codecs/mozjpeg/encoder.ts | src/codecs/mozjpeg/encoder.ts | import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg_enc/mozjpeg_enc';
import wasmUrl from '../../../codecs/mozjpeg_enc/mozjpeg_enc.wasm';
import { EncodeOptions } from './encoder-meta';
import { initEmscriptenModule } from '../util';
let emscriptenModule: Promise<MozJPEGModule>;
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(mozjpeg_enc, wasmUrl);
const module = await emscriptenModule;
const resultView = module.encode(data.data, data.width, data.height, options);
// wasm can’t run on SharedArrayBuffers, so we hard-cast to ArrayBuffer.
return resultView.buffer as ArrayBuffer;
}
| import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg/enc/mozjpeg_enc';
import wasmUrl from '../../../codecs/mozjpeg/enc/mozjpeg_enc.wasm';
import { EncodeOptions } from './encoder-meta';
import { initEmscriptenModule } from '../util';
let emscriptenModule: Promise<MozJPEGModule>;
export async function encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
if (!emscriptenModule) emscriptenModule = initEmscriptenModule(mozjpeg_enc, wasmUrl);
const module = await emscriptenModule;
const resultView = module.encode(data.data, data.width, data.height, options);
// wasm can’t run on SharedArrayBuffers, so we hard-cast to ArrayBuffer.
return resultView.buffer as ArrayBuffer;
}
| Update paths for Squoosh PWA | Update paths for Squoosh PWA
| TypeScript | apache-2.0 | GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh,GoogleChromeLabs/squoosh | ---
+++
@@ -1,5 +1,5 @@
-import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg_enc/mozjpeg_enc';
-import wasmUrl from '../../../codecs/mozjpeg_enc/mozjpeg_enc.wasm';
+import mozjpeg_enc, { MozJPEGModule } from '../../../codecs/mozjpeg/enc/mozjpeg_enc';
+import wasmUrl from '../../../codecs/mozjpeg/enc/mozjpeg_enc.wasm';
import { EncodeOptions } from './encoder-meta';
import { initEmscriptenModule } from '../util';
|
917b90c63d7d9180456c87fd9721bb2bc4cbbaf9 | packages/truffle-db/src/loaders/index.ts | packages/truffle-db/src/loaders/index.ts | import { TruffleDB } from "truffle-db";
import { ArtifactsLoader } from "./artifacts";
import { schema as rootSchema } from "truffle-db/schema";
import { Workspace, schema } from "truffle-db/workspace";
const tmp = require("tmp");
import {
makeExecutableSchema
} from "@gnd/graphql-tools";
import { gql } from "apollo-server";
//dummy query here because of known issue with Apollo mutation-only schemas
const typeDefs = gql`
type Mutation {
loadArtifacts: Boolean
}
type Query {
dummy: String
}
`;
const resolvers = {
Mutation: {
loadArtifacts: {
resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => {
const tempDir = tmp.dirSync({ unsafeCleanup: true })
const compilationConfig = {
contracts_directory: contractsDirectory,
contracts_build_directory: tempDir.name,
all: true
}
const loader = new ArtifactsLoader(db, compilationConfig);
await loader.load()
tempDir.removeCallback();
return true;
}
}
}
}
export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
| import { TruffleDB } from "truffle-db";
import { ArtifactsLoader } from "./artifacts";
import { schema as rootSchema } from "truffle-db/schema";
import { Workspace, schema } from "truffle-db/workspace";
const tmp = require("tmp");
import {
makeExecutableSchema
} from "@gnd/graphql-tools";
import { gql } from "apollo-server";
//dummy query here because of known issue with Apollo mutation-only schemas
const typeDefs = gql`
type ArtifactsLoadPayload {
success: Boolean
}
type Mutation {
artifactsLoad: ArtifactsLoadPayload
}
type Query {
dummy: String
}
`;
const resolvers = {
Mutation: {
artifactsLoad: {
resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => {
const tempDir = tmp.dirSync({ unsafeCleanup: true })
const compilationConfig = {
contracts_directory: contractsDirectory,
contracts_build_directory: tempDir.name,
all: true
}
const loader = new ArtifactsLoader(db, compilationConfig);
await loader.load()
tempDir.removeCallback();
return true;
}
}
},
ArtifactsLoadPayload: {
success: {
resolve: () => true
}
}
}
export const loaderSchema = makeExecutableSchema({ typeDefs, resolvers });
| Return success: true when loader mutation is run | Return success: true when loader mutation is run
| TypeScript | mit | ConsenSys/truffle | ---
+++
@@ -10,8 +10,11 @@
//dummy query here because of known issue with Apollo mutation-only schemas
const typeDefs = gql`
+ type ArtifactsLoadPayload {
+ success: Boolean
+ }
type Mutation {
- loadArtifacts: Boolean
+ artifactsLoad: ArtifactsLoadPayload
}
type Query {
dummy: String
@@ -20,7 +23,7 @@
const resolvers = {
Mutation: {
- loadArtifacts: {
+ artifactsLoad: {
resolve: async (_, args, { artifactsDirectory, contractsDirectory, db }, info) => {
const tempDir = tmp.dirSync({ unsafeCleanup: true })
const compilationConfig = {
@@ -28,13 +31,17 @@
contracts_build_directory: tempDir.name,
all: true
}
-
const loader = new ArtifactsLoader(db, compilationConfig);
await loader.load()
tempDir.removeCallback();
return true;
}
}
+ },
+ ArtifactsLoadPayload: {
+ success: {
+ resolve: () => true
+ }
}
}
|
39f5376b52f99ae5d6e8ddbafde23da113805cd1 | packages/@glimmer/component/src/component-definition.ts | packages/@glimmer/component/src/component-definition.ts | import {
ComponentClass,
ComponentDefinition as GlimmerComponentDefinition
} from '@glimmer/runtime';
import ComponentManager from './component-manager';
import Component from './component';
import ComponentFactory from './component-factory';
export default class ComponentDefinition extends GlimmerComponentDefinition<Component> {
public name: string;
public manager: ComponentManager;
public ComponentClass: ComponentClass;
public componentFactory: ComponentFactory;
constructor(name: string, manager: ComponentManager, ComponentClass: ComponentClass) {
super(name, manager, ComponentClass);
this.componentFactory = new ComponentFactory(ComponentClass);
}
}
| import {
ComponentClass,
ComponentDefinition as GlimmerComponentDefinition,
CompiledDynamicProgram
} from '@glimmer/runtime';
import ComponentManager from './component-manager';
import Component from './component';
import ComponentFactory from './component-factory';
export default class ComponentDefinition extends GlimmerComponentDefinition<Component> {
public name: string;
public manager: ComponentManager;
public layout: CompiledDynamicProgram;
public ComponentClass: ComponentClass;
public componentFactory: ComponentFactory;
constructor(name: string, manager: ComponentManager, layout: CompiledDynamicProgram, ComponentClass: ComponentClass) {
super(name, manager, ComponentClass);
this.layout = layout;
this.componentFactory = new ComponentFactory(ComponentClass);
}
} | Store compiled layout on ComponentDefinition | Store compiled layout on ComponentDefinition | TypeScript | mit | glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js,glimmerjs/glimmer.js | ---
+++
@@ -1,6 +1,7 @@
import {
ComponentClass,
- ComponentDefinition as GlimmerComponentDefinition
+ ComponentDefinition as GlimmerComponentDefinition,
+ CompiledDynamicProgram
} from '@glimmer/runtime';
import ComponentManager from './component-manager';
import Component from './component';
@@ -9,11 +10,13 @@
export default class ComponentDefinition extends GlimmerComponentDefinition<Component> {
public name: string;
public manager: ComponentManager;
+ public layout: CompiledDynamicProgram;
public ComponentClass: ComponentClass;
public componentFactory: ComponentFactory;
- constructor(name: string, manager: ComponentManager, ComponentClass: ComponentClass) {
+ constructor(name: string, manager: ComponentManager, layout: CompiledDynamicProgram, ComponentClass: ComponentClass) {
super(name, manager, ComponentClass);
+ this.layout = layout;
this.componentFactory = new ComponentFactory(ComponentClass);
}
} |
103c7173df6ac76713ddf20b60b882018e740a12 | src/containers/message/globalMessage.tsx | src/containers/message/globalMessage.tsx | import * as React from 'react'
import {connect} from 'react-redux'
import Snackbar from 'material-ui/Snackbar'
import { hideGlobalMessage } from './actions'
interface IGlobalMessageProps {
isOpen: boolean,
message: string
}
interface IGlobalMessageState {
isOpen: boolean,
message: string
}
class GlobalMessage extends React.Component<IGlobalMessageProps, IGlobalMessageState> {
constructor(props) {
super(props);
}
render() {
return (
<Snackbar
open={this.props.isOpen}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.props.hideGlobalMessage}
/>
);
}
}
function mapStateToProps (state) {
return {
isOpen: state.message.isOpen,
message: state.message.message
}
}
const mapDispatchToProps = (dispatch) => {
return {
hideGlobalMessage: () => dispatch(hideGlobalMessage())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(GlobalMessage);
| import * as React from 'react'
import {connect} from 'react-redux'
import Snackbar from 'material-ui/Snackbar'
import { hideGlobalMessage } from './actions'
interface IGlobalMessageProps {
isOpen: boolean,
message: string,
hideGlobalMessage(note): void
}
interface IGlobalMessageState {
isOpen: boolean,
message: string
}
class GlobalMessage extends React.Component<IGlobalMessageProps, IGlobalMessageState> {
constructor(props) {
super(props);
}
render() {
return (
<Snackbar
open={this.props.isOpen}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.props.hideGlobalMessage}
/>
);
}
}
function mapStateToProps (state) {
return {
isOpen: state.message.isOpen,
message: state.message.message
}
}
const mapDispatchToProps = (dispatch) => {
return {
hideGlobalMessage: () => dispatch(hideGlobalMessage())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(GlobalMessage);
| Update global message props interface | Update global message props interface
| TypeScript | mit | frycz/frontend-boilerplate,frycz/quick-note,frycz/quick-note,frycz/frontend-boilerplate,frycz/frontend-boilerplate,frycz/quick-note | ---
+++
@@ -6,7 +6,8 @@
interface IGlobalMessageProps {
isOpen: boolean,
- message: string
+ message: string,
+ hideGlobalMessage(note): void
}
interface IGlobalMessageState { |
b955ccf31504d29bb5a6379caf27d16bb21a3d04 | packages/common/src/server/utils/cleanGlobPatterns.ts | packages/common/src/server/utils/cleanGlobPatterns.ts | import * as Path from "path";
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, ""));
return []
.concat(files as any)
.map((file: string) => {
if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
file = file.replace(/\.ts$/i, ".js");
}
return Path.resolve(file);
})
.concat(excludes as any);
}
| import * as Path from "path";
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, "").replace(/\\/g, "/"));
return []
.concat(files as any)
.map((file: string) => {
if (!require.extensions[".ts"] && !process.env["TS_TEST"]) {
file = file.replace(/\.ts$/i, ".js");
}
return Path.resolve(file).replace(/\\/g, "/");
})
.concat(excludes as any);
}
| Fix windows paths in scanner | fix(common): Fix windows paths in scanner
Closes: #709
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,7 +1,7 @@
import * as Path from "path";
export function cleanGlobPatterns(files: string | string[], excludes: string[]): string[] {
- excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, ""));
+ excludes = excludes.map((s: string) => "!" + s.replace(/!/gi, "").replace(/\\/g, "/"));
return []
.concat(files as any)
@@ -10,7 +10,7 @@
file = file.replace(/\.ts$/i, ".js");
}
- return Path.resolve(file);
+ return Path.resolve(file).replace(/\\/g, "/");
})
.concat(excludes as any);
} |
dd65834c2af56006041d3347a3262265e74080f8 | src/index.d.ts | src/index.d.ts | declare module 'react-native-modal' {
import { Component, ReactNode } from 'react'
import { StyleProp, ViewStyle } from 'react-native'
export interface ModalProps {
animationIn?: string
animationInTiming?: number
animationOut?: string
animationOutTiming?: number
backdropColor?: string
backdropOpacity?: number
backdropTransitionInTiming?: number
backdropTransitionOutTiming?: number
children: ReactNode
isVisible: boolean
onModalShow?: () => void
onModalHide?: () => void
onBackButtonPress?: () => void
onBackdropPress?: () => void
style?: StyleProp<ViewStyle>
}
class Modal extends Component<ModalProps> {}
export default Modal
}
| declare module 'react-native-modal' {
import { Component, ReactNode } from 'react'
import { StyleProp, ViewStyle } from 'react-native'
type AnimationConfig = string | { from: Object, to: Object }
export interface ModalProps {
animationIn?: AnimationConfig
animationInTiming?: number
animationOut?: AnimationConfig
animationOutTiming?: number
backdropColor?: string
backdropOpacity?: number
backdropTransitionInTiming?: number
backdropTransitionOutTiming?: number
children: ReactNode
isVisible: boolean
onModalShow?: () => void
onModalHide?: () => void
onBackButtonPress?: () => void
onBackdropPress?: () => void
style?: StyleProp<ViewStyle>
}
class Modal extends Component<ModalProps> {}
export default Modal
}
| Allow animation config to be string or object | feat(typings): Allow animation config to be string or object
| TypeScript | mit | react-native-community/react-native-modal,react-native-community/react-native-modal,react-native-community/react-native-modal,react-native-community/react-native-modal | ---
+++
@@ -2,10 +2,12 @@
import { Component, ReactNode } from 'react'
import { StyleProp, ViewStyle } from 'react-native'
+ type AnimationConfig = string | { from: Object, to: Object }
+
export interface ModalProps {
- animationIn?: string
+ animationIn?: AnimationConfig
animationInTiming?: number
- animationOut?: string
+ animationOut?: AnimationConfig
animationOutTiming?: number
backdropColor?: string
backdropOpacity?: number |
d7572de554268ac0f3fe05ae5fccaa338792ae16 | src/router.tsx | src/router.tsx | import * as React from 'react';
import { AppStore, Route } from './store';
import { reaction } from 'mobx';
import { observer } from 'mobx-react';
interface RouterProps {
store: AppStore;
}
interface RouterState {
Component: React.ComponentClass<{ appStore: AppStore }> | null;
}
@observer
export class Router extends React.Component<RouterProps, RouterState> {
constructor(props) {
super(props);
this.state = {
Component: null
};
}
componentDidMount() {
reaction(() => this.props.store.route, (name: Route) => this.route(name), { fireImmediately: true });
}
async route(name: Route) {
const target = await import('./containers/' + name);
this.setState({ Component: target.default });
}
render(): JSX.Element | null {
const { Component } = this.state;
if (Component) {
return <Component appStore={this.props.store} {...this.props.store.params} />;
}
return null;
}
}
| import * as React from 'react';
import { AppStore, Route } from './store';
import { reaction } from 'mobx';
import { observer } from 'mobx-react';
interface RouterProps {
store: AppStore;
}
interface RouterState {
Component: React.ComponentClass<{ appStore: AppStore }> | null;
}
@observer
export class Router extends React.Component<RouterProps, RouterState> {
constructor(props) {
super(props);
this.state = {
Component: null
};
}
componentDidMount() {
reaction(() => this.props.store.route, (name: Route) => this.route(name), { fireImmediately: true });
}
async route(name: Route) {
let target;
switch (name) {
case 'activities':
target = await import('./containers/activities');
break;
case 'video':
target = await import('./containers/video');
break;
}
this.setState({ Component: target.default });
}
render(): JSX.Element | null {
const { Component } = this.state;
if (Component) {
return <Component appStore={this.props.store} {...this.props.store.params} />;
}
return null;
}
}
| Fix issue with broken routing with fuse | fix: Fix issue with broken routing with fuse
| TypeScript | mit | misantronic/rbtv.ts.youtube,misantronic/rbtv.ts.youtube,misantronic/rbtv.ts.youtube | ---
+++
@@ -26,7 +26,16 @@
}
async route(name: Route) {
- const target = await import('./containers/' + name);
+ let target;
+
+ switch (name) {
+ case 'activities':
+ target = await import('./containers/activities');
+ break;
+ case 'video':
+ target = await import('./containers/video');
+ break;
+ }
this.setState({ Component: target.default });
} |
e98ef69d1c8d4e39e45a52b04b3abf5fd1af3b2c | client/src/assets/player/mobile/peertube-mobile-plugin.ts | client/src/assets/player/mobile/peertube-mobile-plugin.ts | import videojs from 'video.js'
import './peertube-mobile-buttons'
const Plugin = videojs.getPlugin('plugin')
class PeerTubeMobilePlugin extends Plugin {
constructor (player: videojs.Player, options: videojs.PlayerOptions) {
super(player, options)
player.addChild('PeerTubeMobileButtons')
}
}
videojs.registerPlugin('peertubeMobile', PeerTubeMobilePlugin)
export { PeerTubeMobilePlugin }
| import './peertube-mobile-buttons'
import videojs from 'video.js'
const Plugin = videojs.getPlugin('plugin')
class PeerTubeMobilePlugin extends Plugin {
constructor (player: videojs.Player, options: videojs.PlayerOptions) {
super(player, options)
player.addChild('PeerTubeMobileButtons')
if (videojs.browser.IS_ANDROID && screen.orientation) {
this.handleFullscreenRotation()
}
}
private handleFullscreenRotation () {
this.player.on('fullscreenchange', () => {
if (!this.player.isFullscreen() || this.isPortraitVideo()) return
screen.orientation.lock('landscape')
.catch(err => console.error('Cannot lock screen to landscape.', err))
})
}
private isPortraitVideo () {
return this.player.videoWidth() < this.player.videoHeight()
}
}
videojs.registerPlugin('peertubeMobile', PeerTubeMobilePlugin)
export { PeerTubeMobilePlugin }
| Move to landscape on mobile fullscreen | Move to landscape on mobile fullscreen
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -1,5 +1,5 @@
+import './peertube-mobile-buttons'
import videojs from 'video.js'
-import './peertube-mobile-buttons'
const Plugin = videojs.getPlugin('plugin')
@@ -9,6 +9,23 @@
super(player, options)
player.addChild('PeerTubeMobileButtons')
+
+ if (videojs.browser.IS_ANDROID && screen.orientation) {
+ this.handleFullscreenRotation()
+ }
+ }
+
+ private handleFullscreenRotation () {
+ this.player.on('fullscreenchange', () => {
+ if (!this.player.isFullscreen() || this.isPortraitVideo()) return
+
+ screen.orientation.lock('landscape')
+ .catch(err => console.error('Cannot lock screen to landscape.', err))
+ })
+ }
+
+ private isPortraitVideo () {
+ return this.player.videoWidth() < this.player.videoHeight()
}
}
|
7d426f8069f8d57d2c6ed17d0ee0e07e97c1e8cf | src/marketplace/resources/list/SupportResourcesFilter.tsx | src/marketplace/resources/list/SupportResourcesFilter.tsx | import React, { FunctionComponent } from 'react';
import { Row } from 'react-bootstrap';
import { reduxForm } from 'redux-form';
import { OfferingAutocomplete } from '@waldur/marketplace/offerings/details/OfferingAutocomplete';
import { OrganizationAutocomplete } from '@waldur/marketplace/orders/OrganizationAutocomplete';
import { CategoryFilter } from './CategoryFilter';
import { ResourceStateFilter } from './ResourceStateFilter';
const PureSupportResourcesFilter: FunctionComponent = () => (
<Row>
<OfferingAutocomplete />
<OrganizationAutocomplete />
<CategoryFilter />
<ResourceStateFilter />
</Row>
);
const enhance = reduxForm({ form: 'SupportResourcesFilter' });
export const SupportResourcesFilter = enhance(PureSupportResourcesFilter);
| import React, { FunctionComponent } from 'react';
import { Row } from 'react-bootstrap';
import { reduxForm } from 'redux-form';
import { OfferingAutocomplete } from '@waldur/marketplace/offerings/details/OfferingAutocomplete';
import { OrganizationAutocomplete } from '@waldur/marketplace/orders/OrganizationAutocomplete';
import { CategoryFilter } from './CategoryFilter';
import { getStates, ResourceStateFilter } from './ResourceStateFilter';
const PureSupportResourcesFilter: FunctionComponent = () => (
<Row>
<OfferingAutocomplete />
<OrganizationAutocomplete />
<CategoryFilter />
<ResourceStateFilter />
</Row>
);
const enhance = reduxForm({
form: 'SupportResourcesFilter',
initialValues: {
state: getStates().find(({ value }) => value === 'OK'),
},
});
export const SupportResourcesFilter = enhance(PureSupportResourcesFilter);
| Set default filter to OK for support/resources | [WAL-3754] Set default filter to OK for support/resources
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -6,7 +6,7 @@
import { OrganizationAutocomplete } from '@waldur/marketplace/orders/OrganizationAutocomplete';
import { CategoryFilter } from './CategoryFilter';
-import { ResourceStateFilter } from './ResourceStateFilter';
+import { getStates, ResourceStateFilter } from './ResourceStateFilter';
const PureSupportResourcesFilter: FunctionComponent = () => (
<Row>
@@ -17,6 +17,11 @@
</Row>
);
-const enhance = reduxForm({ form: 'SupportResourcesFilter' });
+const enhance = reduxForm({
+ form: 'SupportResourcesFilter',
+ initialValues: {
+ state: getStates().find(({ value }) => value === 'OK'),
+ },
+});
export const SupportResourcesFilter = enhance(PureSupportResourcesFilter); |
dffed37ec335c48e73129eb3bcf4104a030d5fec | test/test-bootstrap.ts | test/test-bootstrap.ts | global._ = require("underscore");
global.$injector = require("../lib/yok").injector;
$injector.require("config", "../lib/config");
$injector.require("resources", "../lib/resource-loader"); | global._ = require("underscore");
global.$injector = require("../lib/yok").injector;
$injector.require("config", "../lib/config");
$injector.require("resources", "../lib/resource-loader");
process.on('exit', (code: number) => {
require("fibers/future").assertNoFutureLeftBehind();
});
| Add check for outstanding fibres in unit tests | Add check for outstanding fibres in unit tests
| TypeScript | apache-2.0 | Icenium/icenium-cli,Icenium/icenium-cli | ---
+++
@@ -2,3 +2,7 @@
global.$injector = require("../lib/yok").injector;
$injector.require("config", "../lib/config");
$injector.require("resources", "../lib/resource-loader");
+
+process.on('exit', (code: number) => {
+ require("fibers/future").assertNoFutureLeftBehind();
+}); |
cfea2bb5005074978ad600703b2c429b456e31fc | client/Widgets/EventLog.ts | client/Widgets/EventLog.ts | module ImprovedInitiative {
export class EventLog {
Events = ko.observableArray<string>();
LatestEvent = ko.pureComputed(() => this.Events()[this.Events().length - 1] || "Welcome to Improved Initiative!");
EventsTail = ko.pureComputed(() => this.Events().slice(0, this.Events().length - 1));
AddEvent = (event: string) => {
this.Events.push(event);
this.scrollToBottomOfLog();
}
ToggleFullLog = () => {
if(this.ShowFullLog()) {
this.ShowFullLog(false);
$('.combatants').css('flex-shrink', 1);
} else {
this.ShowFullLog(true);
$('.combatants').css('flex-shrink', 0);
this.scrollToBottomOfLog();
}
}
ShowFullLog = ko.observable<boolean>(false);
private element = $('.event-log');
private scrollToBottomOfLog = () => {
let scrollHeight = this.element[0].scrollHeight;
this.element.scrollTop(scrollHeight);
}
}
} | module ImprovedInitiative {
export class EventLog {
Events = ko.observableArray<string>();
LatestEvent = ko.pureComputed(() => this.Events()[this.Events().length - 1] || "Welcome to Improved Initiative!");
EventsTail = ko.pureComputed(() => this.Events().slice(0, this.Events().length - 1));
AddEvent = (event: string) => {
this.Events.push(event);
}
ToggleFullLog = () => {
if(this.ShowFullLog()) {
this.ShowFullLog(false);
$('.combatants').css('flex-shrink', 1);
} else {
this.ShowFullLog(true);
$('.combatants').css('flex-shrink', 0);
this.scrollToBottomOfLog();
}
}
ShowFullLog = ko.observable<boolean>(false);
private element = $('.event-log');
private scrollToBottomOfLog = () => {
let scrollHeight = this.element[0].scrollHeight;
this.element.scrollTop(scrollHeight);
}
}
} | Remove scroll after every event for perf | Remove scroll after every event for perf
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -7,7 +7,6 @@
AddEvent = (event: string) => {
this.Events.push(event);
- this.scrollToBottomOfLog();
}
ToggleFullLog = () => { |
d44e12e11638877902201bde87c1097cb8c3a334 | app/dashboard.component.ts | app/dashboard.component.ts | import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: 'app/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1, 5));
}
gotoDetail(hero: Hero): void {}
}
| import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: 'app/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
private heroService: HeroService,
private router: Router) { }
ngOnInit(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1, 5));
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
| Implement gotoDetail method in DashboardComponent to navigation to hero detail on click from list item | Implement gotoDetail method in DashboardComponent to navigation to hero
detail on click from list item
| TypeScript | mit | jjhampton/angular2-tour-of-heroes,jjhampton/angular2-tour-of-heroes,jjhampton/angular2-tour-of-heroes | ---
+++
@@ -1,4 +1,5 @@
import { Component, OnInit } from '@angular/core';
+import { Router } from '@angular/router';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@@ -12,12 +13,17 @@
heroes: Hero[] = [];
- constructor(private heroService: HeroService) { }
+ constructor(
+ private heroService: HeroService,
+ private router: Router) { }
ngOnInit(): void {
this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1, 5));
}
- gotoDetail(hero: Hero): void {}
+ gotoDetail(hero: Hero): void {
+ let link = ['/detail', hero.id];
+ this.router.navigate(link);
+ }
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.