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
|
---|---|---|---|---|---|---|---|---|---|---|
d8cad41e06aed8a79c708cd6067a8b57e5146387 | src/index.ts | src/index.ts | export type something = boolean|number|string|object
export const isArray = (x: any): x is Array<any> => Array.isArray(x)
export const isString = (x: any): x is string => typeof x === "string"
export const isNum = (x: any): x is number => typeof x === "number"
export const isBool = (x: any): x is boolean => typeof x === "boolean"
export const isObject = (x: any): x is boolean =>
typeof x === "object" && !isArray(x)
export const isUndefined = (x: any): x is undefined => typeof x === "undefined"
export const isDefined = (x: any): x is something|null => !isUndefined(x)
export const exists = (x: any): x is something => isDefined(x) && x !== null
export const last = (x: Array<any>) => x[x.length - 1]
export const log = (...xs: Array<any>) => {
console.log(xs.length === 1 ? xs[0] : xs)
return last(xs)
}
export type Ar<T> = ReadonlyArray<T>
export type OneOrMore<T> = T | Ar<T>
| export type something = boolean|number|string|object
export const isArray = (x: any): x is Array<any> => Array.isArray(x)
export const isList = isArray
export const isString = (x: any): x is string => typeof x === "string"
export const isNum = (x: any): x is number => typeof x === "number"
export const isBool = (x: any): x is boolean => typeof x === "boolean"
export const isObject = (x: any): x is boolean =>
typeof x === "object" && !isArray(x)
export const isUndefined = (x: any): x is undefined => typeof x === "undefined"
export const isDefined = (x: any): x is something|null => !isUndefined(x)
export const exists = (x: any): x is something => isDefined(x) && x !== null
export const last = (x: Array<any>) => x[x.length - 1]
export const log = (...xs: Array<any>) => {
console.log(xs.length === 1 ? xs[0] : xs)
return last(xs)
}
export type List<T> = {
readonly [index: number]: T
readonly length: number
}
export type Dict<T> = {
readonly [key: string]: T
}
export type Obj<T> = Dict<T>
export type Record<T> = Readonly<T>
export type OneOrMore<T> = T | List<T>
export const list = <T>(...x: Array<T>): List<T> => x
export const dict = <T>(object: Obj<T>): Dict<T> => object
export const record = <T>(object: T): Record<T> => object
export type Ar<T> = ReadonlyArray<T>
export type OneOrMore<T> = T | Ar<T>
| Create immutable typings and constructors for native javascript objects and arrays | Create immutable typings and constructors for native javascript objects and arrays
| TypeScript | mit | bjoyx/power-belt,bjoyx/power-belt,bjoyx/power-belt | ---
+++
@@ -1,6 +1,7 @@
export type something = boolean|number|string|object
export const isArray = (x: any): x is Array<any> => Array.isArray(x)
+export const isList = isArray
export const isString = (x: any): x is string => typeof x === "string"
export const isNum = (x: any): x is number => typeof x === "number"
export const isBool = (x: any): x is boolean => typeof x === "boolean"
@@ -18,5 +19,24 @@
return last(xs)
}
+export type List<T> = {
+ readonly [index: number]: T
+ readonly length: number
+}
+
+export type Dict<T> = {
+ readonly [key: string]: T
+}
+export type Obj<T> = Dict<T>
+
+export type Record<T> = Readonly<T>
+
+export type OneOrMore<T> = T | List<T>
+
+export const list = <T>(...x: Array<T>): List<T> => x
+export const dict = <T>(object: Obj<T>): Dict<T> => object
+export const record = <T>(object: T): Record<T> => object
+
+
export type Ar<T> = ReadonlyArray<T>
export type OneOrMore<T> = T | Ar<T> |
a16e761a644071a05f98b87c992be49856894fe4 | src/index.ts | src/index.ts | // import 'core-js'; (npm i -D core-js)
export * from './class-decorators';
export * from './method-decorators';
export * from './parameter-decorators';
export * from './property-decorators';
| // Polyfills
// import 'core-js'; (npm i -D core-js)
export * from './class-decorators';
export * from './method-decorators';
//export * from './parameter-decorators';
//export * from './property-decorators';
| Comment empty decorator folders (parameter & property) | Comment empty decorator folders (parameter & property)
| TypeScript | mit | semagarcia/typescript-decorators,semagarcia/typescript-decorators | ---
+++
@@ -1,6 +1,7 @@
+// Polyfills
// import 'core-js'; (npm i -D core-js)
export * from './class-decorators';
export * from './method-decorators';
-export * from './parameter-decorators';
-export * from './property-decorators';
+//export * from './parameter-decorators';
+//export * from './property-decorators'; |
fea0dff895546ea3c041c5b4d9f52be30f1faf79 | src/main.tsx | src/main.tsx | import "core-js";
import { Dialog } from "material-ui";
import { Provider } from "mobx-react";
import * as OfflinePluginRuntime from "offline-plugin/runtime";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { App } from "./components/app";
import * as dialogStyle from "./dialog.scss";
import { stores } from "./stores";
(Dialog as any).defaultProps.className = dialogStyle.dialog;
(Dialog as any).defaultProps.contentClassName = dialogStyle.dialogContent;
// Installing ServiceWorker
if ( process.env.__PROD__ ) {
OfflinePluginRuntime.install();
}
ReactDOM.render(
<BrowserRouter>
<Provider {...stores}>
<Switch>
<Route path="/" component={App} />
</Switch>
</Provider>
</BrowserRouter>,
document.querySelector("#root"),
);
| import "core-js";
import { Dialog } from "material-ui";
import { Provider } from "mobx-react";
import * as OfflinePluginRuntime from "offline-plugin/runtime";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { App } from "./components/app";
import * as dialogStyle from "./dialog.scss";
import { PROD } from "./env";
import { stores } from "./stores";
(Dialog as any).defaultProps.className = dialogStyle.dialog;
(Dialog as any).defaultProps.contentClassName = dialogStyle.dialogContent;
// Installing ServiceWorker
if ( PROD ) {
OfflinePluginRuntime.install();
}
ReactDOM.render(
<BrowserRouter>
<Provider {...stores}>
<Switch>
<Route path="/" component={App} />
</Switch>
</Provider>
</BrowserRouter>,
document.querySelector("#root"),
);
| Fix NODE_ENV source to env.ts | Fix NODE_ENV source to env.ts
| TypeScript | agpl-3.0 | anontown/client,anontown/client,anontown/client | ---
+++
@@ -7,13 +7,14 @@
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { App } from "./components/app";
import * as dialogStyle from "./dialog.scss";
+import { PROD } from "./env";
import { stores } from "./stores";
(Dialog as any).defaultProps.className = dialogStyle.dialog;
(Dialog as any).defaultProps.contentClassName = dialogStyle.dialogContent;
// Installing ServiceWorker
-if ( process.env.__PROD__ ) {
+if ( PROD ) {
OfflinePluginRuntime.install();
}
|
293eed39c626eca5843307554836459ed99bb77e | src/app/Root.tsx | src/app/Root.tsx | import { withProfiler } from '@sentry/react';
import { HTML5Backend } from 'react-dnd-html5-backend';
import {
DndProvider,
MouseTransition,
MultiBackendOptions,
TouchTransition,
} from 'react-dnd-multi-backend';
import { TouchBackend } from 'react-dnd-touch-backend';
import { Provider } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import store from './store/store';
import { isiOSBrowser } from './utils/browsers';
// Wrap App with Sentry profiling
const WrappedApp = $featureFlags.sentry ? withProfiler(App) : App;
function Root() {
const options: MultiBackendOptions = {
backends: isiOSBrowser()
? [
{
id: 'touch',
backend: TouchBackend,
transition: TouchTransition,
options: { delayTouchStart: 150 },
},
]
: [
{ id: 'html5', backend: HTML5Backend, transition: MouseTransition },
{
id: 'touch',
backend: TouchBackend,
transition: TouchTransition,
options: { delayTouchStart: 150 },
},
],
};
return (
<Router>
<Provider store={store}>
<DndProvider options={options}>
<WrappedApp />
</DndProvider>
</Provider>
</Router>
);
}
export default Root;
| import { withProfiler } from '@sentry/react';
import { HTML5Backend } from 'react-dnd-html5-backend';
import {
DndProvider,
MouseTransition,
MultiBackendOptions,
TouchTransition,
} from 'react-dnd-multi-backend';
import { TouchBackend } from 'react-dnd-touch-backend';
import { Provider } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import store from './store/store';
// Wrap App with Sentry profiling
const WrappedApp = $featureFlags.sentry ? withProfiler(App) : App;
function Root() {
const options: MultiBackendOptions = {
backends: [
{ id: 'html5', backend: HTML5Backend, transition: MouseTransition },
{
id: 'touch',
backend: TouchBackend,
transition: TouchTransition,
options: { delayTouchStart: 150 },
},
],
};
return (
<Router>
<Provider store={store}>
<DndProvider options={options}>
<WrappedApp />
</DndProvider>
</Provider>
</Router>
);
}
export default Root;
| Revert "Temp: try removing native drag and drop for iOS" | Revert "Temp: try removing native drag and drop for iOS"
This reverts commit 1e0336c65445331ade43e68de8dcbf31be9ffd97.
| TypeScript | mit | DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM,DestinyItemManager/DIM | ---
+++
@@ -11,31 +11,21 @@
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import store from './store/store';
-import { isiOSBrowser } from './utils/browsers';
// Wrap App with Sentry profiling
const WrappedApp = $featureFlags.sentry ? withProfiler(App) : App;
function Root() {
const options: MultiBackendOptions = {
- backends: isiOSBrowser()
- ? [
- {
- id: 'touch',
- backend: TouchBackend,
- transition: TouchTransition,
- options: { delayTouchStart: 150 },
- },
- ]
- : [
- { id: 'html5', backend: HTML5Backend, transition: MouseTransition },
- {
- id: 'touch',
- backend: TouchBackend,
- transition: TouchTransition,
- options: { delayTouchStart: 150 },
- },
- ],
+ backends: [
+ { id: 'html5', backend: HTML5Backend, transition: MouseTransition },
+ {
+ id: 'touch',
+ backend: TouchBackend,
+ transition: TouchTransition,
+ options: { delayTouchStart: 150 },
+ },
+ ],
};
return (
<Router> |
50a508514f94b0de2c09026aabd3dedfbe3fd94a | app/src/lib/git/fetch.ts | app/src/lib/git/fetch.ts | import { git, envForAuthentication, expectedAuthenticationErrors } from './core'
import { Repository } from '../../models/repository'
import { User } from '../../models/user'
/** Fetch from the given remote. */
export async function fetch(repository: Repository, user: User | null, remote: string): Promise<void> {
const options = {
successExitCodes: new Set([ 0 ]),
env: envForAuthentication(user),
expectedErrors: expectedAuthenticationErrors(),
}
await git([ 'fetch', '--prune', remote ], repository.path, 'fetch', options)
}
/** Fetch a given refspec from the given remote. */
export async function fetchRefspec(repository: Repository, user: User | null, remote: string, refspec: string): Promise<void> {
const options = {
successExitCodes: new Set([ 0, 128 ]),
env: envForAuthentication(user),
expectedErrors: expectedAuthenticationErrors(),
}
await git([ 'fetch', remote, refspec ], repository.path, 'fetchRefspec', options)
}
| import { git, envForAuthentication, expectedAuthenticationErrors, GitError } from './core'
import { Repository } from '../../models/repository'
import { User } from '../../models/user'
/** Fetch from the given remote. */
export async function fetch(repository: Repository, user: User | null, remote: string): Promise<void> {
const options = {
successExitCodes: new Set([ 0 ]),
env: envForAuthentication(user),
expectedErrors: expectedAuthenticationErrors(),
}
const args = [ 'fetch', '--prune', remote ]
const result = await git(args, repository.path, 'fetch', options)
if (result.gitErrorDescription) {
return Promise.reject(new GitError(result, args))
}
return Promise.resolve()
}
/** Fetch a given refspec from the given remote. */
export async function fetchRefspec(repository: Repository, user: User | null, remote: string, refspec: string): Promise<void> {
const options = {
successExitCodes: new Set([ 0, 128 ]),
env: envForAuthentication(user),
expectedErrors: expectedAuthenticationErrors(),
}
const args = [ 'fetch', remote, refspec ]
const result = await git(args, repository.path, 'fetchRefspec', options)
if (result.gitErrorDescription) {
return Promise.reject(new GitError(result, args))
}
return Promise.resolve()
}
| Revert "cleanup check and rethrow" | Revert "cleanup check and rethrow"
This reverts commit 3df56c32782f966e438da0c596357208b4e9bf9a.
| TypeScript | mit | BugTesterTest/desktops,artivilla/desktop,desktop/desktop,say25/desktop,artivilla/desktop,artivilla/desktop,shiftkey/desktop,hjobrien/desktop,j-f1/forked-desktop,BugTesterTest/desktops,gengjiawen/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,gengjiawen/desktop,artivilla/desktop,BugTesterTest/desktops,gengjiawen/desktop,say25/desktop,kactus-io/kactus,say25/desktop,j-f1/forked-desktop,kactus-io/kactus,BugTesterTest/desktops,hjobrien/desktop,desktop/desktop,kactus-io/kactus,gengjiawen/desktop,hjobrien/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,hjobrien/desktop,desktop/desktop | ---
+++
@@ -1,4 +1,4 @@
-import { git, envForAuthentication, expectedAuthenticationErrors } from './core'
+import { git, envForAuthentication, expectedAuthenticationErrors, GitError } from './core'
import { Repository } from '../../models/repository'
import { User } from '../../models/user'
@@ -10,7 +10,14 @@
expectedErrors: expectedAuthenticationErrors(),
}
- await git([ 'fetch', '--prune', remote ], repository.path, 'fetch', options)
+ const args = [ 'fetch', '--prune', remote ]
+ const result = await git(args, repository.path, 'fetch', options)
+
+ if (result.gitErrorDescription) {
+ return Promise.reject(new GitError(result, args))
+ }
+
+ return Promise.resolve()
}
/** Fetch a given refspec from the given remote. */
@@ -21,6 +28,13 @@
expectedErrors: expectedAuthenticationErrors(),
}
- await git([ 'fetch', remote, refspec ], repository.path, 'fetchRefspec', options)
+ const args = [ 'fetch', remote, refspec ]
+ const result = await git(args, repository.path, 'fetchRefspec', options)
+
+ if (result.gitErrorDescription) {
+ return Promise.reject(new GitError(result, args))
+ }
+
+ return Promise.resolve()
}
|
c9c7e8c7b19e0a8d73cd61beb9169d270913b102 | webpack/server/partials/plugins.ts | webpack/server/partials/plugins.ts | import * as webpack from 'webpack'
import * as Options from 'webpack/models/Options'
export const partial = (c: Options.Interface): webpack.Configuration => ({
plugins: [
// Ignore all files on the frontend.
new webpack.IgnorePlugin(/\.css$/),
new webpack.NormalModuleReplacementPlugin(/\.css$/, 'node-noop'), // Ignore top-level `require`.
// Sourcemap stack traces from Node.
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true, // Prepend the text as it is (instead of wrapping it in a comment).
entryOnly: false, // Add the text to all generated files, not just the entry.
}),
/* Define global constants, configured at compile time.
*
* More info:
* blog.johnnyreilly.com/2016/07/using-webpacks-defineplugin-with-typescript.html
*/
new webpack.DefinePlugin({
/* We need to pass in the output root dir so that we know where to
* retrieve assets.
*
* Note: HtmlWebpackPlugin uses the `output.publicPath` set in the
* Webpack config to prepend the urls of the injects.
*
* More info:
* stackoverflow.com/questions/34620628/htmlwebpackplugin-injects-
* relative-path-files-which-breaks-when-loading-non-root
*/
__OUTPUT_DIR__: JSON.stringify(c.outputDir),
})
],
})
| import * as webpack from 'webpack'
import * as Options from 'webpack/models/Options'
export const partial = (c: Options.Interface): webpack.Configuration => ({
plugins: [
// Ignore all files on the frontend.
new webpack.IgnorePlugin(/\.css$/),
new webpack.NormalModuleReplacementPlugin(/\.css$/, 'node-noop'), // Ignore top-level `require`.
// Sourcemap stack traces from Node.
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true, // Prepend the text as it is (instead of wrapping it in a comment).
entryOnly: false, // Add the text to all generated files, not just the entry.
}),
/* Define global constants, configured at compile time.
*
* More info:
* blog.johnnyreilly.com/2016/07/using-webpacks-defineplugin-with-typescript.html
*/
new webpack.DefinePlugin({
/* We need to pass in the output root dir so that we know where to
* retrieve assets.
*
* Note: HtmlWebpackPlugin uses the `output.publicPath` set in the
* Webpack config to prepend the urls of the injects.
*
* More info:
* stackoverflow.com/questions/34620628/htmlwebpackplugin-injects-
* relative-path-files-which-breaks-when-loading-non-root
*/
__OUTPUT_DIR__: JSON.stringify(c.outputDir),
})
],
})
| Fix relative assets issue for non-root routes | Fix relative assets issue for non-root routes
| TypeScript | mit | devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity | ---
+++
@@ -1,5 +1,4 @@
import * as webpack from 'webpack'
-
import * as Options from 'webpack/models/Options'
export const partial = (c: Options.Interface): webpack.Configuration => ({ |
c0a9f545d32b688c4e49aed649eebc8a804b4518 | lib/store/watch.ts | lib/store/watch.ts | import { TextEditor } from "atom";
import { action } from "mobx";
import OutputStore from "./output";
import { log } from "./../utils";
import type Kernel from "./../kernel";
export default class WatchStore {
kernel: Kernel;
editor: TextEditor;
outputStore = new OutputStore();
autocompleteDisposable: atom$Disposable | null | undefined;
constructor(kernel: Kernel) {
this.kernel = kernel;
this.editor = atom.workspace.buildTextEditor({
softWrapped: true,
lineNumberGutterVisible: false,
});
const grammar = this.kernel.grammar;
if (grammar)
atom.grammars.assignLanguageMode(this.editor, grammar.scopeName);
this.editor.moveToTop();
this.editor.element.classList.add("watch-input");
}
@action
run = () => {
const code = this.getCode();
log("watchview running:", code);
if (code && code.length > 0) {
this.kernel.executeWatch(code, (result) => {
this.outputStore.appendOutput(result);
});
}
};
@action
setCode = (code: string) => {
this.editor.setText(code);
};
getCode = () => {
return this.editor.getText();
};
focus = () => {
this.editor.element.focus();
};
}
| import { TextEditor, Disposable } from "atom";
import { action } from "mobx";
import OutputStore from "./output";
import { log } from "./../utils";
import type Kernel from "./../kernel";
export default class WatchStore {
kernel: Kernel;
editor: TextEditor;
outputStore = new OutputStore();
autocompleteDisposable: Disposable | null | undefined;
constructor(kernel: Kernel) {
this.kernel = kernel;
this.editor = atom.workspace.buildTextEditor({
softWrapped: true,
lineNumberGutterVisible: false,
});
const grammar = this.kernel.grammar;
if (grammar)
atom.grammars.assignLanguageMode(this.editor, grammar.scopeName);
this.editor.moveToTop();
this.editor.element.classList.add("watch-input");
}
@action
run = () => {
const code = this.getCode();
log("watchview running:", code);
if (code && code.length > 0) {
this.kernel.executeWatch(code, (result) => {
this.outputStore.appendOutput(result);
});
}
};
@action
setCode = (code: string) => {
this.editor.setText(code);
};
getCode = () => {
return this.editor.getText();
};
focus = () => {
this.editor.element.focus();
};
}
| Replace atom$Disposable with imported Disposable | Replace atom$Disposable with imported Disposable
| TypeScript | mit | nteract/hydrogen,nteract/hydrogen | ---
+++
@@ -1,4 +1,4 @@
-import { TextEditor } from "atom";
+import { TextEditor, Disposable } from "atom";
import { action } from "mobx";
import OutputStore from "./output";
import { log } from "./../utils";
@@ -7,7 +7,7 @@
kernel: Kernel;
editor: TextEditor;
outputStore = new OutputStore();
- autocompleteDisposable: atom$Disposable | null | undefined;
+ autocompleteDisposable: Disposable | null | undefined;
constructor(kernel: Kernel) {
this.kernel = kernel; |
aa7676b498204c3db94e116eed9fed8f0fe8c0fc | ui/analyse/src/explorer/explorerXhr.ts | ui/analyse/src/explorer/explorerXhr.ts | import { OpeningData, TablebaseData } from './interfaces';
export function opening(endpoint: string, variant: VariantKey, fen: Fen, config, withGames: boolean): JQueryPromise<OpeningData> {
let url: string;
const params: any = {
fen,
moves: 12
};
if (!withGames) params.topGames = params.recentGames = 0;
if (config.db.selected() === 'masters') url = '/master';
else {
url = '/lichess';
params['variant'] = variant;
params['speeds[]'] = config.speed.selected();
params['ratings[]'] = config.rating.selected();
}
return $.ajax({
url: endpoint + url,
data: params,
cache: true
}).then((data: Partial<OpeningData>) => {
data.opening = true;
data.fen = fen;
return data as OpeningData;
});
}
export function tablebase(endpoint: string, variant: VariantKey, fen: Fen): JQueryPromise<TablebaseData> {
const effectiveVariant = (variant === 'fromPosition' || variant === 'chess960') ? 'standard' : variant;
return $.ajax({
url: endpoint + '/' + effectiveVariant,
data: { fen },
cache: true,
timeout: 30
}).then((data: Partial<TablebaseData>) => {
data.tablebase = true;
data.fen = fen;
return data as TablebaseData;
});
}
| import { OpeningData, TablebaseData } from './interfaces';
export function opening(endpoint: string, variant: VariantKey, fen: Fen, config, withGames: boolean): JQueryPromise<OpeningData> {
let url: string;
const params: any = {
fen,
moves: 12
};
if (!withGames) params.topGames = params.recentGames = 0;
if (config.db.selected() === 'masters') url = '/master';
else {
url = '/lichess';
params['variant'] = variant;
params['speeds[]'] = config.speed.selected();
params['ratings[]'] = config.rating.selected();
}
return $.ajax({
url: endpoint + url,
data: params,
cache: true
}).then((data: Partial<OpeningData>) => {
data.opening = true;
data.fen = fen;
return data as OpeningData;
});
}
export function tablebase(endpoint: string, variant: VariantKey, fen: Fen): JQueryPromise<TablebaseData> {
const effectiveVariant = (variant === 'fromPosition' || variant === 'chess960') ? 'standard' : variant;
return $.ajax({
url: endpoint + '/' + effectiveVariant,
data: { fen },
cache: true
}).then((data: Partial<TablebaseData>) => {
data.tablebase = true;
data.fen = fen;
return data as TablebaseData;
});
}
| Revert "configure timeout for tablebase requests" | Revert "configure timeout for tablebase requests"
This reverts commit 6b3c63ebb73f92399a1ea1cd6a61fc6847d919fd.
| TypeScript | agpl-3.0 | luanlv/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,luanlv/lila,arex1337/lila,arex1337/lila,luanlv/lila,arex1337/lila,luanlv/lila | ---
+++
@@ -30,8 +30,7 @@
return $.ajax({
url: endpoint + '/' + effectiveVariant,
data: { fen },
- cache: true,
- timeout: 30
+ cache: true
}).then((data: Partial<TablebaseData>) => {
data.tablebase = true;
data.fen = fen; |
b6f8a264c9b3eb6f4f9a1b37e59f750a4a6df49e | js/components/portal-dashboard/all-responses-popup/popup-student-response-list.tsx | js/components/portal-dashboard/all-responses-popup/popup-student-response-list.tsx | import React from "react";
import { Map } from "immutable";
import Answer from "../../../containers/portal-dashboard/answer";
import { getFormattedStudentName } from "../../../util/student-utils";
import css from "../../../../css/portal-dashboard/all-responses-popup/popup-student-response-list.less";
interface IProps {
students: any; // TODO: add type
isAnonymous: boolean;
currentQuestion?: Map<string, any>;
}
export class PopupStudentResponseList extends React.PureComponent<IProps> {
render() {
const { students, isAnonymous, currentQuestion } = this.props;
return (
<div className={css.responseTable} data-cy="popup-response-table">
{students && students.map((student: any, i: number) => {
const formattedName = getFormattedStudentName(isAnonymous, student);
return (
<div className={css.studentRow} key={`student ${i}`} data-cy="student-row">
{this.renderStudentNameWrapper(formattedName)}
<div className={`${css.studentResponse}`} data-cy="student-response">
<Answer question={currentQuestion} student={student} responsive={false} />
</div>
</div>
);
})}
</div>
);
}
private renderStudentNameWrapper(formattedName: string) {
return (
<div className={`${css.studentWrapper}`}>
<div className={css.spotlightSelectionCheckbox} data-cy="spotlight-selection-checkbox"></div>
<div className={css.studentName} data-cy="student-name">{formattedName}</div>
</div>
);
}
}
| import React from "react";
import { Map } from "immutable";
import Answer from "../../../containers/portal-dashboard/answer";
import { getFormattedStudentName } from "../../../util/student-utils";
import css from "../../../../css/portal-dashboard/all-responses-popup/popup-student-response-list.less";
interface IProps {
students: Map<any, any>;
isAnonymous: boolean;
currentQuestion?: Map<string, any>;
}
export class PopupStudentResponseList extends React.PureComponent<IProps> {
render() {
const { students, isAnonymous, currentQuestion } = this.props;
return (
<div className={css.responseTable} data-cy="popup-response-table">
{students && students.map((student: any, i: number) => {
const formattedName = getFormattedStudentName(isAnonymous, student);
return (
<div className={css.studentRow} key={`student ${i}`} data-cy="student-row">
{this.renderStudentNameWrapper(formattedName)}
<div className={css.studentResponse} data-cy="student-response">
<Answer question={currentQuestion} student={student} responsive={false} studentName={formattedName} />
</div>
</div>
);
})}
</div>
);
}
private renderStudentNameWrapper(formattedName: string) {
return (
<div className={css.studentWrapper}>
<div className={css.spotlightSelectionCheckbox} data-cy="spotlight-selection-checkbox"></div>
<div className={css.studentName} data-cy="student-name">{formattedName}</div>
</div>
);
}
}
| Fix student name in modal popup | Fix student name in modal popup
| TypeScript | mit | concord-consortium/portal-report,concord-consortium/portal-report,concord-consortium/portal-report,concord-consortium/portal-report | ---
+++
@@ -6,7 +6,7 @@
import css from "../../../../css/portal-dashboard/all-responses-popup/popup-student-response-list.less";
interface IProps {
- students: any; // TODO: add type
+ students: Map<any, any>;
isAnonymous: boolean;
currentQuestion?: Map<string, any>;
}
@@ -18,12 +18,11 @@
<div className={css.responseTable} data-cy="popup-response-table">
{students && students.map((student: any, i: number) => {
const formattedName = getFormattedStudentName(isAnonymous, student);
-
return (
<div className={css.studentRow} key={`student ${i}`} data-cy="student-row">
{this.renderStudentNameWrapper(formattedName)}
- <div className={`${css.studentResponse}`} data-cy="student-response">
- <Answer question={currentQuestion} student={student} responsive={false} />
+ <div className={css.studentResponse} data-cy="student-response">
+ <Answer question={currentQuestion} student={student} responsive={false} studentName={formattedName} />
</div>
</div>
);
@@ -34,7 +33,7 @@
private renderStudentNameWrapper(formattedName: string) {
return (
- <div className={`${css.studentWrapper}`}>
+ <div className={css.studentWrapper}>
<div className={css.spotlightSelectionCheckbox} data-cy="spotlight-selection-checkbox"></div>
<div className={css.studentName} data-cy="student-name">{formattedName}</div>
</div> |
6583ce26dcd12605c8427966153fcf93194696f6 | common/predictive-text/worker/index.ts | common/predictive-text/worker/index.ts | // Dummy module for getting environment setup.
class MyWorker {
public hello() {
return 'hello';
}
}
// The technique below allows code to work both in-browser and in Node.
if(typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = new MyWorker();
} else {
//@ts-ignore
window.worker = new MyWorker();
} | // Dummy module for getting environment setup.
let EXPORTS = {
hello() {
return 'hello';
}
}
// The technique below allows code to work both in-browser and in Node.
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = EXPORTS;
} else {
//@ts-ignore
window.worker = EXPORTS;
} | Use an object instead of a new class instance. | Use an object instead of a new class instance.
| TypeScript | apache-2.0 | tavultesoft/keymanweb,tavultesoft/keymanweb | ---
+++
@@ -1,14 +1,14 @@
// Dummy module for getting environment setup.
-class MyWorker {
- public hello() {
+let EXPORTS = {
+ hello() {
return 'hello';
}
}
// The technique below allows code to work both in-browser and in Node.
-if(typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
- module.exports = new MyWorker();
+if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
+ module.exports = EXPORTS;
} else {
//@ts-ignore
- window.worker = new MyWorker();
+ window.worker = EXPORTS;
} |
88aff2cad6a42ef0ce64bead55216c262ac4efb9 | src/base/lang.ts | src/base/lang.ts | module Base {
export function randomString(length: number, chars: string) {
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
export var ALPHA_NUMERIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export enum ComparisonResult {
GREATER_THAN,
EQUAL,
LESS_THAN
}
export function allPairs(arr1:Array<any>, arr2:Array<any>) {
let res: Array<Array<Char.Operation>> = [];
for (var first of arr1) {
for (var second of arr2) {
res.push([first, second]);
}
}
return res;
}
export function compare(first: any, second: any):ComparisonResult {
if (first < second) {
return ComparisonResult.LESS_THAN;
} else if (first > second) {
return ComparisonResult.GREATER_THAN;
}
return ComparisonResult.EQUAL;
}
export class IDGenerator {
constructor(private _counter:number = -1) {
}
next():number {
this._counter += 1;
return this._counter;
}
}
}
| module Base {
export function randomString(length: number, chars: string) {
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
export var ALPHA_NUMERIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export enum ComparisonResult {
GREATER_THAN,
EQUAL,
LESS_THAN
}
export function allPairs(arr1:Array<any>, arr2:Array<any>) {
let res: Array<Array<any>> = [];
for (var first of arr1) {
for (var second of arr2) {
res.push([first, second]);
}
}
return res;
}
export function compare(first: any, second: any):ComparisonResult {
if (first < second) {
return ComparisonResult.LESS_THAN;
} else if (first > second) {
return ComparisonResult.GREATER_THAN;
}
return ComparisonResult.EQUAL;
}
export class IDGenerator {
constructor(private _counter:number = -1) {
}
next():number {
this._counter += 1;
return this._counter;
}
}
}
| Fix compilation error in demo | Fix compilation error in demo
| TypeScript | mit | ryankaplan/pattern-based-ot,ryankaplan/pattern-based-ot,ryankaplan/pattern-based-ot | ---
+++
@@ -16,7 +16,7 @@
}
export function allPairs(arr1:Array<any>, arr2:Array<any>) {
- let res: Array<Array<Char.Operation>> = [];
+ let res: Array<Array<any>> = [];
for (var first of arr1) {
for (var second of arr2) {
res.push([first, second]); |
fa3954495a077999121763ae55bb925aa27ea044 | packages/apollo-client/src/util/Observable.ts | packages/apollo-client/src/util/Observable.ts | // This simplified polyfill attempts to follow the ECMAScript Observable proposal.
// See https://github.com/zenparsing/es-observable
import { Observable as LinkObservable } from 'apollo-link';
export type Subscription = ZenObservable.Subscription;
export type Observer<T> = ZenObservable.Observer<T>;
import $$observable from 'symbol-observable';
// rxjs interopt
export class Observable<T> extends LinkObservable<T> {
public [$$observable]() {
return this;
}
}
| // This simplified polyfill attempts to follow the ECMAScript Observable proposal.
// See https://github.com/zenparsing/es-observable
import { Observable as LinkObservable } from 'apollo-link';
export type Subscription = ZenObservable.Subscription;
export type Observer<T> = ZenObservable.Observer<T>;
import $$observable from 'symbol-observable';
// rxjs interopt
export class Observable<T> extends LinkObservable<T> {
public [$$observable]() {
return this;
}
public ['@@observable']() {
return this;
}
}
| Use @@observable in case rxjs was loaded before apollo | Use @@observable in case rxjs was loaded before apollo
| TypeScript | mit | apollographql/apollo-client,apollostack/apollo-client,apollostack/apollo-client,apollostack/apollo-client,apollographql/apollo-client | ---
+++
@@ -12,4 +12,8 @@
public [$$observable]() {
return this;
}
+
+ public ['@@observable']() {
+ return this;
+ }
} |
c893ea19ba5e6f62db95478e5b615d65f9b399a0 | src/app/core/animations.ts | src/app/core/animations.ts | import { trigger, state, transition, animate, style } from '@angular/animations';
export let slideAnimation = trigger('slide', [
// state('left', style({ transform: 'translateX(0)' })),
// state('right', style({ transform: 'translateX(-50%)' })),
transition('* => *', [
style({ transform: 'translateX(0)'}),
animate(300, style({ transform: 'translateX(-50%)' }))
])
]) | import { trigger, state, transition, animate, style } from '@angular/animations';
export let slideAnimation = trigger('slide', [
transition('* => *', [
style({transform: 'translateX(-100%)'}),
animate('150ms ease-in', style({transform: 'translateX(0%)'}))
])
]) | Change animation on tab switching. | Change animation on tab switching.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -1,11 +1,8 @@
import { trigger, state, transition, animate, style } from '@angular/animations';
export let slideAnimation = trigger('slide', [
-
- // state('left', style({ transform: 'translateX(0)' })),
- // state('right', style({ transform: 'translateX(-50%)' })),
transition('* => *', [
- style({ transform: 'translateX(0)'}),
- animate(300, style({ transform: 'translateX(-50%)' }))
+ style({transform: 'translateX(-100%)'}),
+ animate('150ms ease-in', style({transform: 'translateX(0%)'}))
])
]) |
29ce204f305f33dcedf6ab87ae37da8eb981a00b | frontend/app/framework/angular/title.component.ts | frontend/app/framework/angular/title.component.ts | /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
// tslint:disable: readonly-array
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '@app/framework/internal';
import { Types } from '@app/shared';
@Component({
selector: 'sqx-title[message]',
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TitleComponent implements OnDestroy, OnChanges {
private previousIndex: undefined | number;
@Input()
public url: any[] = ['./'];
@Input()
public message: string;
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly titleService: TitleService,
) {
}
public ngOnChanges() {
const routeTree = this.router.createUrlTree(this.url, { relativeTo: this.route });
const routeUrl = this.router.serializeUrl(routeTree);
this.previousIndex = this.titleService.push(this.message, this.previousIndex, routeUrl);
}
public ngOnDestroy() {
if (Types.isNumber(this.previousIndex)) {
this.titleService.pop();
}
}
}
| /*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
// tslint:disable: readonly-array
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService, Types } from '@app/framework/internal';
@Component({
selector: 'sqx-title[message]',
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TitleComponent implements OnDestroy, OnChanges {
private previousIndex: undefined | number;
@Input()
public url: any[] = ['./'];
@Input()
public message: string;
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly titleService: TitleService,
) {
}
public ngOnChanges() {
const routeTree = this.router.createUrlTree(this.url, { relativeTo: this.route });
const routeUrl = this.router.serializeUrl(routeTree);
this.previousIndex = this.titleService.push(this.message, this.previousIndex, routeUrl);
}
public ngOnDestroy() {
if (Types.isNumber(this.previousIndex)) {
this.titleService.pop();
}
}
}
| Fix build and circular dependency. | Fix build and circular dependency.
| TypeScript | mit | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | ---
+++
@@ -9,8 +9,7 @@
import { ChangeDetectionStrategy, Component, Input, OnChanges, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
-import { TitleService } from '@app/framework/internal';
-import { Types } from '@app/shared';
+import { TitleService, Types } from '@app/framework/internal';
@Component({
selector: 'sqx-title[message]', |
aed954e4e6e8beabd47268916ff0955fbb20682d | bin/src/run/alternateScreen.ts | bin/src/run/alternateScreen.ts | import ansiEscape from 'ansi-escapes';
import { stderr } from '../logging';
const SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';
const HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';
export default function alternateScreen (enabled: boolean) {
if (!enabled) {
let needAnnounce = true;
return {
open () { },
close () { },
reset (heading: string) {
if (needAnnounce) {
stderr(heading);
needAnnounce = false;
}
}
};
}
return {
open () {
process.stderr.write(SHOW_ALTERNATE_SCREEN);
},
close () {
process.stderr.write(HIDE_ALTERNATE_SCREEN);
},
reset (heading: string) {
stderr(`${ansiEscape.eraseScreen}${ansiEscape.cursorTo(0, 0)}${heading}`);
}
};
}
| import ansiEscape from 'ansi-escapes';
import { stderr } from '../logging';
const SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';
const HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';
const isWindows = process.platform === 'win32';
const isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);
const isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';
const supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;
export default function alternateScreen (enabled: boolean) {
if (!enabled) {
let needAnnounce = true;
return {
open () { },
close () { },
reset (heading: string) {
if (needAnnounce) {
stderr(heading);
needAnnounce = false;
}
}
};
}
return {
open () {
if (supportsAnsi) {
process.stderr.write(SHOW_ALTERNATE_SCREEN);
}
},
close () {
if (supportsAnsi) {
process.stderr.write(HIDE_ALTERNATE_SCREEN);
}
},
reset (heading: string) {
stderr(`${ansiEscape.eraseScreen}${ansiEscape.cursorTo(0, 0)}${heading}`);
}
};
}
| Fix rollup watch crashes in cmd or powershell | Fix rollup watch crashes in cmd or powershell
| TypeScript | mit | corneliusweig/rollup | ---
+++
@@ -3,6 +3,11 @@
const SHOW_ALTERNATE_SCREEN = '\u001B[?1049h';
const HIDE_ALTERNATE_SCREEN = '\u001B[?1049l';
+
+const isWindows = process.platform === 'win32';
+const isMintty = isWindows && !!(process.env.SHELL || process.env.TERM);
+const isConEmuAnsiOn = (process.env.ConEmuANSI || '').toLowerCase() === 'on';
+const supportsAnsi = !isWindows || isMintty || isConEmuAnsiOn;
export default function alternateScreen (enabled: boolean) {
if (!enabled) {
@@ -21,10 +26,14 @@
return {
open () {
- process.stderr.write(SHOW_ALTERNATE_SCREEN);
+ if (supportsAnsi) {
+ process.stderr.write(SHOW_ALTERNATE_SCREEN);
+ }
},
close () {
- process.stderr.write(HIDE_ALTERNATE_SCREEN);
+ if (supportsAnsi) {
+ process.stderr.write(HIDE_ALTERNATE_SCREEN);
+ }
},
reset (heading: string) {
stderr(`${ansiEscape.eraseScreen}${ansiEscape.cursorTo(0, 0)}${heading}`); |
b5ffe6fef6bad333cbe7e3e08af7c3ea01ad292a | tests/cases/fourslash/callOrderDependence.ts | tests/cases/fourslash/callOrderDependence.ts | /// <reference path="fourslash.ts" />
/////**/
// Bug 768028
// FourSlash.currentTestState.enableIncrementalUpdateValidation = false;
edit.replace(0,0,"function foo(bar) {\n b\n}\n");
goTo.position(27);
FourSlash.currentTestState.getCompletionListAtCaret().entries
.forEach(entry =>
console.log(FourSlash.currentTestState.getCompletionEntryDetails(entry.name)));
| /// <reference path="fourslash.ts" />
/////**/
// Bug 768028
// FourSlash.currentTestState.enableIncrementalUpdateValidation = false;
edit.replace(0,0,"function foo(bar) {\n b\n}\n");
goTo.position(27);
FourSlash.currentTestState.getCompletionListAtCaret().entries
.forEach(entry => FourSlash.currentTestState.getCompletionEntryDetails(entry.name));
| Remove console logging from test | Remove console logging from test
| TypeScript | apache-2.0 | popravich/typescript,mbebenita/shumway.ts,fdecampredon/jsx-typescript-old-version,fdecampredon/jsx-typescript-old-version,hippich/typescript,hippich/typescript,hippich/typescript,mbebenita/shumway.ts,popravich/typescript,popravich/typescript,fdecampredon/jsx-typescript-old-version,mbebenita/shumway.ts | ---
+++
@@ -7,5 +7,4 @@
edit.replace(0,0,"function foo(bar) {\n b\n}\n");
goTo.position(27);
FourSlash.currentTestState.getCompletionListAtCaret().entries
- .forEach(entry =>
- console.log(FourSlash.currentTestState.getCompletionEntryDetails(entry.name)));
+ .forEach(entry => FourSlash.currentTestState.getCompletionEntryDetails(entry.name)); |
58942d704d0794fbf2221f73e53d9cf5a79e5adc | src/main/cpu.ts | src/main/cpu.ts | export class CPU {
registers: number[] = new Array(16).fill(0);
I = 0;
get V0() { return this.registers[0x0]; }
get V1() { return this.registers[0x1]; }
get V2() { return this.registers[0x2]; }
get V3() { return this.registers[0x3]; }
get V4() { return this.registers[0x4]; }
get V5() { return this.registers[0x5]; }
get V6() { return this.registers[0x6]; }
get V7() { return this.registers[0x7]; }
get V8() { return this.registers[0x8]; }
get V9() { return this.registers[0x9]; }
get VA() { return this.registers[0xA]; }
get VB() { return this.registers[0xB]; }
get VC() { return this.registers[0xC]; }
get VD() { return this.registers[0xD]; }
get VE() { return this.registers[0xE]; }
get VF() { return this.registers[0xF]; }
execute(opcode: number): CPU {
const registerIndex = ((opcode & 0x0F00) >> 8);
this.registers[registerIndex] = opcode & 0xFF;
return this;
}
}
| export class CPU {
registers: number[] = new Array(16).fill(0);
I = 0;
get V0() { return this.registers[0x0]; }
get V1() { return this.registers[0x1]; }
get V2() { return this.registers[0x2]; }
get V3() { return this.registers[0x3]; }
get V4() { return this.registers[0x4]; }
get V5() { return this.registers[0x5]; }
get V6() { return this.registers[0x6]; }
get V7() { return this.registers[0x7]; }
get V8() { return this.registers[0x8]; }
get V9() { return this.registers[0x9]; }
get VA() { return this.registers[0xA]; }
get VB() { return this.registers[0xB]; }
get VC() { return this.registers[0xC]; }
get VD() { return this.registers[0xD]; }
get VE() { return this.registers[0xE]; }
get VF() { return this.registers[0xF]; }
execute(opcode: number): CPU {
const firstRegisterIndex = ((opcode & 0x0F00) >> 8);
const constValue = opcode & 0xFF;
switch (((opcode & 0xF000) >> 12)) {
case 0x6:
this.registers[firstRegisterIndex] = constValue;
break;
}
return this;
}
}
| Refactor de CPU.execute avec un switch | Refactor de CPU.execute avec un switch
| TypeScript | unlicense | cybrown/chip8,cybrown/chip8 | ---
+++
@@ -21,8 +21,13 @@
get VF() { return this.registers[0xF]; }
execute(opcode: number): CPU {
- const registerIndex = ((opcode & 0x0F00) >> 8);
- this.registers[registerIndex] = opcode & 0xFF;
+ const firstRegisterIndex = ((opcode & 0x0F00) >> 8);
+ const constValue = opcode & 0xFF;
+ switch (((opcode & 0xF000) >> 12)) {
+ case 0x6:
+ this.registers[firstRegisterIndex] = constValue;
+ break;
+ }
return this;
}
} |
7958f45d24461ea0ded4e87a5d3a0b5509b2681b | source/services/timezone/timezone.service.tests.ts | source/services/timezone/timezone.service.tests.ts | import { timezone } from './timezone.service';
import { defaultFormats } from '../date/date.module';
import * as moment from 'moment';
import 'moment-timezone';
describe('timezone', (): void => {
it('should return the timezone', (): void => {
let date: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
expect(timezone.getTimezone(date)).to.equal('-07:00');
});
}); | import { timezone } from './timezone.service';
import { defaultFormats } from '../date/date.module';
import * as moment from 'moment';
import 'moment-timezone';
describe('timezone', (): void => {
it('should return the timezone', (): void => {
let date: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
expect(timezone.getTimezone(date)).to.equal('-07:00');
});
it('should handle daylight savings time', (): void => {
let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
expect(timezone.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00');
expect(timezone.getTimezone(dateWithDaylightSavings)).to.equal('-07:00');
});
}); | Verify that moment handles daylight savings time correctly. We can just pass a consistent timezone offset to the client and let moment handle daylight savings time internally. | Verify that moment handles daylight savings time correctly. We can just pass a consistent timezone offset to the client and let moment handle daylight savings time internally.
| TypeScript | mit | RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities,RenovoSolutions/TypeScript-Angular-Utilities,SamGraber/TypeScript-Angular-Utilities | ---
+++
@@ -9,4 +9,11 @@
let date: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
expect(timezone.getTimezone(date)).to.equal('-07:00');
});
+
+ it('should handle daylight savings time', (): void => {
+ let dateWithoutDaylightSavings: moment.Moment = moment('2016-2-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
+ let dateWithDaylightSavings: moment.Moment = moment('2016-4-1T12:00:00-07:00', defaultFormats.isoFormat).tz('America/Los_Angeles');
+ expect(timezone.getTimezone(dateWithoutDaylightSavings)).to.equal('-08:00');
+ expect(timezone.getTimezone(dateWithDaylightSavings)).to.equal('-07:00');
+ });
}); |
b74a4beb3e682a4e9bd69595a7293430bc1186d5 | src/components/PlayerAudio.tsx | src/components/PlayerAudio.tsx | import React from 'react';
interface IProps {
stream: string;
userState: any; // todo
onChange: any;
}
class PlayerAudio extends React.Component<IProps> {
private audioEl: any;
componentWillUpdate(nextProps: IProps) {
const { userState } = this.props;
if (nextProps.userState !== userState) {
if (nextProps.userState) {
this.audioEl.play();
} else {
this.audioEl.pause();
}
}
}
render() {
const { stream } = this.props;
return (
<audio
src={
stream === 'live'
? 'http://uk2.internet-radio.com:30764/stream'
: stream
}
ref={ref => (this.audioEl = ref)}
/>
);
}
}
export default PlayerAudio;
| import React from 'react';
interface IProps {
stream: string;
userState: any; // todo
onChange: any;
}
interface IState {
cacheKey: number
}
class PlayerAudio extends React.Component<IProps, IState> {
private audioEl: any;
constructor(props: IProps) {
super(props);
this.state = {
cacheKey: Math.random(),
};
}
componentWillUpdate(nextProps: IProps) {
const { userState } = this.props;
if (nextProps.userState !== userState) {
if (nextProps.userState) {
this.audioEl.play();
} else {
this.audioEl.pause();
this.setState({ cacheKey: Math.random() })
}
}
}
render() {
const { stream } = this.props;
return (
<audio
src={
stream === 'live'
? `http://uk2.internet-radio.com:30764/stream?nocache=${this.state.cacheKey}`
: stream
}
ref={ref => (this.audioEl = ref)}
/>
);
}
}
export default PlayerAudio;
| Fix FireFox audio caching issue | Fix FireFox audio caching issue
| TypeScript | mit | urfonline/frontend,urfonline/frontend,urfonline/frontend | ---
+++
@@ -6,8 +6,20 @@
onChange: any;
}
-class PlayerAudio extends React.Component<IProps> {
+interface IState {
+ cacheKey: number
+}
+
+class PlayerAudio extends React.Component<IProps, IState> {
private audioEl: any;
+
+ constructor(props: IProps) {
+ super(props);
+
+ this.state = {
+ cacheKey: Math.random(),
+ };
+ }
componentWillUpdate(nextProps: IProps) {
const { userState } = this.props;
@@ -17,6 +29,7 @@
this.audioEl.play();
} else {
this.audioEl.pause();
+ this.setState({ cacheKey: Math.random() })
}
}
}
@@ -28,7 +41,7 @@
<audio
src={
stream === 'live'
- ? 'http://uk2.internet-radio.com:30764/stream'
+ ? `http://uk2.internet-radio.com:30764/stream?nocache=${this.state.cacheKey}`
: stream
}
ref={ref => (this.audioEl = ref)} |
cb700d0bf01a426c261f9cb873230cb7502ca5ee | src/utils/index.ts | src/utils/index.ts | import { Grid, Row, Column, Diagonal } from '../definitions';
export function getRows(grid: Grid): Row[] {
const length = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(length).map(() => copy.splice(0, length));
}
export function getColumns(grid: Grid): Column[] {
return getRows(transpose(grid));
}
export function getDiagonals(grid: Grid): Diagonal[] {
// TODO: Make it work
return [];
}
function getArray(length: number) {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
}
| import { Grid, Row, Column, Diagonal } from '../definitions';
export function getRows(grid: Grid): Row[] {
const size = Math.sqrt(grid.length);
const copy = grid.concat([]);
return getArray(size).map(() => copy.splice(0, size));
}
export function getColumns(grid: Grid): Column[] {
return getRows(transpose(grid));
}
export function getDiagonals(grid: Grid): Diagonal[] {
// TODO: Make it work
return [];
}
function getArray(length: number) {
return Array.apply(null, { length }).map(Number.call, Number);
}
export function transpose<T>(grid: Array<T>): Array<T> {
const size = Math.sqrt(grid.length);
return grid.map((x, i) => grid[Math.floor(i / size) + ((i % size) * size)]);
}
| Rename local variable length to size | Rename local variable length to size
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -1,9 +1,9 @@
import { Grid, Row, Column, Diagonal } from '../definitions';
export function getRows(grid: Grid): Row[] {
- const length = Math.sqrt(grid.length);
+ const size = Math.sqrt(grid.length);
const copy = grid.concat([]);
- return getArray(length).map(() => copy.splice(0, length));
+ return getArray(size).map(() => copy.splice(0, size));
}
export function getColumns(grid: Grid): Column[] { |
424dc0ec03c79e978b8f4bbd192f16ab0bd69236 | types/p-defer/p-defer-tests.ts | types/p-defer/p-defer-tests.ts | import pDefer = require('p-defer');
function delay(deferred: pDefer.DeferredPromise<string>, ms: number) {
setTimeout(deferred.resolve, ms, '🦄');
return deferred.promise;
}
let s: string;
async function f() { s = await delay(pDefer<string>(), 100); }
| import pDefer = require('p-defer');
function delay(deferred: pDefer.DeferredPromise<string>, ms: number) {
setTimeout(deferred.resolve, ms, '🦄');
return deferred.promise;
}
let s: string;
async function f() { s = await delay(pDefer<string>(), 100); }
async function u() {
const u: Promise<any> = pDefer().resolve();
}
| Test for calling p-defer's resolve without any arguments | Test for calling p-defer's resolve without any arguments | TypeScript | mit | magny/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,markogresak/DefinitelyTyped,mcliment/DefinitelyTyped | ---
+++
@@ -7,3 +7,7 @@
let s: string;
async function f() { s = await delay(pDefer<string>(), 100); }
+
+async function u() {
+ const u: Promise<any> = pDefer().resolve();
+} |
d5c48ee05303f9b3759ea8665d78a2132a50894f | tests/__tests__/synthetic-default-imports.spec.ts | tests/__tests__/synthetic-default-imports.spec.ts | import runJest from '../__helpers__/runJest';
describe('synthetic default imports', () => {
it('should not work when the compiler option is false', () => {
const result = runJest('../no-synthetic-default', ['--no-cache']);
const stderr = result.stderr.toString();
expect(result.status).toBe(1);
expect(stderr).toContain(
`TypeError: Cannot read property 'someExport' of undefined`,
);
expect(stderr).toContain('module.test.ts:6:15');
});
it('should work when the compiler option is true', () => {
const result = runJest('../synthetic-default', ['--no-cache']);
expect(result.status).toBe(0);
});
});
| import runJest from '../__helpers__/runJest';
describe('synthetic default imports', () => {
it('should not work when the compiler option is false', () => {
const result = runJest('../no-synthetic-default', ['--no-cache']);
const stderr = result.stderr.toString();
expect(result.status).toBe(1);
expect(stderr).toContain(
`TypeError: Cannot read property 'someExport' of undefined`,
);
expect(stderr).toContain('module.test.ts:6');
});
it('should work when the compiler option is true', () => {
const result = runJest('../synthetic-default', ['--no-cache']);
expect(result.status).toBe(0);
});
});
| Remove the column number from the check | Remove the column number from the check | TypeScript | mit | kulshekhar/ts-jest,kulshekhar/ts-jest | ---
+++
@@ -10,7 +10,7 @@
expect(stderr).toContain(
`TypeError: Cannot read property 'someExport' of undefined`,
);
- expect(stderr).toContain('module.test.ts:6:15');
+ expect(stderr).toContain('module.test.ts:6');
});
it('should work when the compiler option is true', () => { |
c541c4fae74193cf66f64ab148cf69824b487f9e | lib/utils/remoteable.ts | lib/utils/remoteable.ts | import {SupertypeSession, SupertypeLogger} from 'supertype';
import {Persistor} from 'Persistor';
type Constructable<BC> = new (...args: any[]) => BC;
export class AmorphicSession extends SupertypeSession {
connectSession : any
withoutChangeTracking (callback : Function) {};
config : any;
}
export class amorphicStatic {
static logger : SupertypeLogger;
static config : any;
static beginDefaultTransaction() : any {}
static beginTransaction(nodefault? : boolean) : any {}
static endTransaction(persistorTransaction?, logger?) : any {}
static begin (isdefault?) : any {}
static end (persistorTransaction?, logger?) : any {};
static commit (options?) : any {};
static createTransientObject(callback : any) : any {};
static __transient__ : any
}
export function Remoteable<BC extends Constructable<{}>>(Base: BC) {
return class extends Base {
amorphicate (obj : any) {}
amorphic : AmorphicSession
};
}
| import {SupertypeSession, SupertypeLogger} from 'supertype';
import {Persistor} from 'Persistor';
type Constructable<BC> = new (...args: any[]) => BC;
export class AmorphicSession extends SupertypeSession {
connectSession : any
withoutChangeTracking (callback : Function) {};
config : any;
}
export class amorphicStatic {
static logger : SupertypeLogger;
static config : any;
static beginDefaultTransaction() : any {}
static beginTransaction(nodefault? : boolean) : any {}
static endTransaction(persistorTransaction?, logger?) : any {}
static begin (isdefault?) : any {}
static end (persistorTransaction?, logger?) : any {};
static commit (options?) : any {};
static createTransientObject(callback : any) : any {};
static __transient__ : any;
static __dictionary__: any;
}
export function Remoteable<BC extends Constructable<{}>>(Base: BC) {
return class extends Base {
amorphicate (obj : any) {}
amorphic : AmorphicSession
};
}
| Add __dictionary__ to amorphicStatic's definition | Add __dictionary__ to amorphicStatic's definition
| TypeScript | mit | selsamman/amorphic,hackerrdave/amorphic,selsamman/amorphic,hackerrdave/amorphic,selsamman/amorphic,hackerrdave/amorphic,hackerrdave/amorphic,selsamman/amorphic | ---
+++
@@ -17,7 +17,8 @@
static end (persistorTransaction?, logger?) : any {};
static commit (options?) : any {};
static createTransientObject(callback : any) : any {};
- static __transient__ : any
+ static __transient__ : any;
+ static __dictionary__: any;
}
export function Remoteable<BC extends Constructable<{}>>(Base: BC) { |
8f54f5ec16948dbc1e176a6217b50504889e1593 | src/reducers/audioSettings.ts | src/reducers/audioSettings.ts | import { ChangeVolume, ToggleAudioEnabled } from '../actions/audio';
import { AudioSettings } from '../types';
import { CHANGE_VOLUME, TOGGLE_AUDIO_ENABLED } from '../constants';
const initial: AudioSettings = {
enabled: true,
volume: 0.1
};
type AudioAction = ChangeVolume | ToggleAudioEnabled;
export default (state = initial, action: AudioAction): AudioSettings => {
switch (action.type) {
case CHANGE_VOLUME:
return {
...state,
volume: action.value
};
case TOGGLE_AUDIO_ENABLED:
return {
...state,
enabled: state.enabled
};
default:
return state;
}
};
| import { ChangeVolume, ToggleAudioEnabled } from '../actions/audio';
import { AudioSettings } from '../types';
import { CHANGE_VOLUME, TOGGLE_AUDIO_ENABLED } from '../constants';
const initial: AudioSettings = {
enabled: true,
volume: 0.1
};
type AudioAction = ChangeVolume | ToggleAudioEnabled;
export default (state = initial, action: AudioAction): AudioSettings => {
switch (action.type) {
case CHANGE_VOLUME:
return {
...state,
volume: action.value
};
case TOGGLE_AUDIO_ENABLED:
return {
...state,
enabled: !state.enabled
};
default:
return state;
}
};
| Fix bug causing audio to not toggle. | Fix bug causing audio to not toggle.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -19,7 +19,7 @@
case TOGGLE_AUDIO_ENABLED:
return {
...state,
- enabled: state.enabled
+ enabled: !state.enabled
};
default:
return state; |
cf2de4bb4b800ef707c7e0f4c47317fc53a7eea4 | packages/services/src/settings/index.ts | packages/services/src/settings/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
export
namespace Settings {
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
ISettingRegistry, URLExt
} from '@jupyterlab/coreutils';
import {
JSONObject
} from '@phosphor/coreutils';
import {
ServerConnection
} from '..';
/**
* The url for the lab settings service.
*/
const SERVICE_SETTINGS_URL = 'labsettings';
/**
* The static namespace for `SettingService`.
*/
export
namespace SettingService {
/**
* Fetch a plugin's settings.
*
* @param id - The plugin's ID.
*
* @returns A promise that resolves with the plugin settings.
*/
export
function fetch(id: string): Promise<ISettingRegistry.IPlugin> {
const request = { method: 'GET', url: Private.url(id) };
const { serverSettings } = Private;
const promise = ServerConnection.makeRequest(request, serverSettings);
return promise.then(response => {
const { status } = response.xhr;
if (status < 200 || status >= 400) {
throw ServerConnection.makeError(response);
}
return response.data;
});
}
/**
* Save a plugin's settings.
*
* @param id - The plugin's ID.
*
* @param user - The plugin's user setting values.
*
* @returns A promise that resolves when saving is complete.
*/
export
function save(id: string, user: JSONObject): Promise<void> {
const request = { data: user, method: 'PATCH', url: Private.url(id) };
const { serverSettings } = Private;
const promise = ServerConnection.makeRequest(request, serverSettings);
return promise.then(response => {
const { status } = response.xhr;
if (status < 200 || status >= 400) {
throw ServerConnection.makeError(response);
}
return void 0;
});
}
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* The API connection settings.
*/
export
const serverSettings = ServerConnection.makeSettings();
/**
* Get the url for a plugin's settings.
*/
export
function url(id: string): string {
return URLExt.join(serverSettings.baseUrl, SERVICE_SETTINGS_URL, id);
}
}
| Create `SettingService` with `fetch` and `save` methods. | Create `SettingService` with `fetch` and `save` methods.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -1,8 +1,97 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
+import {
+ ISettingRegistry, URLExt
+} from '@jupyterlab/coreutils';
+import {
+ JSONObject
+} from '@phosphor/coreutils';
+
+import {
+ ServerConnection
+} from '..';
+
+
+/**
+ * The url for the lab settings service.
+ */
+const SERVICE_SETTINGS_URL = 'labsettings';
+
+
+/**
+ * The static namespace for `SettingService`.
+ */
export
-namespace Settings {
+namespace SettingService {
+ /**
+ * Fetch a plugin's settings.
+ *
+ * @param id - The plugin's ID.
+ *
+ * @returns A promise that resolves with the plugin settings.
+ */
+ export
+ function fetch(id: string): Promise<ISettingRegistry.IPlugin> {
+ const request = { method: 'GET', url: Private.url(id) };
+ const { serverSettings } = Private;
+ const promise = ServerConnection.makeRequest(request, serverSettings);
+ return promise.then(response => {
+ const { status } = response.xhr;
+
+ if (status < 200 || status >= 400) {
+ throw ServerConnection.makeError(response);
+ }
+
+ return response.data;
+ });
+ }
+
+ /**
+ * Save a plugin's settings.
+ *
+ * @param id - The plugin's ID.
+ *
+ * @param user - The plugin's user setting values.
+ *
+ * @returns A promise that resolves when saving is complete.
+ */
+ export
+ function save(id: string, user: JSONObject): Promise<void> {
+ const request = { data: user, method: 'PATCH', url: Private.url(id) };
+ const { serverSettings } = Private;
+ const promise = ServerConnection.makeRequest(request, serverSettings);
+
+ return promise.then(response => {
+ const { status } = response.xhr;
+
+ if (status < 200 || status >= 400) {
+ throw ServerConnection.makeError(response);
+ }
+
+ return void 0;
+ });
+ }
}
+
+
+/**
+ * A namespace for private data.
+ */
+namespace Private {
+ /**
+ * The API connection settings.
+ */
+ export
+ const serverSettings = ServerConnection.makeSettings();
+
+ /**
+ * Get the url for a plugin's settings.
+ */
+ export
+ function url(id: string): string {
+ return URLExt.join(serverSettings.baseUrl, SERVICE_SETTINGS_URL, id);
+ }
+} |
025bbf37c6c2ebf1539e828ccf241ea746a7bf5a | app/src/main-process/menu/menu-ids.ts | app/src/main-process/menu/menu-ids.ts | export type MenuIDs =
'rename-branch' |
'delete-branch' |
'check-for-updates' |
'checking-for-updates' |
'downloading-update' |
'quit-and-install-update' |
'preferences' |
'update-branch' |
'merge-branch' |
'view-repository-on-github' |
'compare-branch' |
'open-in-shell' | export type MenuIDs =
'rename-branch' |
'delete-branch' |
'check-for-updates' |
'checking-for-updates' |
'downloading-update' |
'quit-and-install-update' |
'preferences' |
'update-branch' |
'merge-branch' |
'view-repository-on-github' |
'compare-branch' |
'open-in-shell'
| Add new line to end of file | Add new line to end of file
| TypeScript | mit | shiftkey/desktop,say25/desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,j-f1/forked-desktop,hjobrien/desktop,gengjiawen/desktop,shiftkey/desktop,hjobrien/desktop,shiftkey/desktop,desktop/desktop,gengjiawen/desktop,gengjiawen/desktop,desktop/desktop,BugTesterTest/desktops,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,j-f1/forked-desktop,hjobrien/desktop,BugTesterTest/desktops,BugTesterTest/desktops,artivilla/desktop,artivilla/desktop,gengjiawen/desktop,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,say25/desktop | |
47d9cc85bd2176782fa7b450cb5cf03d645d9c31 | src/services/db-connection.service.ts | src/services/db-connection.service.ts | import PouchDB from 'pouchdb';
import { Injectable } from "@angular/core";
// Manages to connection to local and remote databases,
// creates per-user databases if needed.
@Injectable()
export class DbConnectionService {
public pagesDb: PouchDB.Database<{}>;
public eventsDb: PouchDB.Database<{}>;
public onLogin(username: string) {
this.pagesDb = this.setupLocalAndRemoteDb(username, "pages");
this.eventsDb = this.setupLocalAndRemoteDb(username, "events");
}
public onLogout() {
// TODO: Is this enough? What if someone already subscribed for some events from
// existing databases.
this.pagesDb = null;
this.eventsDb = null;
}
private setupLocalAndRemoteDb(username: string, dbName: string) : PouchDB.Database<{}> {
// TODO: remove slice hack when we switch to proper usernames
const localDbName = `${username.slice(0, 5)}_${dbName}`;
let db = new PouchDB(localDbName);
// TODO: provide proper credentials
const removeDbName = `https://aeremin:[email protected]/${localDbName}`;
let replicationOptions = {
live: true,
retry: true,
continuous: true,
};
db.sync(removeDbName, replicationOptions);
return db;
}
} | import PouchDB from 'pouchdb';
import { Injectable } from "@angular/core";
// Manages to connection to local and remote databases,
// creates per-user databases if needed.
@Injectable()
export class DbConnectionService {
public pagesDb: PouchDB.Database<{}>;
public eventsDb: PouchDB.Database<{}>;
public onLogin(username: string) {
this.pagesDb = this.setupLocalAndRemoteDb(username, "pages-dev");
this.eventsDb = this.setupLocalAndRemoteDb(username, "events-dev");
}
public onLogout() {
// TODO: Is this enough? What if someone already subscribed for some events from
// existing databases.
this.pagesDb = null;
this.eventsDb = null;
}
private setupLocalAndRemoteDb(username: string, dbName: string) : PouchDB.Database<{}> {
// TODO: remove slice hack when we switch to proper usernames
const localDbName = `${username.slice(0, 5)}_${dbName}`;
let db = new PouchDB(localDbName);
// TODO: provide proper credentials
const removeDbName = `http://dev.alice.digital:5984/${dbName}`;
let replicationOptions = {
live: true,
retry: true,
continuous: true,
};
db.sync(removeDbName, replicationOptions);
return db;
}
} | Use our own CouchDB server instead of Cloudant | Use our own CouchDB server instead of Cloudant
| TypeScript | apache-2.0 | sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile | ---
+++
@@ -10,8 +10,8 @@
public eventsDb: PouchDB.Database<{}>;
public onLogin(username: string) {
- this.pagesDb = this.setupLocalAndRemoteDb(username, "pages");
- this.eventsDb = this.setupLocalAndRemoteDb(username, "events");
+ this.pagesDb = this.setupLocalAndRemoteDb(username, "pages-dev");
+ this.eventsDb = this.setupLocalAndRemoteDb(username, "events-dev");
}
public onLogout() {
@@ -27,7 +27,7 @@
let db = new PouchDB(localDbName);
// TODO: provide proper credentials
- const removeDbName = `https://aeremin:[email protected]/${localDbName}`;
+ const removeDbName = `http://dev.alice.digital:5984/${dbName}`;
let replicationOptions = {
live: true,
retry: true, |
c93770a6c1779af44b9786688b88688836b4f941 | packages/mobile/src/index.ts | packages/mobile/src/index.ts | try {
// tslint:disable-next-line
const modules = require('.').default;
modules.triggerOnAppCreate();
} catch (e) {
if (typeof ErrorUtils !== 'undefined') {
(ErrorUtils as any).reportFatalError(e);
} else {
console.error(e);
}
}
| try {
// tslint:disable-next-line
const modules = require('./modules').default;
modules.triggerOnAppCreate();
} catch (e) {
if (typeof ErrorUtils !== 'undefined') {
(ErrorUtils as any).reportFatalError(e);
} else {
console.error(e);
}
}
| Fix wrong path to modules for mobile | Fix wrong path to modules for mobile
| TypeScript | mit | sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit | ---
+++
@@ -1,6 +1,6 @@
try {
// tslint:disable-next-line
- const modules = require('.').default;
+ const modules = require('./modules').default;
modules.triggerOnAppCreate();
} catch (e) {
if (typeof ErrorUtils !== 'undefined') { |
00b19d9516cf49549601234c959c2846bc1aec65 | apps/angular-thirty-seconds/src/app/angular-thirty-seconds/angular-thirty-seconds-routing.module.ts | apps/angular-thirty-seconds/src/app/angular-thirty-seconds/angular-thirty-seconds-routing.module.ts | import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateSnippetComponent } from './create-snippet/create-snippet.component';
import { AngularThirtySecondsComponent } from './angular-thirty-seconds.component';
const routes: Routes = [
{path: '', component: AngularThirtySecondsComponent},
{path: 'new', component: CreateSnippetComponent}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AngularThirtySecondsRoutingModule {
}
| import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CreateSnippetComponent } from './create-snippet/create-snippet.component';
import { AngularThirtySecondsComponent } from './angular-thirty-seconds.component';
import { SlidesRoutes } from '@codelab/slides/src/lib/routing/slide-routes';
const routes = RouterModule.forChild(
[
{path: 'new', component: CreateSnippetComponent},
...SlidesRoutes.get(AngularThirtySecondsComponent)
]
);
@NgModule({
imports: [routes],
exports: [RouterModule]
})
export class AngularThirtySecondsRoutingModule {
}
| Fix - returned routing to snippet component | Fix - returned routing to snippet component
| TypeScript | apache-2.0 | nycJSorg/angular-presentation,nycJSorg/angular-presentation,nycJSorg/angular-presentation | ---
+++
@@ -1,15 +1,18 @@
import { NgModule } from '@angular/core';
-import { Routes, RouterModule } from '@angular/router';
+import { RouterModule } from '@angular/router';
import { CreateSnippetComponent } from './create-snippet/create-snippet.component';
import { AngularThirtySecondsComponent } from './angular-thirty-seconds.component';
+import { SlidesRoutes } from '@codelab/slides/src/lib/routing/slide-routes';
-const routes: Routes = [
- {path: '', component: AngularThirtySecondsComponent},
- {path: 'new', component: CreateSnippetComponent}
-];
+const routes = RouterModule.forChild(
+ [
+ {path: 'new', component: CreateSnippetComponent},
+ ...SlidesRoutes.get(AngularThirtySecondsComponent)
+ ]
+);
@NgModule({
- imports: [RouterModule.forChild(routes)],
+ imports: [routes],
exports: [RouterModule]
})
|
639af73bb73b12c7c52b99b0c5b5666b09fbc1ee | src/generic_ui/polymer/roster.ts | src/generic_ui/polymer/roster.ts | /// <reference path='../../interfaces/ui-polymer.d.ts' />
Polymer({
model: model,
onlineTrustedUproxyContacts: model.contacts.onlineTrustedUproxy,
offlineTrustedUproxyContacts: model.contacts.offlineTrustedUproxy,
onlineUntrustedUproxyContacts: model.contacts.onlineUntrustedUproxy,
offlineUntrustedUproxyContacts: model.contacts.offlineUntrustedUproxy,
onlineNonUproxyContacts: model.contacts.onlineNonUproxy,
offlineNonUproxyContacts: model.contacts.offlineNonUproxy,
toggleSharing: function() {
model.globalSettings.sharing = !this.model.globalSettings.sharing;
core.updateGlobalSettings({newSettings:model.globalSettings,
path:this.path});
},
ready: function() {
this.path = <InstancePath>{
network : {
name: this.network.name,
userId: this.network.userId
},
userId: this.userId,
instanceId: this.instance.instanceId
};
console.log('initializing roster');
// this.contacts.push({
// name: 'alice',
// description: 'just some laptop'
// });
// this.contacts.push({ name: 'bob' });
// this.contacts.push({ name: 'charlie' });
// this.contacts.push({ name: 'dave' });
// this.contacts.push({ name: 'eve' });
},
searchQuery: ''
});
| /// <reference path='../../interfaces/ui-polymer.d.ts' />
Polymer({
model: model,
onlineTrustedUproxyContacts: model.contacts.onlineTrustedUproxy,
offlineTrustedUproxyContacts: model.contacts.offlineTrustedUproxy,
onlineUntrustedUproxyContacts: model.contacts.onlineUntrustedUproxy,
offlineUntrustedUproxyContacts: model.contacts.offlineUntrustedUproxy,
onlineNonUproxyContacts: model.contacts.onlineNonUproxy,
offlineNonUproxyContacts: model.contacts.offlineNonUproxy,
toggleSharing: function() {
core.updateGlobalSettings({newSettings:model.globalSettings,
path:this.path});
},
ready: function() {
this.path = <InstancePath>{
network : {
name: this.network.name,
userId: this.network.userId
},
userId: this.userId,
instanceId: this.instance.instanceId
};
console.log('initializing roster');
// this.contacts.push({
// name: 'alice',
// description: 'just some laptop'
// });
// this.contacts.push({ name: 'bob' });
// this.contacts.push({ name: 'charlie' });
// this.contacts.push({ name: 'dave' });
// this.contacts.push({ name: 'eve' });
},
searchQuery: ''
});
| Remove reference to sharing status. | Remove reference to sharing status.
| TypeScript | apache-2.0 | roceys/uproxy,jpevarnek/uproxy,jpevarnek/uproxy,roceys/uproxy,chinarustin/uproxy,MinFu/uproxy,jpevarnek/uproxy,dhkong88/uproxy,dhkong88/uproxy,itplanes/uproxy,qida/uproxy,uProxy/uproxy,roceys/uproxy,IveWong/uproxy,IveWong/uproxy,uProxy/uproxy,dhkong88/uproxy,chinarustin/uproxy,qida/uproxy,MinFu/uproxy,MinFu/uproxy,itplanes/uproxy,roceys/uproxy,itplanes/uproxy,chinarustin/uproxy,uProxy/uproxy,dhkong88/uproxy,uProxy/uproxy,chinarustin/uproxy,qida/uproxy,qida/uproxy,itplanes/uproxy,IveWong/uproxy,qida/uproxy,dhkong88/uproxy,jpevarnek/uproxy,itplanes/uproxy,MinFu/uproxy,uProxy/uproxy,chinarustin/uproxy,roceys/uproxy,MinFu/uproxy,IveWong/uproxy,jpevarnek/uproxy | ---
+++
@@ -9,7 +9,6 @@
onlineNonUproxyContacts: model.contacts.onlineNonUproxy,
offlineNonUproxyContacts: model.contacts.offlineNonUproxy,
toggleSharing: function() {
- model.globalSettings.sharing = !this.model.globalSettings.sharing;
core.updateGlobalSettings({newSettings:model.globalSettings,
path:this.path});
}, |
9c38e9c0c66fe371fcabe419569f0d23511793cb | src/components/sources/sourceManager.ts | src/components/sources/sourceManager.ts | import { ENABLE_DEBUG_MODE } from '../../config/config'
import { log } from '../../lib/logger'
/**
* Create an array of all sources in the room and update job entries where
* available. This should ensure that each room has 1 harvester per source.
*
* @export
* @param {Room} room The current room.
*/
export function refreshAvailableSources(room: Room): void {
const sources: Source[] = room.find<Source>(FIND_SOURCES)
if (room.memory.sources.length === 0) {
sources.forEach((source: Source) => {
// Create an array of all source IDs in the room
room.memory.sources.push(source.id)
})
}
if (ENABLE_DEBUG_MODE) {
log.info(`${room.name}: ${_.size(sources)} source(s) in room.`)
}
// Update job assignments.
room.memory.jobs.harvester = sources.length
}
| import { ENABLE_DEBUG_MODE } from '../../config/config'
import { blacklistedSources } from '../../config/jobs'
import { log } from '../../lib/logger'
/**
* Create an array of all sources in the room and update job entries where
* available. This should ensure that each room has 1 harvester per source.
*
* @export
* @param {Room} room The current room.
*/
export function refreshAvailableSources(room: Room): void {
const sources: Source[] = room.find<Source>(FIND_SOURCES)
if (room.memory.sources.length === 0) {
sources.forEach((source: Source) => {
// We only push sources that aren't blacklisted.
if (_.includes(blacklistedSources, source.id) === false) {
room.memory.sources.push(source.id)
}
})
room.memory.jobs.harvester = sources.length
} else {
// If sources array exists in memory, filter out blacklisted sources.
room.memory.sources = _.filter((room.memory.sources as string[]), (id: string) => {
return _.includes(blacklistedSources, id) === false
})
}
if (ENABLE_DEBUG_MODE) {
log.info(`${room.name}: ${_.size(sources)} source(s) in room.`)
}
}
| Add option to filter out blacklisted sources | [SourceManager] Add option to filter out blacklisted sources
| TypeScript | mit | resir014/screeps,resir014/screeps | ---
+++
@@ -1,4 +1,5 @@
import { ENABLE_DEBUG_MODE } from '../../config/config'
+import { blacklistedSources } from '../../config/jobs'
import { log } from '../../lib/logger'
/**
@@ -13,15 +14,21 @@
if (room.memory.sources.length === 0) {
sources.forEach((source: Source) => {
- // Create an array of all source IDs in the room
- room.memory.sources.push(source.id)
+ // We only push sources that aren't blacklisted.
+ if (_.includes(blacklistedSources, source.id) === false) {
+ room.memory.sources.push(source.id)
+ }
+ })
+
+ room.memory.jobs.harvester = sources.length
+ } else {
+ // If sources array exists in memory, filter out blacklisted sources.
+ room.memory.sources = _.filter((room.memory.sources as string[]), (id: string) => {
+ return _.includes(blacklistedSources, id) === false
})
}
if (ENABLE_DEBUG_MODE) {
log.info(`${room.name}: ${_.size(sources)} source(s) in room.`)
}
-
- // Update job assignments.
- room.memory.jobs.harvester = sources.length
} |
75566f709d6c6b7ba9a2098fe36a8ef90d5a9bc1 | components/backdrop/backdrop.service.ts | components/backdrop/backdrop.service.ts | import { AppBackdrop } from './backdrop';
export class Backdrop
{
private static backdrops: AppBackdrop[] = [];
static push()
{
const el = document.createElement( 'div' );
document.body.appendChild( el );
const backdrop = new AppBackdrop();
backdrop.$mount( el );
this.backdrops.push( backdrop );
return backdrop;
}
static remove( backdrop: AppBackdrop )
{
backdrop.$destroy();
backdrop.$el.parentNode!.removeChild( backdrop.$el );
const index = this.backdrops.indexOf( backdrop );
if ( index !== -1 ) {
this.backdrops.splice( index, 1 );
}
}
}
| import { AppBackdrop } from './backdrop';
export class Backdrop
{
private static backdrops: AppBackdrop[] = [];
static push( context?: HTMLElement )
{
const el = document.createElement( 'div' );
if ( !context ) {
document.body.appendChild( el );
}
else {
context.appendChild( el );
}
const backdrop = new AppBackdrop();
backdrop.$mount( el );
this.backdrops.push( backdrop );
return backdrop;
}
static remove( backdrop: AppBackdrop )
{
backdrop.$destroy();
backdrop.$el.parentNode!.removeChild( backdrop.$el );
const index = this.backdrops.indexOf( backdrop );
if ( index !== -1 ) {
this.backdrops.splice( index, 1 );
}
}
}
| Allow to attach backdrops to elements other than window. | Allow to attach backdrops to elements other than window.
| TypeScript | mit | gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib | ---
+++
@@ -4,10 +4,16 @@
{
private static backdrops: AppBackdrop[] = [];
- static push()
+ static push( context?: HTMLElement )
{
const el = document.createElement( 'div' );
- document.body.appendChild( el );
+
+ if ( !context ) {
+ document.body.appendChild( el );
+ }
+ else {
+ context.appendChild( el );
+ }
const backdrop = new AppBackdrop();
backdrop.$mount( el ); |
d4c16858ce0ef2c22f084eecd2f142d9864ac8dd | lib/util/request.ts | lib/util/request.ts | import * as requestPromise from 'request-promise-native';
import { Config, Request, TaxjarError } from '../util/types';
const proxyError = (result): never => {
throw new TaxjarError(
result.error.error,
result.error.detail,
result.statusCode,
);
};
export default (config: Config): Request => {
const request = requestPromise.defaults({
headers: Object.assign({}, config.headers || {}, {
Authorization: `Bearer ${config.apiKey}`,
'Content-Type': 'application/json'
}),
baseUrl: config.apiUrl,
json: true
});
return {
get: options => request.get(options.url, {qs: options.params}).catch(proxyError),
post: options => request.post(options.url, {body: options.params}).catch(proxyError),
put: options => request.put(options.url, {body: options.params}).catch(proxyError),
delete: options => request.delete(options.url, {qs: options.params}).catch(proxyError)
};
};
| import * as requestPromise from 'request-promise-native';
import { Config, Request, TaxjarError } from '../util/types';
const proxyError = (result): never => {
const isTaxjarError = result.statusCode && result.error && result.error.error && result.error.detail;
if (isTaxjarError) {
throw new TaxjarError(
result.error.error,
result.error.detail,
result.statusCode
);
}
throw result;
};
export default (config: Config): Request => {
const request = requestPromise.defaults({
headers: Object.assign({}, config.headers || {}, {
Authorization: `Bearer ${config.apiKey}`,
'Content-Type': 'application/json'
}),
baseUrl: config.apiUrl,
json: true
});
return {
get: options => request.get(options.url, {qs: options.params}).catch(proxyError),
post: options => request.post(options.url, {body: options.params}).catch(proxyError),
put: options => request.put(options.url, {body: options.params}).catch(proxyError),
delete: options => request.delete(options.url, {qs: options.params}).catch(proxyError)
};
};
| Check if an error is from the API before converting to a TaxjarError | Check if an error is from the API before converting to a TaxjarError
| TypeScript | mit | taxjar/taxjar-node,taxjar/taxjar-node | ---
+++
@@ -2,11 +2,15 @@
import { Config, Request, TaxjarError } from '../util/types';
const proxyError = (result): never => {
- throw new TaxjarError(
- result.error.error,
- result.error.detail,
- result.statusCode,
- );
+ const isTaxjarError = result.statusCode && result.error && result.error.error && result.error.detail;
+ if (isTaxjarError) {
+ throw new TaxjarError(
+ result.error.error,
+ result.error.detail,
+ result.statusCode
+ );
+ }
+ throw result;
};
export default (config: Config): Request => { |
56e5c10c538645b6d03d2e002de25d93cba3dbc1 | Web/typescript/dropdown.component.ts | Web/typescript/dropdown.component.ts | import {Component, EventEmitter, Input, Output} from 'angular2/core';
import {SelectableOption} from './soapy.interfaces';
import * as util from './soapy.utils';
@Component({
selector: 'soapy-dropdown',
templateUrl: '/app/dropdown.component.html',
})
export class DropdownComponent {
@Input() items: SelectableOption[];
@Input() selectedItem: SelectableOption;
@Output() selectedItemChange = new EventEmitter();
get selectedItemId(): String {
if (this.selectedItem == null) {
return null;
}
return this.selectedItem.id;
}
set selectedItemId(id: String) {
this.selectedItem = util.findByProperty(this.items, 'id', id);
this.selectedItemChange.next(this.selectedItem);
}
}
| import {Component, EventEmitter, Input, Output} from 'angular2/core';
import {SelectableOption} from './soapy.interfaces';
import * as util from './soapy.utils';
@Component({
selector: 'soapy-dropdown',
templateUrl: '/app/dropdown.component.html',
})
export class DropdownComponent {
@Input() items: SelectableOption[];
@Input() selectedItem: SelectableOption;
@Output() selectedItemChange = new EventEmitter();
get selectedItemId(): string {
if (this.selectedItem == null) {
return null;
}
return this.selectedItem.id;
}
set selectedItemId(id: string) {
this.selectedItem = util.findByProperty(this.items, 'id', id);
this.selectedItemChange.next(this.selectedItem);
}
}
| Use correct typescript 'string' type (not 'String'). | Web: Use correct typescript 'string' type (not 'String').
| TypeScript | mit | dag10/Soapy,dag10/Soapy,dag10/Soapy,dag10/Soapy,dag10/Soapy | ---
+++
@@ -13,7 +13,7 @@
@Input() selectedItem: SelectableOption;
@Output() selectedItemChange = new EventEmitter();
- get selectedItemId(): String {
+ get selectedItemId(): string {
if (this.selectedItem == null) {
return null;
}
@@ -21,7 +21,7 @@
return this.selectedItem.id;
}
- set selectedItemId(id: String) {
+ set selectedItemId(id: string) {
this.selectedItem = util.findByProperty(this.items, 'id', id);
this.selectedItemChange.next(this.selectedItem);
} |
4cb96edfec89f243aea063bb09ebdfb8b173fc3c | src/app/core/errorhandler/error-handler.service.ts | src/app/core/errorhandler/error-handler.service.ts | import {Injectable, ErrorHandler} from '@angular/core';
import {Response} from "@angular/http";
import {Observable} from "rxjs";
@Injectable()
export class ErrorHandlerService implements ErrorHandler {
constructor() { }
/*
* @description: handler for http-request catch-clauses
*/
handleError(error: Response | any) {
let errorMessage: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errorMessage = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errorMessage = error.message ? error.message : error.toString();
}
return Observable.throw(errorMessage);
}
}
| import {Injectable, ErrorHandler} from '@angular/core';
import {Response} from "@angular/http";
import {Observable} from "rxjs";
@Injectable()
export class ErrorHandlerService implements ErrorHandler {
constructor() { }
/*
* @description: handler for http-request catch-clauses
*/
handleError(error: Response | any) {
let errorMessage: string;
if (error instanceof Response) {
//const body = error.json() || '';
//const err = body.error || JSON.stringify(body);
const err = error.text() || '';
errorMessage = `${error.status} - ${error.statusText || ''} (${err})`;
} else {
errorMessage = error.message ? error.message : error.toString();
}
return Observable.throw(errorMessage);
}
}
| Handle errors as plain text | Handle errors as plain text
| TypeScript | mit | chipster/chipster-web,chipster/chipster-web,chipster/chipster-web | ---
+++
@@ -14,9 +14,10 @@
let errorMessage: string;
if (error instanceof Response) {
- const body = error.json() || '';
- const err = body.error || JSON.stringify(body);
- errorMessage = `${error.status} - ${error.statusText || ''} ${err}`;
+ //const body = error.json() || '';
+ //const err = body.error || JSON.stringify(body);
+ const err = error.text() || '';
+ errorMessage = `${error.status} - ${error.statusText || ''} (${err})`;
} else {
errorMessage = error.message ? error.message : error.toString();
} |
b6b463f7043dac15a427952be76c2890cb5b844c | src/app/app.routing.ts | src/app/app.routing.ts | import { Routes, RouterModule } from '@angular/router';
import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './profile/login/login.component';
import { SignUpComponent } from './profile/sign-up/sign-up.component';
import { UserProfileComponent } from './profile/user-profile/user-profile.component';
import { SnippetEditorComponent } from './snippets/snippet-editor/snippet-editor.component';
import { SnippetViewerComponent } from './snippets/snippet-viewer/snippet-viewer.component';
const APP_ROUTES: Routes = [
{ path: '', component: HomepageComponent },
{ path: 'login', component: LoginComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'profile', component: UserProfileComponent },
{ path: 'snippet/editor', component: SnippetEditorComponent },
{ path: 'snippet/view', component: SnippetViewerComponent }
];
export const ROUTING = RouterModule.forRoot(APP_ROUTES);
| import { Routes, RouterModule } from '@angular/router';
import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './profile/login/login.component';
import { SignUpComponent } from './profile/sign-up/sign-up.component';
import { UserProfileComponent } from './profile/user-profile/user-profile.component';
import { SnippetEditorComponent } from './snippets/snippet-editor/snippet-editor.component';
import { SnippetViewerComponent } from './snippets/snippet-viewer/snippet-viewer.component';
import { PublicSnippetsComponent } from './snippets/public-snippets/public-snippets.component';
const APP_ROUTES: Routes = [
{ path: '', component: HomepageComponent },
{ path: 'login', component: LoginComponent },
{ path: 'sign-up', component: SignUpComponent },
{ path: 'profile', component: UserProfileComponent },
{ path: 'snippet/editor', component: SnippetEditorComponent },
{ path: 'snippets', component: PublicSnippetsComponent },
{ path: 'snippet/:id', component: SnippetViewerComponent }
];
export const ROUTING = RouterModule.forRoot(APP_ROUTES);
| Add public snippets route. Add snippet by id route | Add public snippets route. Add snippet by id route
| TypeScript | apache-2.0 | SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend,SamuelM333/snippet-sniper-frontend | ---
+++
@@ -6,6 +6,7 @@
import { UserProfileComponent } from './profile/user-profile/user-profile.component';
import { SnippetEditorComponent } from './snippets/snippet-editor/snippet-editor.component';
import { SnippetViewerComponent } from './snippets/snippet-viewer/snippet-viewer.component';
+import { PublicSnippetsComponent } from './snippets/public-snippets/public-snippets.component';
const APP_ROUTES: Routes = [
{ path: '', component: HomepageComponent },
@@ -13,7 +14,8 @@
{ path: 'sign-up', component: SignUpComponent },
{ path: 'profile', component: UserProfileComponent },
{ path: 'snippet/editor', component: SnippetEditorComponent },
- { path: 'snippet/view', component: SnippetViewerComponent }
+ { path: 'snippets', component: PublicSnippetsComponent },
+ { path: 'snippet/:id', component: SnippetViewerComponent }
];
export const ROUTING = RouterModule.forRoot(APP_ROUTES); |
aca3de76affa8babd77f81a1f4858b8181a2f87f | src/components/HistorySideBar.tsx | src/components/HistorySideBar.tsx | import { PastCommitNode } from "./PastCommitNode";
import { SingleCommitInfo, GitBranchResult } from "../git";
import {
historySideBarStyle,
} from "../componentsStyle/HistorySideBarStyle";
import * as React from "react";
/** Interface for PastCommits component props */
export interface IHistorySideBarProps {
pastCommits: SingleCommitInfo[];
data: GitBranchResult["branches"];
isExpanded: boolean;
topRepoPath: string;
currentTheme: string;
app: any;
refresh: any;
diff: any;
}
/** Interface for PastCommits component state */
export interface IHistorySideBarState {
activeNode: number;
}
export class HistorySideBar extends React.Component<
IHistorySideBarProps,
IHistorySideBarState
> {
constructor(props: IHistorySideBarProps) {
super(props);
this.state = {
activeNode: -1
};
}
updateActiveNode = (index: number): void => {
this.setState({ activeNode: index });
};
render() {
if (!this.props.isExpanded) {
return null;
}
return (
<div className={historySideBarStyle}>
{this.props.pastCommits.map(
(pastCommit: SingleCommitInfo, pastCommitIndex: number) => (
<PastCommitNode
key={pastCommitIndex}
pastCommit={pastCommit}
data={this.props.data}
topRepoPath={this.props.topRepoPath}
currentTheme={this.props.currentTheme}
app={this.props.app}
refresh={this.props.refresh}
diff={this.props.diff}
/>
)
)}
</div>
);
}
}
| import { PastCommitNode } from "./PastCommitNode";
import { SingleCommitInfo, GitBranchResult } from "../git";
import {
historySideBarStyle,
} from "../componentsStyle/HistorySideBarStyle";
import * as React from "react";
/** Interface for PastCommits component props */
export interface IHistorySideBarProps {
pastCommits: SingleCommitInfo[];
data: GitBranchResult["branches"];
isExpanded: boolean;
topRepoPath: string;
currentTheme: string;
app: any;
refresh: any;
diff: any;
}
export class HistorySideBar extends React.Component<
IHistorySideBarProps,
{}
> {
render() {
if (!this.props.isExpanded) {
return null;
}
return (
<div className={historySideBarStyle}>
{this.props.pastCommits.map(
(pastCommit: SingleCommitInfo, pastCommitIndex: number) => (
<PastCommitNode
key={pastCommitIndex}
pastCommit={pastCommit}
data={this.props.data}
topRepoPath={this.props.topRepoPath}
currentTheme={this.props.currentTheme}
app={this.props.app}
refresh={this.props.refresh}
diff={this.props.diff}
/>
)
)}
</div>
);
}
}
| Remove unused state in history side bar | Remove unused state in history side bar
| TypeScript | bsd-3-clause | jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git,jupyterlab/jupyterlab-git | ---
+++
@@ -21,28 +21,12 @@
diff: any;
}
-/** Interface for PastCommits component state */
-export interface IHistorySideBarState {
- activeNode: number;
-}
+
export class HistorySideBar extends React.Component<
IHistorySideBarProps,
- IHistorySideBarState
+ {}
> {
- constructor(props: IHistorySideBarProps) {
- super(props);
-
- this.state = {
- activeNode: -1
- };
- }
-
-
- updateActiveNode = (index: number): void => {
- this.setState({ activeNode: index });
- };
-
render() {
if (!this.props.isExpanded) {
return null; |
e906151751e424e7727c32b148b03c11ce21760c | src/features/structureProvider.ts | src/features/structureProvider.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { FoldingRangeProvider, TextDocument, FoldingContext, CancellationToken, FoldingRange, FoldingRangeKind } from "vscode";
import AbstractSupport from './abstractProvider';
import { blockStructure } from "../omnisharp/utils";
import { Request } from "../omnisharp/protocol";
export class StructureProvider extends AbstractSupport implements FoldingRangeProvider {
async provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): Promise<FoldingRange[]> {
let request: Request = {
FileName: document.fileName,
};
try {
let response = await blockStructure(this._server, request, token);
let ranges: FoldingRange[] = [];
for (let member of response.Spans) {
ranges.push(new FoldingRange(member.Range.Start.Line, member.Range.End.Line, this.GetType(member.Kind)));
}
return ranges;
}
catch (error) {
return [];
}
}
GetType(type: string): FoldingRangeKind {
switch (type) {
case "Comment":
return FoldingRangeKind.Comment;
case "Imports":
return FoldingRangeKind.Imports;
case "Region":
return FoldingRangeKind.Region;
default:
return null;
}
}
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { FoldingRangeProvider, TextDocument, FoldingContext, CancellationToken, FoldingRange, FoldingRangeKind } from "vscode";
import AbstractSupport from './abstractProvider';
import { blockStructure } from "../omnisharp/utils";
import { Request } from "../omnisharp/protocol";
export class StructureProvider extends AbstractSupport implements FoldingRangeProvider {
async provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): Promise<FoldingRange[]> {
let request: Request = {
FileName: document.fileName,
};
try {
let response = await blockStructure(this._server, request, token);
let ranges: FoldingRange[] = [];
for (let member of response.Spans) {
ranges.push(new FoldingRange(member.Range.Start.Line, member.Range.End.Line, this.GetType(member.Kind)));
}
return ranges;
}
catch (error) {
return [];
}
}
GetType(type: string): FoldingRangeKind | undefined {
switch (type) {
case "Comment":
return FoldingRangeKind.Comment;
case "Imports":
return FoldingRangeKind.Imports;
case "Region":
return FoldingRangeKind.Region;
default:
return undefined;
}
}
}
| Allow GetType to return undefined | Allow GetType to return undefined
| TypeScript | mit | OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode,OmniSharp/omnisharp-vscode | ---
+++
@@ -28,7 +28,7 @@
}
}
- GetType(type: string): FoldingRangeKind {
+ GetType(type: string): FoldingRangeKind | undefined {
switch (type) {
case "Comment":
return FoldingRangeKind.Comment;
@@ -37,7 +37,7 @@
case "Region":
return FoldingRangeKind.Region;
default:
- return null;
+ return undefined;
}
}
|
5f95bbc927f1161dfef3481ead5f6098fe60f0f7 | src/app/services/form.service.ts | src/app/services/form.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class FormService {
private phenotypesUrl = 'http://private-de10f-seqpipe.apiary-mock.com/phenotypes';
constructor (private http: Http) {}
getPhenotypes(){
return this.http.get(this.phenotypesUrl).map(response => response.json());
}
getPresentInChild(){
return this.http.get('http://localhost:4400/app/services/present-in-child.json').map(response => response.json());
}
getPresentInParent(){
return this.http.get('http://localhost:4400/app/services/present-in-parent.json').map(response => response.json());
}
getEffectTypes(){
return this.http.get('http://localhost:4400/app/services/effect-types.json').map(response => response.json());
}
} | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class FormService {
private phenotypesUrl = 'http://private-de10f-seqpipe.apiary-mock.com/phenotypes';
constructor (private http: Http) {}
getPhenotypes(){
return this.http.get(this.phenotypesUrl).map(response => response.json());
}
getPresentInChild(){
return this.http.get('http://localhost:4200/app/services/present-in-child.json').map(response => response.json());
}
getPresentInParent(){
return this.http.get('http://localhost:4200/app/services/present-in-parent.json').map(response => response.json());
}
getEffectTypes(){
return this.http.get('http://localhost:4200/app/services/effect-types.json').map(response => response.json());
}
} | Fix in the request urls. | Fix in the request urls.
| TypeScript | mit | Ftujio/gen,Ftujio/gen,Ftujio/gen | ---
+++
@@ -14,14 +14,14 @@
}
getPresentInChild(){
- return this.http.get('http://localhost:4400/app/services/present-in-child.json').map(response => response.json());
+ return this.http.get('http://localhost:4200/app/services/present-in-child.json').map(response => response.json());
}
getPresentInParent(){
- return this.http.get('http://localhost:4400/app/services/present-in-parent.json').map(response => response.json());
+ return this.http.get('http://localhost:4200/app/services/present-in-parent.json').map(response => response.json());
}
getEffectTypes(){
- return this.http.get('http://localhost:4400/app/services/effect-types.json').map(response => response.json());
+ return this.http.get('http://localhost:4200/app/services/effect-types.json').map(response => response.json());
}
} |
9f555d1c445f26a43ac69e2b8ac58633b0a22bf7 | src/components/log/index.tsx | src/components/log/index.tsx | import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {connect} from 'react-redux'
import {firebaseConnect} from 'react-redux-firebase'
import {LogEntry} from './log-entry'
import {momentedLogsSelector} from '../../selectors/momented-logs'
import {IMomentLog, IRootState} from '../../types'
const mapStateToProps = (state: IRootState) => ({
logs: momentedLogsSelector(state)
})
interface ILogProps {
logs: IMomentLog[]
}
function LogImpl({logs}: ILogProps) {
return (
<table>
<thead>
<tr>
<th>Time</th>
<th>Message</th>
</tr>
</thead>
<tbody>
{logs.map((log, i) => (
<LogEntry key={i} message={log.message} time={log.time} />
))}
</tbody>
</table>
)
}
export const Log = flowRight(
firebaseConnect([
'/log#limitToFirst=50'
]),
connect(mapStateToProps)
)(LogImpl)
| import * as React from 'react'
import flowRight from 'lodash-es/flowRight'
import {connect} from 'react-redux'
import {firebaseConnect} from 'react-redux-firebase'
import {LogEntry} from './log-entry'
import {momentedLogsSelector} from '../../selectors/momented-logs'
import {IMomentLog, IRootState} from '../../types'
const mapStateToProps = (state: IRootState) => ({
logs: momentedLogsSelector(state)
})
interface ILogProps {
logs: IMomentLog[]
}
function LogImpl({logs}: ILogProps) {
return (
<table>
<thead>
<tr>
<th>Time</th>
<th>Message</th>
</tr>
</thead>
<tbody>
{logs.map((log, i) => (
<LogEntry key={i} message={log.message} time={log.time} />
))}
</tbody>
</table>
)
}
export const Log = flowRight(
firebaseConnect([
'/log#limitToLast=50#orderByChild=time'
]),
connect(mapStateToProps)
)(LogImpl)
| Fix log sort and limit logic | Fix log sort and limit logic
| TypeScript | mit | jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend,jsse-2017-ph23/web-frontend | ---
+++
@@ -34,7 +34,7 @@
export const Log = flowRight(
firebaseConnect([
- '/log#limitToFirst=50'
+ '/log#limitToLast=50#orderByChild=time'
]),
connect(mapStateToProps)
)(LogImpl) |
f2e92d80aca5c3dfa13841cd03390edaeacaef45 | resources/scripts/components/elements/PageContentBlock.tsx | resources/scripts/components/elements/PageContentBlock.tsx | import React, { useEffect } from 'react';
import ContentContainer from '@/components/elements/ContentContainer';
import { CSSTransition } from 'react-transition-group';
import tw from 'twin.macro';
import FlashMessageRender from '@/components/FlashMessageRender';
export interface PageContentBlockProps {
title?: string;
className?: string;
showFlashKey?: string;
}
const PageContentBlock: React.FC<PageContentBlockProps> = ({ title, showFlashKey, className, children }) => {
useEffect(() => {
if (title) {
document.title = title;
}
}, [ title ]);
return (
<CSSTransition timeout={150} classNames={'fade'} appear in>
<>
<ContentContainer css={tw`my-4 sm:my-10`} className={className}>
{showFlashKey &&
<FlashMessageRender byKey={showFlashKey} css={tw`mb-4`}/>
}
{children}
</ContentContainer>
<ContentContainer css={tw`mb-4`}>
<p css={tw`text-center text-neutral-500 text-xs`}>
© 2015 - {(new Date()).getFullYear()}
<a
rel={'noopener nofollow noreferrer'}
href={'https://pterodactyl.io'}
target={'_blank'}
css={tw`no-underline text-neutral-500 hover:text-neutral-300`}
>
Pterodactyl Software
</a>
</p>
</ContentContainer>
</>
</CSSTransition>
);
};
export default PageContentBlock;
| import React, { useEffect } from 'react';
import ContentContainer from '@/components/elements/ContentContainer';
import { CSSTransition } from 'react-transition-group';
import tw from 'twin.macro';
import FlashMessageRender from '@/components/FlashMessageRender';
export interface PageContentBlockProps {
title?: string;
className?: string;
showFlashKey?: string;
}
const PageContentBlock: React.FC<PageContentBlockProps> = ({ title, showFlashKey, className, children }) => {
useEffect(() => {
if (title) {
document.title = title;
}
}, [ title ]);
return (
<CSSTransition timeout={150} classNames={'fade'} appear in>
<>
<ContentContainer css={tw`my-4 sm:my-10`} className={className}>
{showFlashKey &&
<FlashMessageRender byKey={showFlashKey} css={tw`mb-4`}/>
}
{children}
</ContentContainer>
<ContentContainer css={tw`mb-4`}>
<p css={tw`text-center text-neutral-500 text-xs`}>
<a
rel={'noopener nofollow noreferrer'}
href={'https://pterodactyl.io'}
target={'_blank'}
css={tw`no-underline text-neutral-500 hover:text-neutral-300`}
>
Pterodactyl®
</a>
© 2015 - {(new Date()).getFullYear()}
</p>
</ContentContainer>
</>
</CSSTransition>
);
};
export default PageContentBlock;
| Adjust copyright in footer to be more consistent | Adjust copyright in footer to be more consistent | TypeScript | mit | Pterodactyl/Panel,Pterodactyl/Panel,Pterodactyl/Panel,Pterodactyl/Panel | ---
+++
@@ -28,15 +28,15 @@
</ContentContainer>
<ContentContainer css={tw`mb-4`}>
<p css={tw`text-center text-neutral-500 text-xs`}>
- © 2015 - {(new Date()).getFullYear()}
<a
rel={'noopener nofollow noreferrer'}
href={'https://pterodactyl.io'}
target={'_blank'}
css={tw`no-underline text-neutral-500 hover:text-neutral-300`}
>
- Pterodactyl Software
+ Pterodactyl®
</a>
+ © 2015 - {(new Date()).getFullYear()}
</p>
</ContentContainer>
</> |
3f704c2c9736cc5b1cd8f18ade2d87cd52a6387b | src/components/SearchResults.tsx | src/components/SearchResults.tsx | import React from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { EdamamHit } from '../types/edamam';
import { allRecipes } from '../redux/selectors';
import SearchResultsItem from './SearchResultsItem';
type SearchResultsProps = {
allRecipes: EdamamHit[];
};
const Block = styled.section`
padding-top: 8px;
`;
const SearchResultsList = styled.ul`
display: grid;
justify-content: center;
list-style-type: none;
grid-template-columns: repeat(auto-fit, 300px);
grid-gap: 24px;
padding: 0;
`;
const SearchResults = ({ allRecipes }: SearchResultsProps) => (
<Block>
<SearchResultsList>
{allRecipes.map(({ recipe }) => (
<li key={recipe.label}>
<SearchResultsItem {...recipe} />
</li>
))}
</SearchResultsList>
</Block>
);
const mapStateToProps = createStructuredSelector({ allRecipes });
export default connect(mapStateToProps)(SearchResults);
| import React from 'react';
import styled from 'styled-components';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { EdamamHit } from '../types/edamam';
import { allRecipes } from '../redux/selectors';
import SearchResultsItem from './SearchResultsItem';
type SearchResultsProps = {
allRecipes: EdamamHit[];
};
const Block = styled.section`
margin: 0 auto;
max-width: 954px;
`;
const SearchResultsList = styled.ul`
display: grid;
list-style-type: none;
grid-template-columns: repeat(3, 302px);
grid-gap: 24px;
padding: 0;
width: 100%;
`;
const SearchResults = ({ allRecipes }: SearchResultsProps) => (
<Block>
<SearchResultsList>
{allRecipes.map(({ recipe }) => (
<li key={recipe.label}>
<SearchResultsItem {...recipe} />
</li>
))}
</SearchResultsList>
</Block>
);
const mapStateToProps = createStructuredSelector({ allRecipes });
export default connect(mapStateToProps)(SearchResults);
| Set max three recipe cards per row in grid layout | Set max three recipe cards per row in grid layout
| TypeScript | mit | mbchoa/recipeek,mbchoa/recipeek,mbchoa/recipeek | ---
+++
@@ -13,16 +13,17 @@
};
const Block = styled.section`
- padding-top: 8px;
+ margin: 0 auto;
+ max-width: 954px;
`;
const SearchResultsList = styled.ul`
display: grid;
- justify-content: center;
list-style-type: none;
- grid-template-columns: repeat(auto-fit, 300px);
+ grid-template-columns: repeat(3, 302px);
grid-gap: 24px;
padding: 0;
+ width: 100%;
`;
const SearchResults = ({ allRecipes }: SearchResultsProps) => ( |
5243995bc376e93b606633469d52cf81a33131b2 | app/src/lib/git/stash.ts | app/src/lib/git/stash.ts | import { git } from '.'
import { Repository } from '../../models/repository'
export interface IStashEntry {
/** The name of the branch at the time the entry was created. */
readonly branchName: string
/** The SHA of the commit object created as a result of stashing. */
readonly stashSha: string
}
/** RegEx for parsing out the stash SHA and message */
const stashEntryRe = /^([0-9a-f]{5,40})@(.+)$/
export async function getStashEntries(
repository: Repository
): Promise<ReadonlyArray<IStashEntry>> {
const prettyFormat = '%H@%gs'
const result = await git(
['log', '-g', 'refs/stash', `--pretty=${prettyFormat}`],
repository.path,
'getStashEntries'
)
const out = result.stdout
const lines = out.split('\n')
const stashEntries: Array<IStashEntry> = []
for (const line of lines) {
const match = stashEntryRe.exec(line)
console.log(match)
if (match == null) {
continue
}
stashEntries.push({
branchName: 'Todo: parse from message',
stashSha: match[1],
})
}
return stashEntries
}
| import { git } from '.'
import { Repository } from '../../models/repository'
export const MagicStashString = '!github-desktop'
export interface IStashEntry {
/** The name of the branch at the time the entry was created. */
readonly branchName: string
/** The SHA of the commit object created as a result of stashing. */
readonly stashSha: string
}
/** RegEx for parsing out the stash SHA and message */
const stashEntryRe = /^([0-9a-f]{5,40})@(.+)$/
/**
* Get the list of stash entries
*
* @param repository
*/
export async function getStashEntries(
repository: Repository
): Promise<ReadonlyArray<IStashEntry>> {
const prettyFormat = '%H@%gs'
const result = await git(
['log', '-g', 'refs/stash', `--pretty=${prettyFormat}`],
repository.path,
'getStashEntries'
)
const out = result.stdout
const lines = out.split('\n')
const stashEntries: Array<IStashEntry> = []
for (const line of lines) {
const match = stashEntryRe.exec(line)
console.log(match)
if (match == null) {
continue
}
const branchName = getCanonicalRefName(match[2])
// if branch name is null, the stash entry isn't using our magic string
if (branchName === null) {
continue
}
stashEntries.push({
branchName: branchName,
stashSha: match[1],
})
}
return stashEntries
}
function getCanonicalRefName(stashMessage: string): string | null {
const parts = stashMessage.split(':').map(s => s.trim())
const magicString = parts[1]
const canonicalRef = parts[2]
if (magicString !== MagicStashString) {
return null
}
return canonicalRef
}
| Add function to pull out branchName | Add function to pull out branchName
| TypeScript | mit | desktop/desktop,say25/desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus,j-f1/forked-desktop,kactus-io/kactus,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,say25/desktop,kactus-io/kactus,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,say25/desktop,shiftkey/desktop,j-f1/forked-desktop,shiftkey/desktop,artivilla/desktop,desktop/desktop | ---
+++
@@ -1,6 +1,7 @@
import { git } from '.'
import { Repository } from '../../models/repository'
+export const MagicStashString = '!github-desktop'
export interface IStashEntry {
/** The name of the branch at the time the entry was created. */
readonly branchName: string
@@ -12,6 +13,11 @@
/** RegEx for parsing out the stash SHA and message */
const stashEntryRe = /^([0-9a-f]{5,40})@(.+)$/
+/**
+ * Get the list of stash entries
+ *
+ * @param repository
+ */
export async function getStashEntries(
repository: Repository
): Promise<ReadonlyArray<IStashEntry>> {
@@ -34,11 +40,30 @@
continue
}
+ const branchName = getCanonicalRefName(match[2])
+
+ // if branch name is null, the stash entry isn't using our magic string
+ if (branchName === null) {
+ continue
+ }
+
stashEntries.push({
- branchName: 'Todo: parse from message',
+ branchName: branchName,
stashSha: match[1],
})
}
return stashEntries
}
+
+function getCanonicalRefName(stashMessage: string): string | null {
+ const parts = stashMessage.split(':').map(s => s.trim())
+ const magicString = parts[1]
+ const canonicalRef = parts[2]
+
+ if (magicString !== MagicStashString) {
+ return null
+ }
+
+ return canonicalRef
+} |
da6a8db53cfafe06ffae3172d7b4105e717b6a32 | src/derivable/index.ts | src/derivable/index.ts | export * from './atom';
import './boolean-funcs';
export * from './constant';
export * from './derivable';
export * from './derivation';
export * from './lens';
export * from './unpack';
// Extend the Derivable interface with the react method.
import '../reactor';
| export * from './atom';
import './boolean-funcs';
export * from './constant';
export * from './derivable';
export * from './derivation';
export * from './lens';
export * from './unpack';
| Fix circular dependency reported by Rollup | Fix circular dependency reported by Rollup
| TypeScript | apache-2.0 | politie/sherlock,politie/sherlock,politie/sherlock,politie/sherlock | ---
+++
@@ -5,6 +5,3 @@
export * from './derivation';
export * from './lens';
export * from './unpack';
-
-// Extend the Derivable interface with the react method.
-import '../reactor'; |
112fe2d34fba89eaa9f6c08fd48293d76c502c16 | packages/lesswrong/server/emails/sendEmail.ts | packages/lesswrong/server/emails/sendEmail.ts | import { DatabaseServerSetting } from '../databaseSettings';
import type { RenderedEmail } from './renderEmail';
import nodemailer from 'nodemailer';
export const mailUrlSetting = new DatabaseServerSetting<string | null>('mailUrl', null) // The SMTP URL used to send out email
const getMailUrl = () => {
if (mailUrlSetting.get())
return mailUrlSetting.get();
else if (process.env.MAIL_URL)
return process.env.MAIL_URL;
else
return null;
};
// Send an email. Returns true for success or false for failure.
export const sendEmailSmtp = async (email: RenderedEmail): Promise<boolean> => {
const mailUrl = getMailUrl();
if (!mailUrl) {
// eslint-disable-next-line no-console
console.log("Enable to send email because no mailserver is configured");
return false;
}
const transport = nodemailer.createTransport(mailUrl);
const result = await transport.sendMail({
from: email.from,
to: email.to,
subject: email.subject,
text: email.text,
html: email.html,
});
return true;
}
| import { DatabaseServerSetting } from '../databaseSettings';
import type { RenderedEmail } from './renderEmail';
import nodemailer from 'nodemailer';
export const mailUrlSetting = new DatabaseServerSetting<string | null>('mailUrl', null) // The SMTP URL used to send out email
const getMailUrl = () => {
if (mailUrlSetting.get())
return mailUrlSetting.get();
else if (process.env.MAIL_URL)
return process.env.MAIL_URL;
else
return null;
};
// Send an email. Returns true for success or false for failure.
export const sendEmailSmtp = async (email: RenderedEmail): Promise<boolean> => {
const mailUrl = getMailUrl();
if (!mailUrl) {
// eslint-disable-next-line no-console
console.log("Unable to send email because no mailserver is configured");
return false;
}
const transport = nodemailer.createTransport(mailUrl);
const result = await transport.sendMail({
from: email.from,
to: email.to,
subject: email.subject,
text: email.text,
html: email.html,
});
return true;
}
| Fix typo in error message | Fix typo in error message
| TypeScript | mit | Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2 | ---
+++
@@ -19,7 +19,7 @@
if (!mailUrl) {
// eslint-disable-next-line no-console
- console.log("Enable to send email because no mailserver is configured");
+ console.log("Unable to send email because no mailserver is configured");
return false;
}
|
aa016fbe16318900ffe6019e550a526fb3c44e84 | packages/node-sass-once-importer/src/index.ts | packages/node-sass-once-importer/src/index.ts | import {
buildIncludePaths,
resolveUrl,
} from 'node-sass-magic-importer/dist/toolbox';
const EMPTY_IMPORT = {
file: ``,
contents: ``,
};
export = function onceImporter() {
const contextTemplate = {
store: new Set(),
};
return function importer(url: string, prev: string) {
const nodeSassOptions = this.options;
// Create a context for the current importer run.
// An importer run is different from an importer instance,
// one importer instance can spawn infinite importer runs.
if (!this.nodeSassOnceImporterContext) {
this.nodeSassOnceImporterContext = Object.assign({}, contextTemplate);
}
// Each importer run has it's own new store, otherwise
// files already imported in a previous importer run
// would be detected as multiple imports of the same file.
const store = this.nodeSassOnceImporterContext.store;
const includePaths = buildIncludePaths(
nodeSassOptions.includePaths,
prev,
);
const resolvedUrl = resolveUrl(
url,
includePaths,
);
if (store.has(resolvedUrl)) {
return EMPTY_IMPORT;
}
store.add(resolvedUrl);
return null;
};
};
| import {
buildIncludePaths,
resolveUrl,
} from 'node-sass-magic-importer/dist/toolbox';
const EMPTY_IMPORT = {
file: ``,
contents: ``,
};
export = function onceImporter() {
return function importer(url: string, prev: string) {
const nodeSassOptions = this.options;
// Create a context for the current importer run.
// An importer run is different from an importer instance,
// one importer instance can spawn infinite importer runs.
if (!this.nodeSassOnceImporterContext) {
this.nodeSassOnceImporterContext = {
store: new Set(),
};
}
// Each importer run has it's own new store, otherwise
// files already imported in a previous importer run
// would be detected as multiple imports of the same file.
const store = this.nodeSassOnceImporterContext.store;
const includePaths = buildIncludePaths(
nodeSassOptions.includePaths,
prev,
);
const resolvedUrl = resolveUrl(
url,
includePaths,
);
if (store.has(resolvedUrl)) {
return EMPTY_IMPORT;
}
store.add(resolvedUrl);
return null;
};
};
| Fix shared context between webpack instances | Fix shared context between webpack instances
Fixes #189
| TypeScript | mit | maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer,maoberlehner/node-sass-magic-importer | ---
+++
@@ -9,17 +9,15 @@
};
export = function onceImporter() {
- const contextTemplate = {
- store: new Set(),
- };
-
return function importer(url: string, prev: string) {
const nodeSassOptions = this.options;
// Create a context for the current importer run.
// An importer run is different from an importer instance,
// one importer instance can spawn infinite importer runs.
if (!this.nodeSassOnceImporterContext) {
- this.nodeSassOnceImporterContext = Object.assign({}, contextTemplate);
+ this.nodeSassOnceImporterContext = {
+ store: new Set(),
+ };
}
// Each importer run has it's own new store, otherwise |
ad2257e4a309b135e481f77dc820b0363eda42a4 | src/clients/extensions/injected/modules/browser.ts | src/clients/extensions/injected/modules/browser.ts | import { message, PLAYER_EXIT_FULLSCREEN, HANDSHAKE } from "../../../../communication/actions";
import { initActions } from "./events";
import { sendOkResponse } from "./messaging";
const noop = () => { }
export const addMessageListener = (callback: any) => {
chrome.runtime.onMessage.addListener(function (request: message, sender: any, sendResponse: (response: any) => void) {
callback(request, sender)
.then((result: message) => {
chrome.runtime.sendMessage(result);
})
return true
})
}
export const getCurrentDomain = (): string => {
const host = location.host.split('.')
if (host.length > 0)
return host[host.length - 2]
return null
}
export const addKeyboardListeners = () => {
const ESC_KEY = 27;
document.onkeydown = function (evt) {
switch (evt.keyCode) {
case ESC_KEY:
initActions({
from: 'webapp',
type: PLAYER_EXIT_FULLSCREEN
}, null);
break;
}
};
}; | import { message, PLAYER_EXIT_FULLSCREEN, HANDSHAKE } from "../../../../communication/actions";
import { initActions } from "./events";
import { sendOkResponse } from "./messaging";
const noop = () => { }
export const addMessageListener = (callback: any) => {
chrome.runtime.onMessage.addListener(function (request: message, sender: any, sendResponse: (response: any) => void) {
if (request.extensionId)
callback(request, sender)
.then((result: message) => {
if (result)
chrome.runtime.sendMessage(request.extensionId, result, { includeTlsChannelId: false });
})
return true
})
}
export const getCurrentDomain = (): string => {
const host = location.host.split('.')
if (host.length > 0)
return host[host.length - 2]
return null
}
export const addKeyboardListeners = () => {
const ESC_KEY = 27;
document.onkeydown = function (evt) {
switch (evt.keyCode) {
case ESC_KEY:
initActions({
from: 'webapp',
type: PLAYER_EXIT_FULLSCREEN
}, null);
break;
}
};
}; | Fix postmessage only when receiving message from our extension | Fix postmessage only when receiving message from our extension
| TypeScript | mit | wdelmas/remote-potato,wdelmas/remote-potato,wdelmas/remote-potato | ---
+++
@@ -5,10 +5,12 @@
export const addMessageListener = (callback: any) => {
chrome.runtime.onMessage.addListener(function (request: message, sender: any, sendResponse: (response: any) => void) {
- callback(request, sender)
- .then((result: message) => {
- chrome.runtime.sendMessage(result);
- })
+ if (request.extensionId)
+ callback(request, sender)
+ .then((result: message) => {
+ if (result)
+ chrome.runtime.sendMessage(request.extensionId, result, { includeTlsChannelId: false });
+ })
return true
})
} |
d2e062d16e03cd085d5055efda83381fbec21298 | src/utils/gamehelpers.ts | src/utils/gamehelpers.ts | import * as Phaser from 'phaser-ce'
/**
* Sets to skip Phaser internal type checking
* Workaround until https://github.com/photonstorm/phaser-ce/issues/317 is resolved
*/
export const skipBuiltinTypeChecks = (): void => {
Phaser['Component'].Core.skipTypeChecks = true
}
/**
* Get random value between the max and min limits
* @param {number} max
* @param {number} min
* @returns {number}
*/
export function randomInRange(min: number, max: number): number {
return Math.floor(Math.random() * max) + min
}
export function randomYPos(height: number): number {
return randomInRange(5, height - 5)
}
/**
* Check if sprite hits bounds
* @param {any} body
* @param {Phaser.Game} game
* @returns {boolean}
*/
export const checkOnOrOutOfBounds = (body: any, game: Phaser.Game): boolean => {
const { position } = body
const { width, height } = game
const pad = 3
return position.x <= pad || position.x >= width - pad || position.y <= pad || position.y >= height - pad
}
| import * as Phaser from 'phaser-ce'
/**
* Sets to skip Phaser internal type checking
* Workaround until https://github.com/photonstorm/phaser-ce/issues/317 is resolved
*/
export const skipBuiltinTypeChecks = (): void => {
Phaser['Component'].Core.skipTypeChecks = true
}
/**
* Get random value between the max and min limits
* @param {number} max
* @param {number} min
* @returns {number}
*/
export function randomInRange(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
export function randomYPos(height: number): number {
return randomInRange(5, height - 5)
}
/**
* Check if sprite hits bounds
* @param {any} body
* @param {Phaser.Game} game
* @returns {boolean}
*/
export const checkOnOrOutOfBounds = (body: any, game: Phaser.Game): boolean => {
const { position } = body
const { width, height } = game
const pad = 3
return position.x <= pad || position.x >= width - pad || position.y <= pad || position.y >= height - pad
}
export const uuid = (): string => {
return '_' + Math.random().toString(36).substr(2, 9);
}
| Implement uuid function and fix random function | Implement uuid function and fix random function
| TypeScript | unlicense | codingInSpace/CoffeeConundrum,codingInSpace/CoffeeConundrum,codingInSpace/CoffeeConundrum,codingInSpace/CoffeeConundrum | ---
+++
@@ -15,7 +15,7 @@
* @returns {number}
*/
export function randomInRange(min: number, max: number): number {
- return Math.floor(Math.random() * max) + min
+ return Math.floor(Math.random() * (max - min + 1)) + min
}
export function randomYPos(height: number): number {
@@ -34,3 +34,7 @@
const pad = 3
return position.x <= pad || position.x >= width - pad || position.y <= pad || position.y >= height - pad
}
+
+export const uuid = (): string => {
+ return '_' + Math.random().toString(36).substr(2, 9);
+} |
88a5a50752e2e72579ca65c82939efbb2eccdb84 | src/app/doc/utilities/component.component.ts | src/app/doc/utilities/component.component.ts | import { Component, OnInit} from '@angular/core';
import { DocService } from '../doc.service';
import { PolarisComponent } from '../doc.data';
export abstract class ComponentComponent {
public component: PolarisComponent;
protected abstract componentPath;
constructor(protected service: DocService) {
}
ngOnInit() {
this.component = this.service.getByPath(this.componentPath);
}
/**
* Build an optional attribute for the Angular code preview
* @param {string} attr [description]
* @return {string} [description]
*/
protected nullableAttr(attr: string): string {
return this[attr] != "" ? `\n [${attr}]="${this[attr]}"` : '';
}
/**
* Build an optional attribute for the Angular code preview
* @param {string} attr [description]
* @return {string} [description]
*/
protected eventAttr(eventName: string): string {
const eventUC = this.capitalizeFirstLetter(eventName);
return this['log' + eventUC] ? `\n (${eventName})="on${eventUC}($event)"` : '';
}
private capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
eventLog(event: any, name: string = ''):void {
if (name) {
console.log(`Event: ${name}`);
}
console.dir(event);
}
clearConsole = {content: 'Clear console', onAction: console.clear};
}
| import { Component, OnInit} from '@angular/core';
import { DocService } from '../doc.service';
import { PolarisComponent } from '../doc.data';
export abstract class ComponentComponent {
public component: PolarisComponent;
protected abstract componentPath;
constructor(protected service: DocService) {
}
ngOnInit() {
this.component = this.service.getByPath(this.componentPath);
}
/**
* Build an optional attribute for the Angular code preview
* @param {string} attr [description]
* @return {string} [description]
*/
protected nullableAttr(attr: string): string {
return this[attr] != "" ? this.indent(`${attr}="${this[attr]}"`) : '';
}
/**
* Build an optional attribute for the Angular code preview
* @param {string} attr [description]
* @return {string} [description]
*/
protected eventAttr(eventName: string): string {
const eventUC = this.capitalizeFirstLetter(eventName);
return this['log' + eventUC] ? this.indent(`(${eventName})="on${eventUC}($event)"`) : '';
}
private capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
protected indent(str: string): string {
return `\n ${str}`;
}
eventLog(event: any, name: string = ''):void {
if (name) {
console.log(`Event: ${name}`);
}
console.dir(event);
}
clearConsole = {content: 'Clear console', onAction: console.clear};
}
| Add indent function + remove bracket around static attributes. | Add indent function + remove bracket around static attributes.
| TypeScript | mit | syrp-nz/angular-polaris,syrp-nz/angular-polaris,syrp-nz/angular-polaris | ---
+++
@@ -22,7 +22,7 @@
* @return {string} [description]
*/
protected nullableAttr(attr: string): string {
- return this[attr] != "" ? `\n [${attr}]="${this[attr]}"` : '';
+ return this[attr] != "" ? this.indent(`${attr}="${this[attr]}"`) : '';
}
/**
@@ -32,11 +32,15 @@
*/
protected eventAttr(eventName: string): string {
const eventUC = this.capitalizeFirstLetter(eventName);
- return this['log' + eventUC] ? `\n (${eventName})="on${eventUC}($event)"` : '';
+ return this['log' + eventUC] ? this.indent(`(${eventName})="on${eventUC}($event)"`) : '';
}
private capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
+ }
+
+ protected indent(str: string): string {
+ return `\n ${str}`;
}
eventLog(event: any, name: string = ''):void { |
22f865726a758bfee084fc275d77126f80e52378 | js/components/table/raiseBlock/raiseBlock.ts | js/components/table/raiseBlock/raiseBlock.ts | /// <reference types="knockout" />
import ko = require("knockout");
import { TableSlider } from "../../../table/tableSlider";
export class RaiseBlockComponent {
private tableSlider: TableSlider;
constructor(params: { data: TableSlider }) {
this.tableSlider = params.data;
}
}
| /// <reference types="knockout" />
import ko = require("knockout");
import { TableSlider } from "../../../table/tableSlider";
export class RaiseBlockComponent {
private tableSlider: TableSlider;
constructor(params: { data: TableSlider, updateTranslatorTrigger: KnockoutSubscribable<any>, updateTranslator: Function }) {
this.tableSlider = params.data;
if (params.updateTranslatorTrigger) {
params.updateTranslatorTrigger.subscribe(function (newValue) {
params.updateTranslator();
});
}
if (params.updateTranslator) {
params.updateTranslator();
}
}
}
| Add support for force update of raise block | Add support for force update of raise block
| TypeScript | apache-2.0 | online-poker/poker-html-client,online-poker/poker-html-client,online-poker/poker-html-client | ---
+++
@@ -6,7 +6,16 @@
export class RaiseBlockComponent {
private tableSlider: TableSlider;
- constructor(params: { data: TableSlider }) {
+ constructor(params: { data: TableSlider, updateTranslatorTrigger: KnockoutSubscribable<any>, updateTranslator: Function }) {
this.tableSlider = params.data;
+ if (params.updateTranslatorTrigger) {
+ params.updateTranslatorTrigger.subscribe(function (newValue) {
+ params.updateTranslator();
+ });
+ }
+
+ if (params.updateTranslator) {
+ params.updateTranslator();
+ }
}
} |
c6defcf1160f98136ac720e36f0c02236d58f313 | src/definition/load-js.ts | src/definition/load-js.ts | import clearModule from 'clear-module'
import type { Middleware } from 'koa'
import type { Logger } from '../interfaces'
/**
* @param filePath - path to load file
* @param logger
* @returns
* return loaded stuff if successfully loaded;
* return `undefined` if failed to load;
*/
export default function loadJsDef(filePath: string, logger: Logger): Middleware|undefined {
try {
const regexp = new RegExp(`^${process.cwd()}`, 'u')
clearModule.match(regexp)
const loadedFile = require(filePath) as unknown
if (typeof loadedFile === 'function') {
return loadedFile as Middleware
}
if (typeof (loadedFile as { default?: unknown })?.default === 'function') {
return (loadedFile as { default: Middleware }).default
}
logger.warn(`Failed to recognize commonjs export or es default export from module ${filePath}`)
} catch (e: unknown) {
if ((e as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {
logger.debug(`module "${filePath}" doesn't exist`)
} else {
logger.warn(`failed to require module "${filePath}", due to: ${(e as Error).message}`)
}
}
return undefined
}
| import clearModule from 'clear-module'
import type { Middleware } from 'koa'
import path from 'path'
import type { Logger } from '../interfaces'
/**
* @param filePath - path to load file
* @param logger
* @returns
* return loaded stuff if successfully loaded;
* return `undefined` if failed to load;
*/
export default function loadJsDef(filePath: string, logger: Logger): Middleware|undefined {
try {
const cwd = path.sep === '/' ? process.cwd() : process.cwd().replaceAll(path.sep, '/')
const regexp = new RegExp(`^${cwd}`, 'u')
clearModule.match(regexp)
const loadedFile = require(filePath) as unknown
if (typeof loadedFile === 'function') {
return loadedFile as Middleware
}
if (typeof (loadedFile as { default?: unknown })?.default === 'function') {
return (loadedFile as { default: Middleware }).default
}
logger.warn(`Failed to recognize commonjs export or es default export from module ${filePath}`)
} catch (e: unknown) {
if ((e as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {
logger.debug(`module "${filePath}" doesn't exist`)
} else {
logger.warn(`failed to require module "${filePath}", due to: ${(e as Error).message}`)
}
}
return undefined
}
| Fix windows path RegExp error | Fix windows path RegExp error
| TypeScript | mit | whitetrefoil/mock-server-middleware,whitetrefoil/mock-server-middleware | ---
+++
@@ -1,5 +1,6 @@
import clearModule from 'clear-module'
import type { Middleware } from 'koa'
+import path from 'path'
import type { Logger } from '../interfaces'
@@ -12,7 +13,8 @@
*/
export default function loadJsDef(filePath: string, logger: Logger): Middleware|undefined {
try {
- const regexp = new RegExp(`^${process.cwd()}`, 'u')
+ const cwd = path.sep === '/' ? process.cwd() : process.cwd().replaceAll(path.sep, '/')
+ const regexp = new RegExp(`^${cwd}`, 'u')
clearModule.match(regexp)
const loadedFile = require(filePath) as unknown
if (typeof loadedFile === 'function') { |
782f4cf8646ee4aa3382b4176ff7ffe2884c6e0a | src/report/CommandLine.ts | src/report/CommandLine.ts | import Symbols from './Symbols';
class CommandLine {
public write(results: ResultInterface[], level: number = 0): void {
results.forEach((result) => {
this.print(result.getTitle(), result.getStatus(), level);
const r = result.getResults();
if (r !== null) {
this.write(r, level + 1);
}
});
}
public print(message: string, status: string, level: number): void {
console.log('%s%s %s', Array(level * 4).join(' '), this.getFormattedSymbol(status), message);
}
public getFormattedSymbol(status: string) {
switch (status) {
case 'SUCCESSFUL':
return '\x1b[32m' + Symbols.success + '\x1b[0m';
case 'UNSUCCESSFUL':
return '\x1b[33m' + Symbols.warning + '\x1b[0m';
case 'ERROR':
return '\x1b[31m' + Symbols.error + '\x1b[0m';
}
return '\x1b[34m' + Symbols.info + '\x1b[0m';
}
}
export default CommandLine;
| import Symbols from './Symbols';
class CommandLine {
public write(results: ResultInterface[], level: number = 0): void {
results.forEach((result) => {
const r = result.getResults();
if ((r !== null && r.length > 0) || level > 0) {
this.print(result.getTitle(), result.getStatus(), level);
}
if (r !== null) {
this.write(r, level + 1);
}
});
}
public print(message: string, status: string, level: number): void {
console.log('%s%s %s', Array(level * 4).join(' '), this.getFormattedSymbol(status), message);
}
public getFormattedSymbol(status: string) {
switch (status) {
case 'SUCCESSFUL':
return '\x1b[32m' + Symbols.success + '\x1b[0m';
case 'UNSUCCESSFUL':
return '\x1b[33m' + Symbols.warning + '\x1b[0m';
case 'ERROR':
return '\x1b[31m' + Symbols.error + '\x1b[0m';
}
return '\x1b[34m' + Symbols.info + '\x1b[0m';
}
}
export default CommandLine;
| Fix report when grep param is used | Fix report when grep param is used
If the user wanted to run just one or more tests from security,
the report also contained HTML successful message.
| TypeScript | mit | juffalow/pentest-tool-lite,juffalow/pentest-tool-lite | ---
+++
@@ -3,8 +3,11 @@
class CommandLine {
public write(results: ResultInterface[], level: number = 0): void {
results.forEach((result) => {
- this.print(result.getTitle(), result.getStatus(), level);
const r = result.getResults();
+
+ if ((r !== null && r.length > 0) || level > 0) {
+ this.print(result.getTitle(), result.getStatus(), level);
+ }
if (r !== null) {
this.write(r, level + 1); |
bcaadd6f14253ea3fe06cf2b55add859c9beb2e6 | src/HawkEye.ts | src/HawkEye.ts | import InstanceCache from 'Core/InstanceCache';
import reducers from 'Reducers/Index';
import configureStore from 'Core/ConfigureStore';
import { renderApplication } from 'Core/Renderer';
import RequestFactory from 'Core/RequestFactory';
import GitHub from 'GitHub/GitHub';
import { gitHubApiUrl } from 'Constants/Services/Github';
import routes from 'Routes';
import { syncHistoryWithStore } from 'react-router-redux';
import { hashHistory } from 'react-router';
/**
* @todo: This needs to change. A lot.
*/
class HawkEye
{
constructor()
{
const store = configureStore(reducers);
const history = syncHistoryWithStore(hashHistory, store);
const renderTarget = document.getElementById('root');
// Services
InstanceCache
.addInstance<IGitHub>('IGitHub', new GitHub(
new RequestFactory(gitHubApiUrl)));
// Render the application
renderApplication(renderTarget, store, history, routes);
}
};
export default HawkEye; | import InstanceCache from 'Core/InstanceCache';
import reducers from 'Reducers/Index';
import configureStore from 'Core/ConfigureStore';
import { renderApplication } from 'Core/Renderer';
import RequestFactory from 'Core/RequestFactory';
import GitHub from 'GitHub/GitHub';
import { gitHubApiUrl } from 'Constants/Services/GitHub';
import routes from 'Routes';
import { syncHistoryWithStore } from 'react-router-redux';
import { hashHistory } from 'react-router';
/**
* @todo: This needs to change. A lot.
*/
class HawkEye
{
constructor()
{
const store = configureStore(reducers);
const history = syncHistoryWithStore(hashHistory, store);
const renderTarget = document.getElementById('root');
// Services
InstanceCache
.addInstance<IGitHub>('IGitHub', new GitHub(
new RequestFactory(gitHubApiUrl)));
// Render the application
renderApplication(renderTarget, store, history, routes);
}
};
export default HawkEye; | Fix GitHub capitalisation in import | Fix GitHub capitalisation in import
| TypeScript | mit | harksys/HawkEye,harksys/HawkEye,harksys/HawkEye | ---
+++
@@ -6,7 +6,7 @@
import RequestFactory from 'Core/RequestFactory';
import GitHub from 'GitHub/GitHub';
-import { gitHubApiUrl } from 'Constants/Services/Github';
+import { gitHubApiUrl } from 'Constants/Services/GitHub';
import routes from 'Routes';
|
46a08045af5a2875af6af1d1fee66b87dab93900 | src/actions.ts | src/actions.ts | import {AppStore} from "./app-store";
/**
* Abstract class to provide utility methods for action creators
*/
export class Actions {
private appStore:AppStore = null;
constructor(appStore?:AppStore) {
if (appStore) {
this.appStore = appStore;
}
}
public createDispatcher(action:(...n:any[])=>any, appStore?:AppStore):(...n)=>void {
if (action && appStore && action instanceof AppStore) {
// backwards compatibility for version 1.1.0
[action, appStore] = [ <any> appStore, <any> action ];
}
if (!appStore && !this.appStore) {
throw new Error("Can't find AppStore for dispatching action");
}
appStore = appStore || this.appStore;
return (...n)=>appStore.dispatch(action.call(this, ...n))
}
}
| import {AppStore} from "./app-store";
/**
* Abstract class to provide utility methods for action creators
*/
export class Actions {
protected appStore:AppStore = null;
constructor(appStore?:AppStore) {
if (appStore) {
this.appStore = appStore;
}
}
public createDispatcher(action:(...n:any[])=>any, appStore?:AppStore):(...n)=>void {
if (action && appStore && action instanceof AppStore) {
// backwards compatibility for version 1.1.0
[action, appStore] = [ <any> appStore, <any> action ];
}
if (!appStore && !this.appStore) {
throw new Error("Can't find AppStore for dispatching action");
}
appStore = appStore || this.appStore;
return (...n)=>appStore.dispatch(action.call(this, ...n))
}
}
| Update appStore in Actions to be protected | feat: Update appStore in Actions to be protected
| TypeScript | mit | InfomediaLtd/angular2-redux,InfomediaLtd/angular2-redux,InfomediaLtd/angular2-redux | ---
+++
@@ -5,7 +5,7 @@
*/
export class Actions {
- private appStore:AppStore = null;
+ protected appStore:AppStore = null;
constructor(appStore?:AppStore) {
if (appStore) { |
7a06c3e25eac0bf32642cc1ee75840b5acb3dbae | src/lib/constants.ts | src/lib/constants.ts | /**
* Delay time before close autocomplete.
*
* (This prevent autocomplete DOM get detroyed before access data.)
*/
export const AUTOCOMPLETE_CLOSE_DELAY = 250;
/**
* Allowed attributes that can be passed to internal input.
*/
export const ALLOWED_ATTRS = [
'name',
'autofocus',
'placeholder',
'disabled',
'readonly',
'required',
'tabindex'
];
| /**
* Delay time before close autocomplete.
*
* (This prevent autocomplete DOM get detroyed before access data.)
*/
export const AUTOCOMPLETE_CLOSE_DELAY = 250;
/**
* Allowed attributes that can be passed to internal input.
*/
export const ALLOWED_ATTRS = [
'autofocus',
'disabled',
'id',
'inputmode',
'list',
'maxlength',
'minlength',
'name',
'pattern',
'placeholder',
'readonly',
'required',
'required',
'size',
'spellcheck',
'tabindex',
'title'
];
| Allow more attributes for internal input | :wrench: Allow more attributes for internal input
| TypeScript | mit | gluons/vue-thailand-address | ---
+++
@@ -9,11 +9,21 @@
* Allowed attributes that can be passed to internal input.
*/
export const ALLOWED_ATTRS = [
+ 'autofocus',
+ 'disabled',
+ 'id',
+ 'inputmode',
+ 'list',
+ 'maxlength',
+ 'minlength',
'name',
- 'autofocus',
+ 'pattern',
'placeholder',
- 'disabled',
'readonly',
'required',
- 'tabindex'
+ 'required',
+ 'size',
+ 'spellcheck',
+ 'tabindex',
+ 'title'
]; |
4bcab210d76348597e3df88f6d736c30b4225a1a | app/src/ui/lib/link-button.tsx | app/src/ui/lib/link-button.tsx | import * as React from 'react'
import { shell } from 'electron'
import * as classNames from 'classnames'
interface ILinkButtonProps extends React.HTMLProps<HTMLAnchorElement> {
/** A URI to open on click. */
readonly uri?: string
/** A function to call on click. */
readonly onClick?: () => void
/** The title of the button. */
readonly children?: string
/** CSS classes attached to the component */
readonly className?: string
/** The tab index of the anchor element. */
readonly tabIndex?: number
/** Disable the link from being clicked */
readonly disabled?: boolean
}
/** A link component. */
export class LinkButton extends React.Component<ILinkButtonProps, void> {
public render() {
const { uri, className, ...otherProps } = this.props
const href = uri || ''
const props = { ...otherProps, className: classNames('link-button-component', className), onClick: this.onClick, href }
return (
<a {...props}>
{this.props.children}
</a>
)
}
private onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault()
if (this.props.disabled) {
return
}
const uri = this.props.uri
if (uri) {
shell.openExternal(uri)
}
const onClick = this.props.onClick
if (onClick) {
onClick()
}
}
}
| import * as React from 'react'
import { shell } from 'electron'
import * as classNames from 'classnames'
interface ILinkButtonProps {
/** A URI to open on click. */
readonly uri?: string | JSX.Element | ReadonlyArray<JSX.Element>
/** A function to call on click. */
readonly onClick?: () => void
/** The title of the button. */
readonly children?: string
/** CSS classes attached to the component */
readonly className?: string
/** The tab index of the anchor element. */
readonly tabIndex?: number
/** Disable the link from being clicked */
readonly disabled?: boolean
/** title-text or tooltip for the link */
readonly title?: string
}
/** A link component. */
export class LinkButton extends React.Component<ILinkButtonProps, void> {
public render() {
const { uri, className, ...otherProps } = this.props
const href = uri || ''
const props = { ...otherProps, className: classNames('link-button-component', className), onClick: this.onClick, href }
return (
<a {...props}>
{this.props.children}
</a>
)
}
private onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
event.preventDefault()
if (this.props.disabled) {
return
}
const uri = this.props.uri
if (uri) {
shell.openExternal(uri)
}
const onClick = this.props.onClick
if (onClick) {
onClick()
}
}
}
| Remove all new <LinkButton> props except title; allow any type of child node | Remove all new <LinkButton> props except title; allow any type of child node | TypeScript | mit | j-f1/forked-desktop,say25/desktop,desktop/desktop,shiftkey/desktop,gengjiawen/desktop,artivilla/desktop,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,shiftkey/desktop,desktop/desktop,hjobrien/desktop,shiftkey/desktop,kactus-io/kactus,say25/desktop,gengjiawen/desktop,kactus-io/kactus,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,gengjiawen/desktop,j-f1/forked-desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,say25/desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop,kactus-io/kactus,hjobrien/desktop,hjobrien/desktop | ---
+++
@@ -2,9 +2,9 @@
import { shell } from 'electron'
import * as classNames from 'classnames'
-interface ILinkButtonProps extends React.HTMLProps<HTMLAnchorElement> {
+interface ILinkButtonProps {
/** A URI to open on click. */
- readonly uri?: string
+ readonly uri?: string | JSX.Element | ReadonlyArray<JSX.Element>
/** A function to call on click. */
readonly onClick?: () => void
@@ -20,6 +20,9 @@
/** Disable the link from being clicked */
readonly disabled?: boolean
+
+ /** title-text or tooltip for the link */
+ readonly title?: string
}
/** A link component. */ |
1626e7253c64dd751fa73d1e7344d1819857774f | app/src/lib/firebase.ts | app/src/lib/firebase.ts | import * as firebase from "firebase";
const projectId = process.env.REACT_APP_FIREBASE_PROJECT_ID;
export function initialize(): void {
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: `${projectId}.firebaseapp.com`,
databaseURL: `https://${projectId}.firebaseio.com`,
storageBucket: `${projectId}.appspot.com`,
});
}
export async function signIn(): Promise<void> {
await firebase.auth().signInWithRedirect(new firebase.auth.GithubAuthProvider());
await firebase.auth().getRedirectResult();
}
export function onAuthStateChanged(callback: (user: firebase.User) => void): void {
firebase.auth().onAuthStateChanged(callback);
}
| import * as firebase from "firebase";
const projectId = process.env.REACT_APP_FIREBASE_PROJECT_ID;
export function initialize(): void {
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: `${projectId}.firebaseapp.com`,
databaseURL: `https://${projectId}.firebaseio.com`,
storageBucket: `${projectId}.appspot.com`,
});
}
export async function signIn(): Promise<void> {
await firebase.auth().signInWithRedirect(new firebase.auth.GithubAuthProvider());
await firebase.auth().getRedirectResult();
}
export async function signOut(): Promise<void> {
await firebase.auth().signOut();
}
export async function deleteAccount(): Promise<void> {
await firebase.auth().currentUser.delete();
}
export function onAuthStateChanged(callback: (user: firebase.User) => void): void {
firebase.auth().onAuthStateChanged(callback);
}
| Add signOut and deleteAccount functions | Add signOut and deleteAccount functions
| TypeScript | mit | raviqqe/code2d,raviqqe/code2d,raviqqe/code2d,raviqqe/code2d | ---
+++
@@ -16,6 +16,14 @@
await firebase.auth().getRedirectResult();
}
+export async function signOut(): Promise<void> {
+ await firebase.auth().signOut();
+}
+
+export async function deleteAccount(): Promise<void> {
+ await firebase.auth().currentUser.delete();
+}
+
export function onAuthStateChanged(callback: (user: firebase.User) => void): void {
firebase.auth().onAuthStateChanged(callback);
} |
049e3e9e1394508807004a8e401e826a78fbdd32 | src/search.ts | src/search.ts | import { getMoves } from './moves';
import { evaluate } from './evaluation';
import { makeMove } from './game';
export function getBestMove(grid: boolean[], forX: boolean, depth?: number): number {
if (depth == undefined)
depth = grid.length;
const moves = getMoves(grid);
const movesWithScores = moves.map(move => {
const newGrid = makeMove(grid, move, forX);
const evaluation = evaluate(newGrid);
return {
move,
score: forX ? evaluation : -evaluation
};
});
const sortedMovesWithScores = movesWithScores.sort((a, b) => b.score - a.score);
const sortedMoves = sortedMovesWithScores.map(x => x.move);
// Return the move with the best evaluation so far
return sortedMoves[0];
}
| import { getMoves } from './moves';
import { evaluate } from './evaluation';
import { makeMove } from './game';
import { Grid, Move } from './definitions';
export function getBestMove(grid: Grid, forX: boolean, depth?: number): Move {
if (depth == undefined)
depth = grid.length;
const moves = getMoves(grid);
const movesWithScores = moves.map(move => {
const newGrid = makeMove(grid, move, forX);
const evaluation = evaluate(newGrid);
return {
move,
score: forX ? evaluation : -evaluation
};
});
const sortedMovesWithScores = movesWithScores.sort((a, b) => b.score - a.score);
const sortedMoves = sortedMovesWithScores.map(x => x.move);
// Return the move with the best evaluation so far
return sortedMoves[0];
}
| Make getBestMove function use Grid and Move | Make getBestMove function use Grid and Move
| TypeScript | mit | artfuldev/tictactoe-ai,artfuldev/tictactoe-ai | ---
+++
@@ -1,8 +1,9 @@
import { getMoves } from './moves';
import { evaluate } from './evaluation';
import { makeMove } from './game';
+import { Grid, Move } from './definitions';
-export function getBestMove(grid: boolean[], forX: boolean, depth?: number): number {
+export function getBestMove(grid: Grid, forX: boolean, depth?: number): Move {
if (depth == undefined)
depth = grid.length;
const moves = getMoves(grid); |
2c159fa94d59a3790ce658a388609bedfb791f34 | src/test/runTests.ts | src/test/runTests.ts | import * as path from 'path';
import { runTests } from 'vscode-test';
(async function main() {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = process.cwd();
// The path to test runner
// Passed to --extensionTestsPath
const extensionTestsPath = path.join(__dirname, './suite');
// The path to the workspace file
const workspace = path.resolve('test-fixtures', 'test.code-workspace');
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [workspace]
});
})().catch(err => console.log(err));
| import * as path from 'path';
import { runTests } from 'vscode-test';
(async function main() {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = process.cwd();
// The path to test runner
// Passed to --extensionTestsPath
const extensionTestsPath = path.join(__dirname, './suite');
// The path to the workspace file
const workspace = path.resolve('test-fixtures', 'test.code-workspace');
// Download VS Code, unzip it and run the integration test
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
launchArgs: [workspace, "--disable-extensions"]
});
})().catch(err => console.log(err));
| Disable other extensions when running tests | Disable other extensions when running tests
| TypeScript | mit | esbenp/prettier-vscode | ---
+++
@@ -17,6 +17,6 @@
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
- launchArgs: [workspace]
+ launchArgs: [workspace, "--disable-extensions"]
});
})().catch(err => console.log(err)); |
29946f324ae128941c0c8354de6b2642b1f6054d | todomvc-react-mobx-typescript/src/components/Main.tsx | todomvc-react-mobx-typescript/src/components/Main.tsx | import * as React from 'react'
import { Component } from 'react'
import { TodoModel } from './TodoModel'
import { TodoList } from './TodoList'
interface Props {
deleteTodo: (todo: TodoModel) => void
todos: Array<TodoModel>
}
export class Main extends Component<Props, void> {
public render() {
return (
<section className="main">
<input type="checkbox" className="toggle-all"/>
<label htmlFor="toggle-all">Mark all as complete</label>
<TodoList
deleteTodo={this.props.deleteTodo}
todos={this.props.todos}
/>
</section>
)
}
} | import * as React from 'react'
import { Component } from 'react'
import { observer } from 'mobx-react'
import { TodoModel } from './TodoModel'
import { TodoList } from './TodoList'
interface Props {
deleteTodo: (todo: TodoModel) => void
todos: Array<TodoModel>
}
@observer
export class Main extends Component<Props, void> {
public render() {
const allTodosChecked = this.props.todos.every(todo => todo.completed)
return (
<section className="main">
<input
className="toggle-all"
type="checkbox"
checked={allTodosChecked}
/>
<label htmlFor="toggle-all">Mark all as complete</label>
<TodoList
deleteTodo={this.props.deleteTodo}
todos={this.props.todos}
/>
</section>
)
}
} | Add checkbox for toggling all todos | Add checkbox for toggling all todos
| TypeScript | unlicense | janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations | ---
+++
@@ -1,5 +1,6 @@
import * as React from 'react'
import { Component } from 'react'
+import { observer } from 'mobx-react'
import { TodoModel } from './TodoModel'
import { TodoList } from './TodoList'
@@ -9,11 +10,18 @@
todos: Array<TodoModel>
}
+@observer
export class Main extends Component<Props, void> {
public render() {
+ const allTodosChecked = this.props.todos.every(todo => todo.completed)
+
return (
<section className="main">
- <input type="checkbox" className="toggle-all"/>
+ <input
+ className="toggle-all"
+ type="checkbox"
+ checked={allTodosChecked}
+ />
<label htmlFor="toggle-all">Mark all as complete</label>
<TodoList
deleteTodo={this.props.deleteTodo} |
caf0285970bb23f9912fb96f63c06b551d4dbeec | plugins/keycloak/keycloak.service.ts | plugins/keycloak/keycloak.service.ts | namespace HawtioKeycloak {
const TOKEN_UPDATE_INTERVAL = 5; // 5 sec.
export class KeycloakService {
constructor(
public readonly enabled: boolean,
public readonly keycloak: Keycloak.KeycloakInstance) {
}
updateToken(onSuccess: (token: string) => void, onError?: () => void): void {
this.keycloak.updateToken(TOKEN_UPDATE_INTERVAL)
.success(() => {
let token = this.keycloak.token;
onSuccess(token);
})
.error(() => {
log.error("Couldn't update token");
if (onError) {
onError();
}
});
}
setupJQueryAjax(userDetails: Core.AuthService): void {
log.debug("Setting authorization header to token");
$.ajaxSetup({
beforeSend: (xhr: JQueryXHR, settings: JQueryAjaxSettings) => {
if (this.keycloak.authenticated && !this.keycloak.isTokenExpired(TOKEN_UPDATE_INTERVAL)) {
// hawtio uses BearerTokenLoginModule on server side
xhr.setRequestHeader('Authorization', Core.getBasicAuthHeader(keycloak.subject, keycloak.token));
} else {
log.debug("Skipped request", settings.url, "for now.");
this.updateToken(
(token) => {
if (token) {
log.debug('Keycloak token refreshed. Set new value to userDetails');
userDetails.token = token;
}
log.debug("Re-sending request after successfully update keycloak token:", settings.url);
$.ajax(settings);
},
() => userDetails.logout());
return false;
}
}
});
}
}
}
| namespace HawtioKeycloak {
const TOKEN_UPDATE_INTERVAL = 5; // 5 sec.
export class KeycloakService {
constructor(
public readonly enabled: boolean,
public readonly keycloak: Keycloak.KeycloakInstance) {
}
updateToken(onSuccess: (token: string) => void, onError?: () => void): void {
this.keycloak.updateToken(TOKEN_UPDATE_INTERVAL)
.success(() => {
let token = this.keycloak.token;
onSuccess(token);
})
.error(() => {
log.error("Couldn't update token");
if (onError) {
onError();
}
});
}
setupJQueryAjax(userDetails: Core.AuthService): void {
log.debug("Setting authorization header to token");
$.ajaxSetup({
beforeSend: (xhr: JQueryXHR, settings: JQueryAjaxSettings) => {
if (this.keycloak.authenticated && !this.keycloak.isTokenExpired(TOKEN_UPDATE_INTERVAL)) {
// hawtio uses BearerTokenLoginModule on server side
xhr.setRequestHeader('Authorization', Core.getBasicAuthHeader(keycloak.profile.username, keycloak.token));
} else {
log.debug("Skipped request", settings.url, "for now.");
this.updateToken(
(token) => {
if (token) {
log.debug('Keycloak token refreshed. Set new value to userDetails');
userDetails.token = token;
}
log.debug("Re-sending request after successfully update keycloak token:", settings.url);
$.ajax(settings);
},
() => userDetails.logout());
return false;
}
}
});
}
}
}
| Change Keycloak Authorization header from cryptic subject to profile.username | Change Keycloak Authorization header from cryptic subject to profile.username
| TypeScript | apache-2.0 | hawtio/hawtio-oauth,hawtio/hawtio-oauth,hawtio/hawtio-oauth | ---
+++
@@ -29,7 +29,7 @@
beforeSend: (xhr: JQueryXHR, settings: JQueryAjaxSettings) => {
if (this.keycloak.authenticated && !this.keycloak.isTokenExpired(TOKEN_UPDATE_INTERVAL)) {
// hawtio uses BearerTokenLoginModule on server side
- xhr.setRequestHeader('Authorization', Core.getBasicAuthHeader(keycloak.subject, keycloak.token));
+ xhr.setRequestHeader('Authorization', Core.getBasicAuthHeader(keycloak.profile.username, keycloak.token));
} else {
log.debug("Skipped request", settings.url, "for now.");
this.updateToken( |
3cc02b61fe33377c1fba3f9a665b356f901dad03 | src/pages/login/login.ts | src/pages/login/login.ts | import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loginForm: FormGroup;
constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public loadingCtrl: LoadingController) {
this.loginForm = this.formBuilder.group({
url: ['', Validators.required],
user: ['', Validators.required],
password: ['', Validators.required],
});
}
login() {
console.log(this.loginForm.value)
}
}
| import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loginForm: FormGroup;
constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder, public loadingCtrl: LoadingController) {
this.loginForm = this.formBuilder.group({
url: ['', Validators.required],
user: ['', Validators.required],
password: ['', Validators.required],
});
}
login() {
let loader = this.loadingCtrl.create({
content: "Connecting to IMS Server",
duration: 3000
});
loader.present();
}
}
| Add loading icon, To lateron wait until user is logged in and maybe content of next page has been loaded. | Add loading icon,
To lateron wait until user is logged in and maybe content of next page has been loaded.
| TypeScript | mit | IMSmobile/app,IMSmobile/app,IMSmobile/app,IMSmobile/app | ---
+++
@@ -1,5 +1,8 @@
import { Component } from '@angular/core';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
+import { NavController, NavParams } from 'ionic-angular';
+import { LoadingController } from 'ionic-angular';
+
@@ -20,7 +23,11 @@
}
login() {
- console.log(this.loginForm.value)
+ let loader = this.loadingCtrl.create({
+ content: "Connecting to IMS Server",
+ duration: 3000
+ });
+ loader.present();
}
} |
ec13de1119d5fdcc19f02e936317d6c2ad220ee1 | framework/src/testsuite/TestRequest.ts | framework/src/testsuite/TestRequest.ts | import { JovoRequest, JovoSession, EntityMap, UnknownObject } from '..';
import { Intent } from '../interfaces';
import { AudioInput, InputType } from '../JovoInput';
export class TestRequest extends JovoRequest {
isTestRequest = true;
locale!: string;
session: JovoSession = new JovoSession({ state: [] });
userId!: string;
getLocale(): string | undefined {
return this.locale;
}
setLocale(locale: string): void {
this.locale = locale;
}
getIntent(): string | Intent | undefined {
return;
}
getEntities(): EntityMap | undefined {
return;
}
getInputType(): string | undefined {
return;
}
getInputText(): string | undefined {
return;
}
getInputAudio(): AudioInput | undefined {
return;
}
setSessionData(data: Record<string, unknown>): void {
this.session.data = data;
}
getUserId(): string | undefined {
return this.userId;
}
setUserId(userId: string): void {
this.userId = userId;
}
getSessionData(): UnknownObject | undefined {
return this.session.data;
}
getSessionId(): string | undefined {
return this.session.id;
}
isNewSession(): boolean | undefined {
return this.session.isNew;
}
getDeviceCapabilities(): string[] | undefined {
return;
}
}
| import { JovoRequest, JovoSession, EntityMap, UnknownObject } from '..';
import { Intent } from '../interfaces';
import { AudioInput, InputType } from '../JovoInput';
export class TestRequest extends JovoRequest {
isTestRequest = true;
locale!: string;
session: JovoSession = new JovoSession({ isNew: false, state: [] });
userId!: string;
getLocale(): string | undefined {
return this.locale;
}
setLocale(locale: string): void {
this.locale = locale;
}
getIntent(): string | Intent | undefined {
return;
}
getEntities(): EntityMap | undefined {
return;
}
getInputType(): string | undefined {
return;
}
getInputText(): string | undefined {
return;
}
getInputAudio(): AudioInput | undefined {
return;
}
setSessionData(data: Record<string, unknown>): void {
this.session.data = data;
}
getUserId(): string | undefined {
return this.userId;
}
setUserId(userId: string): void {
this.userId = userId;
}
getSessionData(): UnknownObject | undefined {
return this.session.data;
}
getSessionId(): string | undefined {
return this.session.id;
}
isNewSession(): boolean | undefined {
return this.session.isNew;
}
getDeviceCapabilities(): string[] | undefined {
return;
}
}
| Set isNew to false on default session | :bug: Set isNew to false on default session
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -5,7 +5,7 @@
export class TestRequest extends JovoRequest {
isTestRequest = true;
locale!: string;
- session: JovoSession = new JovoSession({ state: [] });
+ session: JovoSession = new JovoSession({ isNew: false, state: [] });
userId!: string;
getLocale(): string | undefined { |
6f9c6681f635adb83561eef439b9bf420d3d4a25 | src/util/DeprecatedClassDecorator.ts | src/util/DeprecatedClassDecorator.ts | export function deprecatedClass(message: string): ClassDecorator;
export function deprecatedClass<T>(target: T, key: PropertyKey): void;
/**
* Logs a deprecation warning for the decorated class if
* an instance is created
* @param {string} [message] Class deprecation message
* @returns {ClassDecorator}
*/
export function deprecatedClass<T extends new (...args: any[]) => any>(...decoratorArgs: any[]): any
{
if (typeof (deprecatedClass as any).warnCache === 'undefined') (deprecatedClass as any).warnCache = {};
const warnCache: { [key: string]: boolean } = (deprecatedClass as any).warnCache;
let message: string = decoratorArgs[0];
function emitDeprecationWarning(warning: string): void
{
if (warnCache[warning]) return;
warnCache[warning] = true;
process.emitWarning(warning, 'DeprecationWarning');
}
function decorate(target: T): T
{
return class extends target
{
public constructor(...args: any[])
{
emitDeprecationWarning(message);
super(...args);
}
};
}
if (typeof message !== 'string')
{
const [target]: [T] = decoratorArgs as any;
message = `Class \`${target.name}\` is deprecated and will be removed in a future release`;
return decorate(target);
}
else return decorate;
}
| export function deprecatedClass(message: string): ClassDecorator;
export function deprecatedClass<T>(target: T): T;
/**
* Logs a deprecation warning for the decorated class if
* an instance is created
* @param {string} [message] Class deprecation message
* @returns {ClassDecorator}
*/
export function deprecatedClass<T extends new (...args: any[]) => any>(...decoratorArgs: any[]): any
{
if (typeof (deprecatedClass as any).warnCache === 'undefined') (deprecatedClass as any).warnCache = {};
const warnCache: { [key: string]: boolean } = (deprecatedClass as any).warnCache;
let message: string = decoratorArgs[0];
function emitDeprecationWarning(warning: string): void
{
if (warnCache[warning]) return;
warnCache[warning] = true;
process.emitWarning(warning, 'DeprecationWarning');
}
function decorate(target: T): T
{
return class extends target
{
public constructor(...args: any[])
{
emitDeprecationWarning(message);
super(...args);
}
};
}
if (typeof message !== 'string')
{
const [target]: [T] = decoratorArgs as any;
message = `Class \`${target.name}\` is deprecated and will be removed in a future release`;
return decorate(target);
}
else return decorate;
}
| Update deprecatedClass decorator function signatures | Update deprecatedClass decorator function signatures
| TypeScript | mit | zajrik/yamdbf,zajrik/yamdbf | ---
+++
@@ -1,5 +1,5 @@
export function deprecatedClass(message: string): ClassDecorator;
-export function deprecatedClass<T>(target: T, key: PropertyKey): void;
+export function deprecatedClass<T>(target: T): T;
/**
* Logs a deprecation warning for the decorated class if
* an instance is created |
0eb9a227403ee4430624fbb7fe16b13941e4586e | types/bigi/bigi-tests.ts | types/bigi/bigi-tests.ts | import BigInteger = require('bigi');
const b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012");
const b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
const b3 = b1.multiply(b2);
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132
| import BigInteger = require('bigi');
const b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012");
const b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
const b3 = b1.multiply(b2);
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132
const b4 = BigInteger.valueOf(42);
const b5 = BigInteger.valueOf(10);
const b6 = b4.multiply(b5);
console.log(b6);
// => BigInteger { '0': 420, '1': 0, t: 1, s: 0 }
| Expand tests to cover the previous change | Expand tests to cover the previous change
| TypeScript | mit | rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,markogresak/DefinitelyTyped,rolandzwaga/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,one-pieces/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped | ---
+++
@@ -7,3 +7,10 @@
console.log(b3.toHex());
// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132
+
+const b4 = BigInteger.valueOf(42);
+const b5 = BigInteger.valueOf(10);
+const b6 = b4.multiply(b5);
+
+console.log(b6);
+// => BigInteger { '0': 420, '1': 0, t: 1, s: 0 } |
2ece138af6866ccf1fdfa1e14d1e033fab0696ff | src/a2t-ui/a2t-ui.routes.ts | src/a2t-ui/a2t-ui.routes.ts | import { Routes, RouterModule } from '@angular/router';
import { Angular2TokenService } from '../angular2-token.service';
import { A2tUiComponent } from './a2t-ui.component';
import { A2tSignInComponent } from './a2t-sign-in/a2t-sign-in.component';
import { A2tSignUpComponent } from './a2t-sign-up/a2t-sign-up.component';
import { A2tResetPasswordComponent } from './a2t-reset-password/a2t-reset-password.component';
import { A2tUpdatePasswordComponent } from './a2t-update-password/a2t-update-password.component';
const routes: Routes = [{
path: 'session',
component: A2tUiComponent,
children: [
{ path: 'sign-in', component: A2tSignInComponent },
{ path: 'sign-up', component: A2tSignUpComponent },
{ path: 'reset-password', component: A2tResetPasswordComponent },
{
path: 'update-password',
component: A2tUpdatePasswordComponent,
canActivate: [Angular2TokenService]
}
]
}];
export const a2tRoutes = RouterModule.forChild(routes);
| import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Angular2TokenService } from '../angular2-token.service';
import { A2tUiComponent } from './a2t-ui.component';
import { A2tSignInComponent } from './a2t-sign-in/a2t-sign-in.component';
import { A2tSignUpComponent } from './a2t-sign-up/a2t-sign-up.component';
import { A2tResetPasswordComponent } from './a2t-reset-password/a2t-reset-password.component';
import { A2tUpdatePasswordComponent } from './a2t-update-password/a2t-update-password.component';
const routes: Routes = [{
path: 'session',
component: A2tUiComponent,
children: [
{ path: 'sign-in', component: A2tSignInComponent },
{ path: 'sign-up', component: A2tSignUpComponent },
{ path: 'reset-password', component: A2tResetPasswordComponent },
{
path: 'update-password',
component: A2tUpdatePasswordComponent,
canActivate: [Angular2TokenService]
}
]
}];
export const a2tRoutes = RouterModule.forChild(routes);
| Declare ModuleWithProviders to be AOT ready with Angular-cli | Declare ModuleWithProviders to be AOT ready with Angular-cli
| TypeScript | mit | fastindian84/angular2-token,Tybot204/angular2-token,neroniaky/angular2-token,chadnaylor/angular2-token-ionic3,neroniaky/angular2-token,chadnaylor/angular2-token-ionic3,Tybot204/angular2-token,fastindian84/angular2-token | ---
+++
@@ -1,3 +1,4 @@
+import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Angular2TokenService } from '../angular2-token.service';
|
08f932342786e391d01316d64f94a78a9f5bfad2 | src/app/doc/doc.service.ts | src/app/doc/doc.service.ts | import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import * as MuteStructs from 'mute-structs'
@Injectable()
export class DocService {
private doc: any
constructor() {
this.doc = new MuteStructs.LogootSRopes(0)
}
setTextOperationsStream(textOperationsStream: Observable<any[]>) {
textOperationsStream.subscribe( (array: any[][]) => {
this.handleTextOperations(array)
})
}
handleTextOperations(array: any[][]) {
array.forEach( (textOperations: any[]) => {
textOperations.forEach( (textOperation: any) => {
const logootSOperation: any = textOperation.applyTo(this.doc)
console.log(logootSOperation)
})
console.log('doc: ', this.doc)
})
}
}
| import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import { NetworkService } from '../core/network/network.service'
import * as MuteStructs from 'mute-structs'
@Injectable()
export class DocService {
private doc: any
private network: NetworkService
private remoteTextOperationsStream: Observable<any[]>
constructor(network: NetworkService) {
this.doc = new MuteStructs.LogootSRopes(0)
this.network = network
this.remoteTextOperationsStream = this.network.onRemoteOperations.map( (logootSOperation: any) => {
return this.handleRemoteOperation(logootSOperation)
})
}
setTextOperationsStream(textOperationsStream: Observable<any[]>) {
textOperationsStream.subscribe( (array: any[][]) => {
this.handleTextOperations(array)
})
}
getRemoteTextOperationsStream(): Observable<any[]> {
return this.remoteTextOperationsStream
}
handleTextOperations(array: any[][]) {
array.forEach( (textOperations: any[]) => {
textOperations.forEach( (textOperation: any) => {
const logootSOperation: any = textOperation.applyTo(this.doc)
console.log(logootSOperation)
})
console.log('doc: ', this.doc)
})
}
handleRemoteOperation(logootSOperation: any) {
const textOperations: any[] = logootSOperation.execute(this.doc)
return textOperations
}
}
| Apply remote operations and stream resulting text operations | feat(doc): Apply remote operations and stream resulting text operations
Subscribe to the stream of remote LogootSplit operations, apply them to the data model and generate
a new stream of the resulting text operations
| TypeScript | agpl-3.0 | coast-team/mute,coast-team/mute,coast-team/mute,oster/mute,coast-team/mute,oster/mute,oster/mute | ---
+++
@@ -1,5 +1,7 @@
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
+
+import { NetworkService } from '../core/network/network.service'
import * as MuteStructs from 'mute-structs'
@@ -7,15 +9,25 @@
export class DocService {
private doc: any
+ private network: NetworkService
+ private remoteTextOperationsStream: Observable<any[]>
- constructor() {
+ constructor(network: NetworkService) {
this.doc = new MuteStructs.LogootSRopes(0)
+ this.network = network
+ this.remoteTextOperationsStream = this.network.onRemoteOperations.map( (logootSOperation: any) => {
+ return this.handleRemoteOperation(logootSOperation)
+ })
}
setTextOperationsStream(textOperationsStream: Observable<any[]>) {
textOperationsStream.subscribe( (array: any[][]) => {
this.handleTextOperations(array)
})
+ }
+
+ getRemoteTextOperationsStream(): Observable<any[]> {
+ return this.remoteTextOperationsStream
}
handleTextOperations(array: any[][]) {
@@ -28,4 +40,9 @@
})
}
+ handleRemoteOperation(logootSOperation: any) {
+ const textOperations: any[] = logootSOperation.execute(this.doc)
+ return textOperations
+ }
+
} |
eea137fafb52ff26ac46e5eda5ddc4938c2f5fa9 | app/subscription/subscription.component.ts | app/subscription/subscription.component.ts | import {Component} from '@angular/core';
@Component({
selector: 'subscription',
templateUrl: 'app/subscription/subscription.component.html'
})
export class SubscriptionComponent {
}
| import {Component} from '@angular/core';
import {Mentor} from './mentors_and_courses/mentor';
import {Course} from './mentors_and_courses/course';
@Component({
selector: 'subscription',
templateUrl: 'app/subscription/subscription.component.html'
})
export class SubscriptionComponent {
public mentors: Mentor[];
public courses: Course[];
}
| Add mentors and courses to SubscriptionComponent | Add mentors and courses to SubscriptionComponent
| TypeScript | mit | dhilt/a2-mkdev-sub,dhilt/a2-mkdev-sub,dhilt/a2-mkdev-sub | ---
+++
@@ -1,4 +1,6 @@
import {Component} from '@angular/core';
+import {Mentor} from './mentors_and_courses/mentor';
+import {Course} from './mentors_and_courses/course';
@Component({
selector: 'subscription',
@@ -6,4 +8,6 @@
})
export class SubscriptionComponent {
+ public mentors: Mentor[];
+ public courses: Course[];
} |
416f710573aa64ddea4200e57e9645a9245577cc | sample/19-auth/src/auth/auth.module.ts | sample/19-auth/src/auth/auth.module.ts | import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
| import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}
| Update sample to avoid deprecated secretOrPrivateKey | fix(sample): Update sample to avoid deprecated secretOrPrivateKey
| TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -9,7 +9,7 @@
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
- secretOrPrivateKey: 'secretKey',
+ secret: 'secretKey',
signOptions: {
expiresIn: 3600,
}, |
b39e81c8cde014b227f8de90c90c32c1d476c9a9 | AzureFunctions.Client/app/models/constants.ts | AzureFunctions.Client/app/models/constants.ts | export class Constants {
public static latestExtensionVersion = "~0.2";
public static latest = "latest";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
}
| export class Constants {
public static latestExtensionVersion = "~0.3";
public static latest = "latest";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
}
| Update latest extension version to "~0.3" | Update latest extension version to "~0.3"
| TypeScript | apache-2.0 | agruning/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,agruning/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,projectkudu/WebJobsPortal,projectkudu/AzureFunctions,agruning/azure-functions-ux,chunye/azure-functions-ux,chunye/azure-functions-ux,projectkudu/AzureFunctions,projectkudu/WebJobsPortal,chunye/azure-functions-ux,agruning/azure-functions-ux,chunye/azure-functions-ux,projectkudu/WebJobsPortal | ---
+++
@@ -1,5 +1,5 @@
export class Constants {
- public static latestExtensionVersion = "~0.2";
+ public static latestExtensionVersion = "~0.3";
public static latest = "latest";
public static extensionVersionAppSettingName = "FUNCTIONS_EXTENSION_VERSION";
} |
2d60094aa4ba3e0023349e97f5e90237d861f82f | src/core/abstractComponentContainer.ts | src/core/abstractComponentContainer.ts | ///<reference path="../reference.ts" />
module Plottable {
export class AbstractComponentContainer extends Component {
public _components: Component[] = [];
public _removeComponent(c: Component) {
var removeIndex = this._components.indexOf(c);
if (removeIndex >= 0) {
this._components.splice(removeIndex, 1);
this._invalidateLayout();
}
return this;
}
public _addComponent(c: Component) {
this._components.push(c);
this._invalidateLayout();
return this;
}
public getComponents(): Component[] {
return this._components;
}
public empty() {
this._components.forEach((c) => this._removeComponent(c));
}
}
}
| ///<reference path="../reference.ts" />
module Plottable {
export class AbstractComponentContainer extends Component {
public _components: Component[] = [];
public _removeComponent(c: Component) {
var removeIndex = this._components.indexOf(c);
if (removeIndex >= 0) {
this._components.splice(removeIndex, 1);
this._invalidateLayout();
}
return this;
}
public _addComponent(c: Component) {
this._components.push(c);
this._invalidateLayout();
return this;
}
public getComponents(): Component[] {
return this._components;
}
public empty() {
return this._components.length === 0;
}
public removeAll() {
this._components.forEach((c: Component) => c.remove());
}
}
}
| Change empty() to a boolean test, and add removeAll for ditching all the components | Change empty() to a boolean test, and add removeAll for ditching all the components
| TypeScript | mit | NextTuesday/plottable,onaio/plottable,gdseller/plottable,alyssaq/plottable,palantir/plottable,RobertoMalatesta/plottable,jacqt/plottable,palantir/plottable,danmane/plottable,softwords/plottable,jacqt/plottable,softwords/plottable,NextTuesday/plottable,danmane/plottable,softwords/plottable,alyssaq/plottable,palantir/plottable,onaio/plottable,jacqt/plottable,iobeam/plottable,iobeam/plottable,iobeam/plottable,alyssaq/plottable,gdseller/plottable,onaio/plottable,RobertoMalatesta/plottable,RobertoMalatesta/plottable,palantir/plottable,gdseller/plottable,danmane/plottable,NextTuesday/plottable | ---
+++
@@ -23,7 +23,11 @@
}
public empty() {
- this._components.forEach((c) => this._removeComponent(c));
+ return this._components.length === 0;
+ }
+
+ public removeAll() {
+ this._components.forEach((c: Component) => c.remove());
}
}
} |
9c700ee17e7cf360853ceaeefa557d86a3a3ab3c | app/src/components/preview/preview.service.ts | app/src/components/preview/preview.service.ts | module app.preview {
import TreeService = app.tree.TreeService;
import DataschemaService = app.core.dataschema.DataschemaService;
export class PreviewService implements Observer<PreviewUpdateEvent> {
public schema:{};
public uiSchema:{};
static $inject = ['TreeService', 'DataschemaService'];
constructor(private treeService:TreeService, private dataschemaService:DataschemaService) {
this.schema = JSON.parse(treeService.exportUISchemaAsJSON());
this.uiSchema = dataschemaService.getDataSchema();
//this.treeService.registerObserver(this);
//this.dataschemaService.registerObserver(this);
}
update(update:PreviewUpdateEvent) {
if (update.containsSchema()) {
this.schema = update.getSchema();
} else if (update.containsUiSchema()) {
this.uiSchema = update.getUiSchema();
}
}
}
angular.module('app.preview').service('PreviewService', PreviewService);
} | module app.preview {
import TreeService = app.tree.TreeService;
import DataschemaService = app.core.dataschema.DataschemaService;
export class PreviewService implements Observer<PreviewUpdateEvent> {
public schema:{};
public uiSchema:{};
static $inject = ['TreeService', 'DataschemaService'];
constructor(private treeService:TreeService, private dataschemaService:DataschemaService) {
this.schema = dataschemaService.getDataSchema();
this.uiSchema = JSON.parse(treeService.exportUISchemaAsJSON());
//this.treeService.registerObserver(this);
//this.dataschemaService.registerObserver(this);
}
update(update:PreviewUpdateEvent) {
if (update.containsSchema()) {
this.schema = update.getSchema();
} else if (update.containsUiSchema()) {
this.uiSchema = update.getUiSchema();
}
}
}
angular.module('app.preview').service('PreviewService', PreviewService);
} | Correct error in schema and uiSchema assignments in constructor | Correct error in schema and uiSchema assignments in constructor
| TypeScript | mit | FelixThieleTUM/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,eclipsesource/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,pancho111203/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,eclipsesource/JsonFormsEditor | ---
+++
@@ -9,8 +9,8 @@
static $inject = ['TreeService', 'DataschemaService'];
constructor(private treeService:TreeService, private dataschemaService:DataschemaService) {
- this.schema = JSON.parse(treeService.exportUISchemaAsJSON());
- this.uiSchema = dataschemaService.getDataSchema();
+ this.schema = dataschemaService.getDataSchema();
+ this.uiSchema = JSON.parse(treeService.exportUISchemaAsJSON());
//this.treeService.registerObserver(this);
//this.dataschemaService.registerObserver(this); |
fe493907d803a540a44aac2e75bcafddbd61fb41 | src/app/Utils/RouterProvider.ts | src/app/Utils/RouterProvider.ts | import {IRouterConfiguration, IRouter} from '../Routing';
import {ModuleProvider} from './ModuleProvider';
export class RouterProvider {
private static instance: RouterProvider = null;
public readonly ROUTING: string = '/config/Routing';
protected moduleProvider: ModuleProvider;
protected routers: IRouter[] = [];
private constructor() {
this.moduleProvider = ModuleProvider.getInstance();
}
public static getInstance() {
if (this.instance === null) {
this.instance = new RouterProvider();
}
return this.instance;
}
public getAppRouters(kernelDirectory: string): IRouter[] {
if (this.routers.length === 0) {
let AppRouting, appRouting;
try {
AppRouting = require(`${kernelDirectory}${this.ROUTING}`).default;
appRouting = new AppRouting();
} catch (e) {
console.error('Cannot find application routing.');
return [];
}
let routerConfiguration: IRouterConfiguration[] = appRouting.registerRouters();
routerConfiguration.map(config => this.addRouterFromConfiguration(config));
}
return this.routers;
}
public addRouterFromConfiguration(config: IRouterConfiguration) {
let routerDirectory = this.moduleProvider.getDirname(null, config.resources, 'Resources/config');
this.routers.push({
module: this.moduleProvider.getModule(config.resources),
router: new (require(routerDirectory).default)(),
routerDir: routerDirectory,
prefix: config.prefix || '',
});
}
}
| import {IRouterConfiguration, IRouter} from '../Routing';
import {ModuleProvider} from './ModuleProvider';
export class RouterProvider {
private static instance: RouterProvider = null;
public readonly ROUTING: string = '/config/Routing';
protected moduleProvider: ModuleProvider;
protected routers: IRouter[] = [];
private constructor() {
this.moduleProvider = ModuleProvider.getInstance();
}
public static getInstance() {
if (this.instance === null) {
this.instance = new RouterProvider();
}
return this.instance;
}
public getAppRouters(kernelDirectory: string = null): IRouter[] {
if (this.routers.length === 0 && kernelDirectory !== null) {
let AppRouting, appRouting;
try {
AppRouting = require(`${kernelDirectory}${this.ROUTING}`).default;
appRouting = new AppRouting();
} catch (e) {
console.error('Cannot find application routing.');
return [];
}
let routerConfiguration: IRouterConfiguration[] = appRouting.registerRouters();
routerConfiguration.map(config => this.addRouterFromConfiguration(config));
}
return this.routers;
}
public addRouterFromConfiguration(config: IRouterConfiguration) {
let routerDirectory = this.moduleProvider.getDirname(null, config.resources, 'Resources/config');
this.routers.push({
module: this.moduleProvider.getModule(config.resources),
router: new (require(routerDirectory).default)(),
routerDir: routerDirectory,
prefix: config.prefix || '',
});
}
}
| Return routers if kernel dir is not provide | Return routers if kernel dir is not provide
| TypeScript | mit | vincent-chapron/resonance-js,vincent-chapron/resonance-js,vincent-chapron/resonance-js | ---
+++
@@ -19,8 +19,8 @@
return this.instance;
}
- public getAppRouters(kernelDirectory: string): IRouter[] {
- if (this.routers.length === 0) {
+ public getAppRouters(kernelDirectory: string = null): IRouter[] {
+ if (this.routers.length === 0 && kernelDirectory !== null) {
let AppRouting, appRouting;
try {
AppRouting = require(`${kernelDirectory}${this.ROUTING}`).default; |
5aab66e9753d4e0ac4699aa38893a2288ca5f553 | src/interfaces/UserEvent.ts | src/interfaces/UserEvent.ts | import Message from './Message'
import MessageSendParams from './MessageSendParams'
import { VKResponse } from './APIResponses'
export default interface UserEvent {
pattern: RegExp,
listener(msg?: Message, exec?: RegExpExecArray, reply?: (text: string, params: MessageSendParams) => Promise<VKResponse>): void
} | import Message from './Message'
import MessageSendParams from './MessageSendParams'
import { VKResponse } from './APIResponses'
export default interface UserEvent {
pattern: RegExp,
listener(msg?: Message, exec?: RegExpExecArray, reply?: (text?: string, params?: MessageSendParams) => Promise<VKResponse>): void
} | Make arguments in listener optional | Make arguments in listener optional
| TypeScript | mit | vitalyavolyn/node-vk-bot,vitalyavolyn/node-vk-bot | ---
+++
@@ -4,5 +4,5 @@
export default interface UserEvent {
pattern: RegExp,
- listener(msg?: Message, exec?: RegExpExecArray, reply?: (text: string, params: MessageSendParams) => Promise<VKResponse>): void
+ listener(msg?: Message, exec?: RegExpExecArray, reply?: (text?: string, params?: MessageSendParams) => Promise<VKResponse>): void
} |
3d1026cc8d1bfe08b21cbaf7239c3757bb26c53a | knexfile.ts | knexfile.ts | require('dotenv').config();
/**
* This is the database configuration for the migrations and
* the seeders.
*/
module.exports = {
client: process.env.DB_CLIENT,
connection: process.env.DB_CONNECTION,
migrations: {
directory: process.env.DB_MIGRATION_DIR,
tableName: process.env.DB_MIGRATION_TABLE
},
seeds: {
directory: process.env.DB_SEEDS_DIR
}
};
| import * as dotenv from 'dotenv';
dotenv.config();
/**
* This is the database configuration for the migrations and
* the seeders.
*/
module.exports = {
client: process.env.DB_CLIENT,
connection: process.env.DB_CONNECTION,
migrations: {
directory: process.env.DB_MIGRATION_DIR,
tableName: process.env.DB_MIGRATION_TABLE
},
seeds: {
directory: process.env.DB_SEEDS_DIR
}
};
| Use es6 import to be tslint compiant | Use es6 import to be tslint compiant
| TypeScript | mit | w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate,w3tecch/express-typescript-boilerplate | ---
+++
@@ -1,4 +1,5 @@
-require('dotenv').config();
+import * as dotenv from 'dotenv';
+dotenv.config();
/**
* This is the database configuration for the migrations and |
191dcf06ea39bc9f139df64ed642fc82a2ec25d1 | src/utils.ts | src/utils.ts | import { Vector2 } from "three";
export const textAlign = {
center: new Vector2(0, 0),
left: new Vector2(1, 0),
topLeft: new Vector2(1, -1),
topRight: new Vector2(-1, -1),
right: new Vector2(-1, 0),
bottomLeft: new Vector2(1, 1),
bottomRight: new Vector2(-1, 1),
}
var fontHeightCache: { [id: string]: number; } = {};
export function getFontHeight (fontStyle: string) {
var result = fontHeightCache[fontStyle];
if (!result)
{
var body = document.getElementsByTagName('body')[0];
var dummy = document.createElement('div');
var dummyText = document.createTextNode('MÉq');
dummy.appendChild(dummyText);
dummy.setAttribute('style', `font:${ fontStyle };position:absolute;top:0;left:0`);
body.appendChild(dummy);
result = dummy.offsetHeight;
fontHeightCache[fontStyle] = result;
body.removeChild(dummy);
}
return result;
}
| import { Vector2 } from "three";
export const textAlign = {
center: new Vector2(0, 0),
left: new Vector2(1, 0),
top: new Vector2(0, -1),
topLeft: new Vector2(1, -1),
topRight: new Vector2(-1, -1),
right: new Vector2(-1, 0),
bottom: new Vector2(0, 1),
bottomLeft: new Vector2(1, 1),
bottomRight: new Vector2(-1, 1),
}
var fontHeightCache: { [id: string]: number; } = {};
export function getFontHeight (fontStyle: string) {
var result = fontHeightCache[fontStyle];
if (!result)
{
var body = document.getElementsByTagName('body')[0];
var dummy = document.createElement('div');
var dummyText = document.createTextNode('MÉq');
dummy.appendChild(dummyText);
dummy.setAttribute('style', `font:${ fontStyle };position:absolute;top:0;left:0`);
body.appendChild(dummy);
result = dummy.offsetHeight;
fontHeightCache[fontStyle] = result;
body.removeChild(dummy);
}
return result;
}
| Add bottom and top text aligns | Add bottom and top text aligns
Solves #35 by adding new alignments.
| TypeScript | mit | gamestdio/three-text2d,gamestdio/three-text2d,gamestdio/three-text2d | ---
+++
@@ -3,9 +3,11 @@
export const textAlign = {
center: new Vector2(0, 0),
left: new Vector2(1, 0),
+ top: new Vector2(0, -1),
topLeft: new Vector2(1, -1),
topRight: new Vector2(-1, -1),
right: new Vector2(-1, 0),
+ bottom: new Vector2(0, 1),
bottomLeft: new Vector2(1, 1),
bottomRight: new Vector2(-1, 1),
} |
8c6d489634c7cf895bafac5621069e518fe369a5 | packages/truffle-decoder/lib/allocate/general.ts | packages/truffle-decoder/lib/allocate/general.ts | import { AstDefinition, AstReferences } from "truffle-decode-utils";
function getDeclarationsForTypes(contracts: AstDefinition[], types: string[]): AstReferences {
let result: AstReferences = {};
for (let i = 0; i < contracts.length; i++) {
const contract = contracts[i];
if (contract) {
for (const node of contract.nodes) {
if (types.includes(node.nodeType)) {
result[node.id] = node;
}
}
}
}
return result;
}
export function getReferenceDeclarations(contracts: AstDefinition[]): AstReferences {
const types = [
"EnumDefinition",
"StructDefinition",
];
let contractsObject: AstReferences = Object.assign({}, ...contracts.map(
(node: AstDefinition) => ({[node.id]: node})));
return {...getDeclarationsForTypes(contracts, types), ...contractsObject};
}
export function getEventDefinitions(contracts: AstDefinition[]): AstReferences {
const types = [
"EventDefinition"
];
return getDeclarationsForTypes(contracts, types);
}
| import { AstDefinition, AstReferences } from "truffle-decode-utils";
function getDeclarationsForTypes(contracts: AstDefinition[], types: string[]): AstReferences {
let result: AstReferences = {};
for (let contract of contracts) {
if (contract) {
for (const node of contract.nodes) {
if (types.includes(node.nodeType)) {
result[node.id] = node;
}
}
}
}
return result;
}
export function getReferenceDeclarations(contracts: AstDefinition[]): AstReferences {
const types = [
"EnumDefinition",
"StructDefinition",
];
let contractsObject: AstReferences = Object.assign({}, ...contracts.map(
(node: AstDefinition) => ({[node.id]: node})));
return {...getDeclarationsForTypes(contracts, types), ...contractsObject};
}
export function getEventDefinitions(contracts: AstDefinition[]): AstReferences {
const types = [
"EventDefinition"
];
return getDeclarationsForTypes(contracts, types);
}
| Replace counter variable with for/of loop | Replace counter variable with for/of loop
| TypeScript | mit | ConsenSys/truffle | ---
+++
@@ -3,8 +3,7 @@
function getDeclarationsForTypes(contracts: AstDefinition[], types: string[]): AstReferences {
let result: AstReferences = {};
- for (let i = 0; i < contracts.length; i++) {
- const contract = contracts[i];
+ for (let contract of contracts) {
if (contract) {
for (const node of contract.nodes) {
if (types.includes(node.nodeType)) { |
bdcef01d37ad23add978a6892100c8f3a70eda42 | src/utils/formatting.ts | src/utils/formatting.ts | /**
* Trims leading and trailing whitespace and line terminators and replaces all
* characters after character 90 with an ellipsis.
* @param str
*/
export const truncate = (str: string): string => {
const trimmed = str.trim();
return trimmed.length > 90 ? trimmed.slice(0, 89).concat(' ...') : trimmed;
};
| /**
* Trims leading and trailing whitespace and line terminators and replaces all
* characters after character 90 with an ellipsis.
* @param str
*/
export const truncate = (str: string, max = 90): string => {
const trimmed = str.trim();
return trimmed.length > max ? trimmed.slice(0, 89).concat(' ...') : trimmed;
};
| Truncate now accepts an optional max string length parameter | Truncate now accepts an optional max string length parameter
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -3,7 +3,7 @@
* characters after character 90 with an ellipsis.
* @param str
*/
-export const truncate = (str: string): string => {
+export const truncate = (str: string, max = 90): string => {
const trimmed = str.trim();
- return trimmed.length > 90 ? trimmed.slice(0, 89).concat(' ...') : trimmed;
+ return trimmed.length > max ? trimmed.slice(0, 89).concat(' ...') : trimmed;
}; |
a94928b9e744b839579ba6eb9828bb89d0b36864 | front/components/images/pull/pull-image-vm.ts | front/components/images/pull/pull-image-vm.ts | import * as ko from 'knockout'
import * as fs from 'fs'
import state from '../../state'
class Run {
modalActive = ko.observable(false)
pullEnabled = ko.observable(true)
imageName = ko.observable('')
tag = ko.observable('')
hideModal = () => this.modalActive(false)
showModal = () => {
this.imageName('')
this.tag('')
this.modalActive(true)
}
pullImage = async () => {
const imageName = this.imageName()
const tag = this.tag()
if (!imageName || !tag) {
state.toast.error(`Must specify image name and tag`)
return
}
this.pullEnabled(false)
const result = await fetch(`/api/images/pull?imageName=${imageName}&tag=${tag}`, {
method: 'POST'
})
this.pullEnabled(true)
if (result.status < 400) {
state.toast.success('Successfully begun pulling image')
this.hideModal()
return
}
const msg = await result.json()
state.toast.error(`Failed to pull image: ${msg.message}`)
}
}
const viewModel = new Run()
ko.components.register('ko-pull-image', {
template: fs.readFileSync(`${__dirname}/pull-image.html`).toString(),
viewModel: {
createViewModel: () => viewModel
}
})
export default viewModel
| import * as ko from 'knockout'
import * as fs from 'fs'
import state from '../../state'
class Run {
modalActive = ko.observable(false)
pullEnabled = ko.observable(true)
imageName = ko.observable('')
tag = ko.observable('')
hideModal = () => this.modalActive(false)
showModal = () => {
this.imageName('')
this.tag('')
this.modalActive(true)
}
pullImage = async () => {
const imageName = this.imageName()
const tag = this.tag()
if (!imageName) {
state.toast.error(`Must specify image name and tag`)
return
}
this.pullEnabled(false)
const result = await fetch(`/api/images/pull?imageName=${imageName}&tag=${tag || 'latest'}`, {
method: 'POST'
})
this.pullEnabled(true)
if (result.status < 400) {
state.toast.success('Successfully begun pulling image')
this.hideModal()
return
}
const msg = await result.json()
state.toast.error(`Failed to pull image: ${msg.message}`)
}
}
const viewModel = new Run()
ko.components.register('ko-pull-image', {
template: fs.readFileSync(`${__dirname}/pull-image.html`).toString(),
viewModel: {
createViewModel: () => viewModel
}
})
export default viewModel
| Allow empty pull image tag in viewmodel | Bugfix: Allow empty pull image tag in viewmodel
| TypeScript | mit | the-concierge/concierge,the-concierge/concierge,the-concierge/concierge | ---
+++
@@ -21,13 +21,13 @@
const imageName = this.imageName()
const tag = this.tag()
- if (!imageName || !tag) {
+ if (!imageName) {
state.toast.error(`Must specify image name and tag`)
return
}
this.pullEnabled(false)
- const result = await fetch(`/api/images/pull?imageName=${imageName}&tag=${tag}`, {
+ const result = await fetch(`/api/images/pull?imageName=${imageName}&tag=${tag || 'latest'}`, {
method: 'POST'
})
this.pullEnabled(true) |
88962b9abec0eb95612d825a1b3e576e47e97348 | src/app/states/devices/device-mock.ts | src/app/states/devices/device-mock.ts | import { _ } from '@biesbjerg/ngx-translate-extract/dist/utils/utils';
import { AbstractDevice, ApparatusSensorType, DeviceType } from './abstract-device';
import { DeviceParams, DeviceParamsModel, DeviceParamType } from './device-params';
export class DeviceMock extends AbstractDevice {
readonly deviceType = DeviceType.Mock;
apparatusVersion = DeviceType.Mock;
apparatusSensorType = ApparatusSensorType.Geiger;
hitsPeriod = 1000;
sensorUuid = DeviceType.Mock;
params: DeviceParams = {
audioHits: true,
visualHits: true
};
paramsModel: DeviceParamsModel = {
audioHits: {
label: <string>_('SENSORS.PARAM.AUDIO_HITS'),
type: DeviceParamType.Boolean
},
visualHits: {
label: <string>_('SENSORS.PARAM.VISUAL_HITS'),
type: DeviceParamType.Boolean
}
};
}
| import { _ } from '@biesbjerg/ngx-translate-extract/dist/utils/utils';
import { AbstractDevice, ApparatusSensorType, DeviceType } from './abstract-device';
import { DeviceParams, DeviceParamsModel, DeviceParamType } from './device-params';
export class DeviceMock extends AbstractDevice {
readonly deviceType = DeviceType.Mock;
apparatusVersion = DeviceType.Mock;
apparatusSensorType = ApparatusSensorType.Geiger;
hitsPeriod = 1000;
sensorUUID = DeviceType.Mock;
params: DeviceParams = {
audioHits: true,
visualHits: true
};
paramsModel: DeviceParamsModel = {
audioHits: {
label: <string>_('SENSORS.PARAM.AUDIO_HITS'),
type: DeviceParamType.Boolean
},
visualHits: {
label: <string>_('SENSORS.PARAM.VISUAL_HITS'),
type: DeviceParamType.Boolean
}
};
}
| Fix device mock sensor UUID | Fix device mock sensor UUID
| TypeScript | apache-2.0 | openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile | ---
+++
@@ -7,7 +7,7 @@
apparatusVersion = DeviceType.Mock;
apparatusSensorType = ApparatusSensorType.Geiger;
hitsPeriod = 1000;
- sensorUuid = DeviceType.Mock;
+ sensorUUID = DeviceType.Mock;
params: DeviceParams = {
audioHits: true, |
922f5c6030d0f44380395ec88538864fa894b050 | src/app/settings/board-admin/board-admin.service.ts | src/app/settings/board-admin/board-admin.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { ApiResponse, Board, User } from '../../shared/index';
import { BoardData } from './board-data.model';
@Injectable()
export class BoardAdminService {
constructor(private http: Http) {
}
addBoard(board: BoardData): Observable<ApiResponse> {
let newBoard = this.convertForApi(board);
return this.http.post('api/boards', newBoard)
.map(res => {
let response: ApiResponse = res.json();
return response;
})
.catch((res, caught) => {
let response: ApiResponse = res.json();
return Observable.of(response);
});
}
private convertForApi(board: BoardData): Board {
let newBoard = new Board();
newBoard.name = board.boardName;
board.columns.forEach(column => {
newBoard.addColumn(column.name);
});
board.categories.forEach(category => {
newBoard.addCategory(category.name, category.defaultColor);
});
board.issueTrackers.forEach(tracker => {
newBoard.addIssueTracker(tracker.url, tracker.bugId);
});
board.users.forEach(user => {
newBoard.users.push(user);
});
return newBoard;
}
}
| import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { ApiResponse, Board, User } from '../../shared/index';
import { BoardData } from './board-data.model';
@Injectable()
export class BoardAdminService {
constructor(private http: Http) {
}
addBoard(board: BoardData): Observable<ApiResponse> {
let newBoard = this.convertForApi(board);
return this.http.post('api/boards', newBoard)
.map(res => {
let response: ApiResponse = res.json();
return response;
})
.catch((res, caught) => {
let response: ApiResponse = res.json();
return Observable.of(response);
});
}
private convertForApi(board: BoardData): Board {
let newBoard = new Board();
newBoard.name = board.boardName;
board.columns.forEach(column => {
newBoard.addColumn(column.name);
});
board.categories.forEach(category => {
newBoard.addCategory(category.name, category.defaultColor);
});
board.issueTrackers.forEach(tracker => {
newBoard.addIssueTracker(tracker.url, tracker.regex);
});
board.users.forEach(user => {
newBoard.users.push(user);
});
return newBoard;
}
}
| Fix issue tracker bug ID not saving | Fix issue tracker bug ID not saving
| TypeScript | mit | kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard,kiswa/TaskBoard | ---
+++
@@ -42,7 +42,7 @@
});
board.issueTrackers.forEach(tracker => {
- newBoard.addIssueTracker(tracker.url, tracker.bugId);
+ newBoard.addIssueTracker(tracker.url, tracker.regex);
});
board.users.forEach(user => { |
80f8e364e1df4005e95c9e207d38d758794e37f6 | client/src/app/login/login.component.ts | client/src/app/login/login.component.ts | import { Component, OnInit } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService } from '../core'
import { FormReactive } from '../shared'
@Component({
selector: 'my-login',
templateUrl: './login.component.html',
styleUrls: [ './login.component.scss' ]
})
export class LoginComponent extends FormReactive implements OnInit {
error: string = null
form: FormGroup
formErrors = {
'username': '',
'password': ''
}
validationMessages = {
'username': {
'required': 'Username is required.'
},
'password': {
'required': 'Password is required.'
}
}
constructor (
private authService: AuthService,
private formBuilder: FormBuilder,
private router: Router
) {
super()
}
buildForm () {
this.form = this.formBuilder.group({
username: [ '', Validators.required ],
password: [ '', Validators.required ]
})
this.form.valueChanges.subscribe(data => this.onValueChanged(data))
}
ngOnInit () {
this.buildForm()
}
login () {
this.error = null
const { username, password } = this.form.value
this.authService.login(username, password).subscribe(
result => this.router.navigate(['/videos/list']),
err => {
if (err.message === 'invalid_grant') {
this.error = 'Credentials are invalid.'
} else {
this.error = `${err.body.error_description}`
}
}
)
}
}
| import { Component, OnInit } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { Router } from '@angular/router'
import { AuthService } from '../core'
import { FormReactive } from '../shared'
@Component({
selector: 'my-login',
templateUrl: './login.component.html',
styleUrls: [ './login.component.scss' ]
})
export class LoginComponent extends FormReactive implements OnInit {
error: string = null
form: FormGroup
formErrors = {
'username': '',
'password': ''
}
validationMessages = {
'username': {
'required': 'Username is required.'
},
'password': {
'required': 'Password is required.'
}
}
constructor (
private authService: AuthService,
private formBuilder: FormBuilder,
private router: Router
) {
super()
}
buildForm () {
this.form = this.formBuilder.group({
username: [ '', Validators.required ],
password: [ '', Validators.required ]
})
this.form.valueChanges.subscribe(data => this.onValueChanged(data))
}
ngOnInit () {
this.buildForm()
}
login () {
this.error = null
const { username, password } = this.form.value
this.authService.login(username, password).subscribe(
() => this.router.navigate(['/videos/list']),
err => this.error = err.message
)
}
}
| Use server error message on login | Use server error message on login
| TypeScript | agpl-3.0 | Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube | ---
+++
@@ -55,15 +55,9 @@
const { username, password } = this.form.value
this.authService.login(username, password).subscribe(
- result => this.router.navigate(['/videos/list']),
+ () => this.router.navigate(['/videos/list']),
- err => {
- if (err.message === 'invalid_grant') {
- this.error = 'Credentials are invalid.'
- } else {
- this.error = `${err.body.error_description}`
- }
- }
+ err => this.error = err.message
)
}
} |
f7dad3aa39bf5642272c8e2ea41e41a9f35f5277 | Foundation/HtmlClient/Foundation.Test.HtmlClient/Implementations/testDefaultAngularAppInitialization.ts | Foundation/HtmlClient/Foundation.Test.HtmlClient/Implementations/testDefaultAngularAppInitialization.ts | /// <reference path="../../foundation.core.htmlclient/foundation.core.d.ts" />
module Foundation.Test.Implementations {
@Core.ObjectDependency({
name: "AppEvent"
})
export class TestDefaultAngularAppInitialization extends ViewModel.Implementations.DefaultAngularAppInitialization {
protected getBaseModuleDependencies(): Array<string> {
return ["pascalprecht.translate", "ngComponentRouter", "kendo.directives", "ngMessages", "ngMaterial", "ngAria", "ngAnimate"];
}
protected async configureAppModule(app: ng.IModule): Promise<void> {
app.config(["$locationProvider", ($locationProvider: ng.ILocationProvider) => {
$locationProvider.html5Mode(true);
}]);
await super.configureAppModule(app);
}
}
} | /// <reference path="../../foundation.core.htmlclient/foundation.core.d.ts" />
module Foundation.Test.Implementations {
@Core.ObjectDependency({
name: "AppEvent"
})
export class TestDefaultAngularAppInitialization extends ViewModel.Implementations.DefaultAngularAppInitialization {
public constructor( @Core.Inject("ClientAppProfileManager") public clientAppProfileManager: Core.ClientAppProfileManager) {
super();
}
protected getBaseModuleDependencies(): Array<string> {
let modules = ["pascalprecht.translate", "ngComponentRouter", "ngMessages", "ngMaterial", "ngAria", "ngAnimate"];
if (this.clientAppProfileManager.getClientAppProfile().screenSize == "DesktopAndTablet")
modules.push("kendo.directives");
return modules;
}
protected async configureAppModule(app: ng.IModule): Promise<void> {
app.config(["$locationProvider", ($locationProvider: ng.ILocationProvider) => {
$locationProvider.html5Mode(true);
}]);
await super.configureAppModule(app);
}
}
} | Add kendo-directives module for DesktopAndTablet devices in test project | Add kendo-directives module for DesktopAndTablet devices in test project
| TypeScript | mit | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | ---
+++
@@ -5,8 +5,15 @@
})
export class TestDefaultAngularAppInitialization extends ViewModel.Implementations.DefaultAngularAppInitialization {
+ public constructor( @Core.Inject("ClientAppProfileManager") public clientAppProfileManager: Core.ClientAppProfileManager) {
+ super();
+ }
+
protected getBaseModuleDependencies(): Array<string> {
- return ["pascalprecht.translate", "ngComponentRouter", "kendo.directives", "ngMessages", "ngMaterial", "ngAria", "ngAnimate"];
+ let modules = ["pascalprecht.translate", "ngComponentRouter", "ngMessages", "ngMaterial", "ngAria", "ngAnimate"];
+ if (this.clientAppProfileManager.getClientAppProfile().screenSize == "DesktopAndTablet")
+ modules.push("kendo.directives");
+ return modules;
}
protected async configureAppModule(app: ng.IModule): Promise<void> { |
e267646ab7fd2abc8821ba5a9e92a5d0669a6193 | applications/account/src/app/content/PrivateApp.tsx | applications/account/src/app/content/PrivateApp.tsx | import React from 'react';
import { StandardPrivateApp } from 'react-components';
import { TtagLocaleMap } from 'proton-shared/lib/interfaces/Locale';
import {
UserModel,
MailSettingsModel,
UserSettingsModel,
DomainsModel,
AddressesModel,
LabelsModel,
FiltersModel,
OrganizationModel,
MembersModel,
SubscriptionModel,
PaymentMethodsModel,
} from 'proton-shared/lib/models';
import PrivateLayout from './PrivateLayout';
const EVENT_MODELS = [
UserModel,
MailSettingsModel,
UserSettingsModel,
AddressesModel,
DomainsModel,
LabelsModel,
FiltersModel,
SubscriptionModel,
OrganizationModel,
MembersModel,
PaymentMethodsModel,
];
const PRELOAD_MODELS = [UserSettingsModel, UserModel, MailSettingsModel];
interface Props {
onLogout: () => void;
locales: TtagLocaleMap;
}
const PrivateApp = ({ onLogout, locales }: Props) => {
return (
<StandardPrivateApp
onLogout={onLogout}
locales={locales}
preloadModels={PRELOAD_MODELS}
eventModels={EVENT_MODELS}
>
<PrivateLayout />
</StandardPrivateApp>
);
};
export default PrivateApp;
| import React from 'react';
import { StandardPrivateApp } from 'react-components';
import { TtagLocaleMap } from 'proton-shared/lib/interfaces/Locale';
import {
UserModel,
MailSettingsModel,
UserSettingsModel,
DomainsModel,
AddressesModel,
LabelsModel,
FiltersModel,
OrganizationModel,
MembersModel,
SubscriptionModel,
PaymentMethodsModel,
} from 'proton-shared/lib/models';
import PrivateLayout from './PrivateLayout';
const EVENT_MODELS = [
UserModel,
MailSettingsModel,
UserSettingsModel,
AddressesModel,
DomainsModel,
LabelsModel,
FiltersModel,
SubscriptionModel,
OrganizationModel,
MembersModel,
PaymentMethodsModel,
];
const PRELOAD_MODELS = [UserSettingsModel, UserModel, MailSettingsModel];
interface Props {
onLogout: () => void;
locales: TtagLocaleMap;
}
const PrivateApp = ({ onLogout, locales }: Props) => {
return (
<StandardPrivateApp
onLogout={onLogout}
locales={locales}
preloadModels={PRELOAD_MODELS}
eventModels={EVENT_MODELS}
hasPrivateMemberKeyGeneration
hasReadableMemberKeyActivation
>
<PrivateLayout />
</StandardPrivateApp>
);
};
export default PrivateApp;
| Enable key activation and generation | Enable key activation and generation
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -45,6 +45,8 @@
locales={locales}
preloadModels={PRELOAD_MODELS}
eventModels={EVENT_MODELS}
+ hasPrivateMemberKeyGeneration
+ hasReadableMemberKeyActivation
>
<PrivateLayout />
</StandardPrivateApp> |
31a0197de240f741bbdb012ba7cae9d899250789 | webpack/sequences/set_active_sequence_by_name.ts | webpack/sequences/set_active_sequence_by_name.ts | import { selectAllSequences } from "../resources/selectors";
import { store } from "../redux/store";
import { urlFriendly, lastUrlChunk } from "../util";
import { selectSequence } from "./actions";
// import { push } from "../history";
export function setActiveSequenceByName() {
if (lastUrlChunk() == "sequences") { return; }
selectAllSequences(store.getState().resources.index).map(seq => {
const name = urlFriendly(seq.body.name);
const setSequence = () => store.dispatch(selectSequence(seq.uuid));
if (lastUrlChunk() === name) {
// push(`api/sequences/${name}`);
setTimeout(setSequence, 450);
}
});
}
| import { selectAllSequences } from "../resources/selectors";
import { store } from "../redux/store";
import { urlFriendly, lastUrlChunk } from "../util";
import { selectSequence } from "./actions";
import { push } from "../history";
export function setActiveSequenceByName() {
console.log("Hmmm");
if (lastUrlChunk() == "sequences") { return; }
selectAllSequences(store.getState().resources.index).map(seq => {
const name = urlFriendly(seq.body.name);
const setSequence = () => store.dispatch(selectSequence(seq.uuid));
if (lastUrlChunk() === name) {
push(`api/sequences/${name}`);
setTimeout(setSequence, 450);
}
});
}
| Change URL when links get clicked in sequence editor | Change URL when links get clicked in sequence editor
| TypeScript | mit | RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App | ---
+++
@@ -2,15 +2,16 @@
import { store } from "../redux/store";
import { urlFriendly, lastUrlChunk } from "../util";
import { selectSequence } from "./actions";
-// import { push } from "../history";
+import { push } from "../history";
export function setActiveSequenceByName() {
+ console.log("Hmmm");
if (lastUrlChunk() == "sequences") { return; }
selectAllSequences(store.getState().resources.index).map(seq => {
const name = urlFriendly(seq.body.name);
const setSequence = () => store.dispatch(selectSequence(seq.uuid));
if (lastUrlChunk() === name) {
- // push(`api/sequences/${name}`);
+ push(`api/sequences/${name}`);
setTimeout(setSequence, 450);
}
}); |
44063a39a648f6131aae9fbb66b063474d091c18 | async/test/es6-generators.ts | async/test/es6-generators.ts | function* funcCollection<T>(): IterableIterator<T> { }
function funcMapIterator<T, E>(value: T, callback: AsyncResultCallback<T, E>) { }
function funcMapComplete<T, E>(error: E, results: T[]) { }
async.map(funcCollection(), funcMapIterator, funcMapComplete)
async.mapSeries(funcCollection(), funcMapIterator, funcMapComplete)
async.mapLimit(funcCollection(), 2, funcMapIterator, funcMapComplete)
| function* funcCollection<T>(): IterableIterator<T> { }
function funcMapIterator<T, E>(value: T, callback: AsyncResultCallback<T, E>) { }
function funcMapComplete<T, E>(error: E, results: T[]) { }
function funcCbErrBoolean<T>(v: T, cb: (err: Error, res: boolean) => void) { }
async.map(funcCollection(), funcMapIterator, funcMapComplete)
async.mapSeries(funcCollection(), funcMapIterator, funcMapComplete)
async.mapLimit(funcCollection(), 2, funcMapIterator, funcMapComplete)
async.filter(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.filterSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.filterLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { })
async.select(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.selectSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.selectLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { })
async.reject(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.rejectSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
async.rejectLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { })
| Create tests for filters, selects, and rejects | Create tests for filters, selects, and rejects
* filter
* filterSeries
* filterLimit
* select
* selectSeries
* selectLimit
* reject
* rejectSeries
* rejectLimit | TypeScript | mit | mcrawshaw/DefinitelyTyped,benliddicott/DefinitelyTyped,ashwinr/DefinitelyTyped,abbasmhd/DefinitelyTyped,johan-gorter/DefinitelyTyped,zuzusik/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,QuatroCode/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,zuzusik/DefinitelyTyped,isman-usoh/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,smrq/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,benishouga/DefinitelyTyped,johan-gorter/DefinitelyTyped,borisyankov/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,one-pieces/DefinitelyTyped,isman-usoh/DefinitelyTyped,magny/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,amir-arad/DefinitelyTyped,markogresak/DefinitelyTyped,aciccarello/DefinitelyTyped,mcrawshaw/DefinitelyTyped,smrq/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,rolandzwaga/DefinitelyTyped,chrootsu/DefinitelyTyped,zuzusik/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,dsebastien/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,minodisk/DefinitelyTyped,YousefED/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,nycdotnet/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,ashwinr/DefinitelyTyped,YousefED/DefinitelyTyped,arusakov/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,nycdotnet/DefinitelyTyped,benishouga/DefinitelyTyped,minodisk/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jimthedev/DefinitelyTyped,AgentME/DefinitelyTyped,mcliment/DefinitelyTyped,abbasmhd/DefinitelyTyped,alexdresko/DefinitelyTyped,arusakov/DefinitelyTyped,chrootsu/DefinitelyTyped,arusakov/DefinitelyTyped,jimthedev/DefinitelyTyped | ---
+++
@@ -3,6 +3,19 @@
function funcMapIterator<T, E>(value: T, callback: AsyncResultCallback<T, E>) { }
function funcMapComplete<T, E>(error: E, results: T[]) { }
+function funcCbErrBoolean<T>(v: T, cb: (err: Error, res: boolean) => void) { }
+
async.map(funcCollection(), funcMapIterator, funcMapComplete)
async.mapSeries(funcCollection(), funcMapIterator, funcMapComplete)
async.mapLimit(funcCollection(), 2, funcMapIterator, funcMapComplete)
+
+async.filter(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.filterSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.filterLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.select(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.selectSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.selectLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { })
+
+async.reject(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.rejectSeries(funcCollection(), funcCbErrBoolean, function (err: Error, results: any[]) { })
+async.rejectLimit(funcCollection(), 2, funcCbErrBoolean, function (err: Error, results: any[]) { }) |
a73a959de35c381b5961fca253688d2b5a60eeae | src/utils/prefixes.ts | src/utils/prefixes.ts | import { camelCase } from './camel-case';
const cache = {};
const testStyle = typeof document !== 'undefined' ? document.createElement('div').style : undefined;
// Get Prefix
// http://davidwalsh.name/vendor-prefix
const prefix = function() {
const styles = typeof window !== 'undefined' ? window.getComputedStyle(document.documentElement, '') : undefined;
const pre = typeof styles !== 'undefined'
? (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/))[1] : undefined;
const dom = typeof pre !== 'undefined' ? ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1] : undefined;
return dom ? {
dom,
lowercase: pre,
css: `-${pre}-`,
js: pre[0].toUpperCase() + pre.substr(1)
} : undefined;
}();
export function getVendorPrefixedName(property: string) {
const name = camelCase(property);
if (!cache[name]) {
if (prefix !== undefined && testStyle[prefix.css + property] !== undefined) {
cache[name] = prefix.css + property;
} else if (testStyle[property] !== undefined) {
cache[name] = property;
}
}
return cache[name];
}
| import { camelCase } from './camel-case';
const cache = {};
const testStyle = typeof document !== 'undefined' ? document.createElement('div').style : undefined;
// Get Prefix
// http://davidwalsh.name/vendor-prefix
const prefix = function() {
const styles = typeof window !== 'undefined' ? window.getComputedStyle(document.documentElement, '') : undefined;
const match = typeof styles !== 'undefined' ?
Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) : null;
const pre = match !== null ? match[1] : undefined;
const dom = typeof pre !== 'undefined' ? ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1] : undefined;
return dom ? {
dom,
lowercase: pre,
css: `-${pre}-`,
js: pre[0].toUpperCase() + pre.substr(1)
} : undefined;
}();
export function getVendorPrefixedName(property: string) {
const name = camelCase(property);
if (!cache[name]) {
if (prefix !== undefined && testStyle[prefix.css + property] !== undefined) {
cache[name] = prefix.css + property;
} else if (testStyle[property] !== undefined) {
cache[name] = property;
}
}
return cache[name];
}
| Fix prefixer function so that it doesn't fail if it cannot find vendor prefix in styles | Fix prefixer function so that it doesn't fail if it cannot find vendor prefix in styles
| TypeScript | mit | achimha/ngx-datatable,swimlane/ngx-datatable,achimha/ngx-datatable,achimha/ngx-datatable,swimlane/angular2-data-table,swimlane/angular2-data-table,swimlane/angular2-data-table,swimlane/ngx-datatable,swimlane/ngx-datatable | ---
+++
@@ -7,8 +7,9 @@
// http://davidwalsh.name/vendor-prefix
const prefix = function() {
const styles = typeof window !== 'undefined' ? window.getComputedStyle(document.documentElement, '') : undefined;
- const pre = typeof styles !== 'undefined'
- ? (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/))[1] : undefined;
+ const match = typeof styles !== 'undefined' ?
+ Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) : null;
+ const pre = match !== null ? match[1] : undefined;
const dom = typeof pre !== 'undefined' ? ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1] : undefined;
return dom ? { |
7822c56d8d623e03682b46a836e68e36d07053ee | src/utils/promises.ts | src/utils/promises.ts | export async function waitFor<T>(action: () => T, checkEveryMilliseconds: number, tryForMilliseconds: number, token?: { isCancellationRequested: boolean }): Promise<T | undefined> {
let timeRemaining = tryForMilliseconds;
while (timeRemaining > 0 && !(token && token.isCancellationRequested)) {
const res = action();
if (res)
return res;
await new Promise((resolve) => setTimeout(resolve, checkEveryMilliseconds));
timeRemaining -= 20;
}
}
| export async function waitFor<T>(action: () => T, checkEveryMilliseconds: number, tryForMilliseconds: number, token?: { isCancellationRequested: boolean }): Promise<T | undefined> {
let timeRemaining = tryForMilliseconds;
while (timeRemaining > 0 && !(token && token.isCancellationRequested)) {
const res = action();
if (res)
return res;
await new Promise((resolve) => setTimeout(resolve, checkEveryMilliseconds));
timeRemaining -= checkEveryMilliseconds;
}
}
| Fix bug in waitFor not waiting long enough | Fix bug in waitFor not waiting long enough
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -5,6 +5,6 @@
if (res)
return res;
await new Promise((resolve) => setTimeout(resolve, checkEveryMilliseconds));
- timeRemaining -= 20;
+ timeRemaining -= checkEveryMilliseconds;
}
} |
e0e6771ea123c37d18f405bc17f8f11408cfb59c | polyfill/promise.ts | polyfill/promise.ts | //@ts-ignore
import Promise from "promise-polyfill";
let globalWindow = window as any;
if (globalWindow.Promise === undefined)
{
globalWindow.Promise = Promise;
}
| import "promise-polyfill/src/polyfill";
| Remove redundant global window assignment as the polyfill does it as well | Remove redundant global window assignment as the polyfill does it as well
| TypeScript | bsd-3-clause | Becklyn/mojave,Becklyn/mojave,Becklyn/mojave | ---
+++
@@ -1,9 +1 @@
-//@ts-ignore
-import Promise from "promise-polyfill";
-
-let globalWindow = window as any;
-
-if (globalWindow.Promise === undefined)
-{
- globalWindow.Promise = Promise;
-}
+import "promise-polyfill/src/polyfill"; |
7a170d51587e478afcd221af25e9dfdcd4900130 | typescript/tssearch/src/searchfile.ts | typescript/tssearch/src/searchfile.ts | /*
* searchfile.js
*
* encapsulates a file to be searched
*/
"use strict";
import {FileType} from './filetype';
var path = require('path');
export class SearchFile {
containerSeparator: string = '!';
containers: string[] = [];
pathname: string;
filename: string;
filetype: FileType;
constructor(pathname: string, filename: string, filetype: FileType) {
this.pathname = pathname;
this.filename = filename;
this.filetype = filetype;
}
public toString(): string {
let s: string = '';
if (this.containers.length > 0) {
s = this.containers.join(this.containerSeparator) + this.containerSeparator;
}
s += path.join(this.pathname, this.filename);
return s;
}
}
| /*
* searchfile.js
*
* encapsulates a file to be searched
*/
"use strict";
import {FileType} from './filetype';
var path = require('path');
export class SearchFile {
containerSeparator: string = '!';
containers: string[] = [];
pathname: string;
filename: string;
filetype: FileType;
constructor(pathname: string, filename: string, filetype: FileType) {
this.pathname = pathname;
this.filename = filename;
this.filetype = filetype;
}
public relativePath(): string {
if (this.pathname === '.' || this.pathname === './') return './' + this.filename;
return path.join(this.pathname, this.filename);
};
public toString(): string {
let s: string = '';
if (this.containers.length > 0) {
s = this.containers.join(this.containerSeparator) + this.containerSeparator;
}
s += path.join(this.pathname, this.filename);
return s;
}
}
| Add relativePath method to SearchFile | Add relativePath method to SearchFile
| TypeScript | mit | clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch | ---
+++
@@ -23,6 +23,11 @@
this.filetype = filetype;
}
+ public relativePath(): string {
+ if (this.pathname === '.' || this.pathname === './') return './' + this.filename;
+ return path.join(this.pathname, this.filename);
+ };
+
public toString(): string {
let s: string = '';
if (this.containers.length > 0) { |
d636ce25841d4f8e6cbf6ff025dc0a37fc3a151a | console/src/app/core/models/chart/mongoose-chart.interface.ts | console/src/app/core/models/chart/mongoose-chart.interface.ts | import { MongooseChartDataset } from "./mongoose-chart-dataset.model";
import { MongooseChartOptions } from "./mongoose-chart-options";
export interface MongooseChart {
chartOptions: MongooseChartOptions;
chartLabels: string[];
chartType: string;
chartLegend: boolean;
chartData: MongooseChartDataset;
} | import { MongooseChartDataset } from "./mongoose-chart-dataset.model";
import { MongooseChartOptions } from "./mongoose-chart-options";
import { MongooseChartDao } from "./mongoose-chart-dao.mode";
export interface MongooseChart {
chartOptions: MongooseChartOptions;
chartLabels: string[];
chartType: string;
chartLegend: boolean;
chartData: MongooseChartDataset;
mongooseChartDao: MongooseChartDao;
updateChart();
} | Add necessary field & method to mongoose chart inteface. | Add necessary field & method to mongoose chart inteface.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -1,10 +1,14 @@
import { MongooseChartDataset } from "./mongoose-chart-dataset.model";
import { MongooseChartOptions } from "./mongoose-chart-options";
+import { MongooseChartDao } from "./mongoose-chart-dao.mode";
-export interface MongooseChart {
-chartOptions: MongooseChartOptions;
-chartLabels: string[];
-chartType: string;
-chartLegend: boolean;
-chartData: MongooseChartDataset;
+export interface MongooseChart {
+ chartOptions: MongooseChartOptions;
+ chartLabels: string[];
+ chartType: string;
+ chartLegend: boolean;
+ chartData: MongooseChartDataset;
+
+ mongooseChartDao: MongooseChartDao;
+ updateChart();
} |
38e771b1c74b0bc426022e84bd867c5fc483d388 | client/src/app/app.module.ts | client/src/app/app.module.ts | import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HttpModule, JsonpModule} from '@angular/http';
import {AppComponent} from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {HomeComponent} from './home/home.component';
import {UserListComponent} from './users/user-list.component';
import {UserListService} from './users/user-list.service';
import {Routing} from './app.routes';
import {FormsModule} from '@angular/forms';
import {APP_BASE_HREF} from "@angular/common";
@NgModule({
imports: [
BrowserModule,
HttpModule,
JsonpModule,
Routing,
FormsModule,
],
declarations: [
AppComponent,
HomeComponent,
NavbarComponent,
UserListComponent
],
providers: [
UserListService,
{provide: APP_BASE_HREF, useValue: '/'}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
| import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HttpModule, JsonpModule} from '@angular/http';
import {AppComponent} from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {HomeComponent} from './home/home.component';
import {UserComponent} from "./users/user.component";
import {UserListComponent} from './users/user-list.component';
import {UserListService} from './users/user-list.service';
import {Routing} from './app.routes';
import {FormsModule} from '@angular/forms';
import {APP_BASE_HREF} from "@angular/common";
@NgModule({
imports: [
BrowserModule,
HttpModule,
JsonpModule,
Routing,
FormsModule,
],
declarations: [
AppComponent,
HomeComponent,
NavbarComponent,
UserListComponent,
UserComponent
],
providers: [
UserListService,
{provide: APP_BASE_HREF, useValue: '/'}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
| Update missing import from UserComponent | Update missing import from UserComponent
| TypeScript | mit | UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams | ---
+++
@@ -1,10 +1,10 @@
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HttpModule, JsonpModule} from '@angular/http';
-
import {AppComponent} from './app.component';
import {NavbarComponent} from './navbar/navbar.component';
import {HomeComponent} from './home/home.component';
+import {UserComponent} from "./users/user.component";
import {UserListComponent} from './users/user-list.component';
import {UserListService} from './users/user-list.service';
import {Routing} from './app.routes';
@@ -24,7 +24,8 @@
AppComponent,
HomeComponent,
NavbarComponent,
- UserListComponent
+ UserListComponent,
+ UserComponent
],
providers: [
UserListService, |
a56896e7ba7bd3a1f02d11ab7a18c7afb246edac | integration/microservices/src/rmq/rmq-broadcast.controller.ts | integration/microservices/src/rmq/rmq-broadcast.controller.ts | import { Controller, Get } from '@nestjs/common';
import {
ClientProxy,
ClientProxyFactory,
MessagePattern,
Transport,
} from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { scan, take } from 'rxjs/operators';
@Controller()
export class RMQBroadcastController {
client: ClientProxy;
constructor() {
this.client = ClientProxyFactory.create({
transport: Transport.RMQ,
options: {
urls: [`amqp://localhost:5672`],
queue: 'test_broadcast',
queueOptions: { durable: false },
},
});
}
@Get('broadcast')
multicats() {
return this.client
.send<number>({ cmd: 'broadcast' }, {})
.pipe(scan((a, b) => a + b), take(2));
}
@MessagePattern({ cmd: 'broadcast' })
replyBroadcast(): Observable<number> {
return new Observable(observer => observer.next(1));
}
}
| import { Controller, Get } from '@nestjs/common';
import {
ClientProxy,
ClientProxyFactory,
MessagePattern,
Transport,
} from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { scan, take } from 'rxjs/operators';
@Controller()
export class RMQBroadcastController {
client: ClientProxy;
constructor() {
this.client = ClientProxyFactory.create({
transport: Transport.RMQ,
options: {
urls: [`amqp://localhost:5672`],
queue: 'test_broadcast',
queueOptions: { durable: false },
socketOptions: { noDelay: true },
},
});
}
@Get('broadcast')
multicats() {
return this.client
.send<number>({ cmd: 'broadcast' }, {})
.pipe(scan((a, b) => a + b), take(2));
}
@MessagePattern({ cmd: 'broadcast' })
replyBroadcast(): Observable<number> {
return new Observable(observer => observer.next(1));
}
}
| Add socketOptions to RMQ broadcast test | Add socketOptions to RMQ broadcast test | TypeScript | mit | kamilmysliwiec/nest,kamilmysliwiec/nest | ---
+++
@@ -19,6 +19,7 @@
urls: [`amqp://localhost:5672`],
queue: 'test_broadcast',
queueOptions: { durable: false },
+ socketOptions: { noDelay: true },
},
});
} |
2d4590a5b59dde8ed9881f569ada58de13bd82ab | src/app/app.ts | src/app/app.ts | /*
* Angular 2 decorators and services
*/
import {Component, OnInit} from 'angular2/core';
import {NgForm, FORM_DIRECTIVES} from 'angular2/common';
import {BudgetItem} from './budget/budget-item';
import {BudgetService} from './services/budget.service';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'app',
pipes: [ ],
providers: [BudgetService],
directives: [FORM_DIRECTIVES],
templateUrl: '/assets/templates/app.html',
styles: [ ]
})
export class App implements OnInit {
public budgetItems: BudgetItem[];
public model: BudgetItem = new BudgetItem(0, "");
public total: number;
constructor(private _budgetService: BudgetService) {
}
ngOnInit() {
this.getItems();
}
getItems() {
this.budgetItems = this._budgetService.getItems();
this.countTotal();
}
addItem(model: BudgetItem) {
console.log("you just submitted:");
console.log(model);
this._budgetService.addItem(model);
this.getItems();
}
sumUp() {
this._budgetService.sumUp();
this.getItems();
}
fillWithTestData() {
this._budgetService.fillWithTestData();
this.getItems();
}
countTotal() {
this.total = this.budgetItems.map(_ => _.sum).reduce((a, b) => a + b);
}
}
| /*
* Angular 2 decorators and services
*/
import {Component, OnInit} from 'angular2/core';
import {NgForm, FORM_DIRECTIVES} from 'angular2/common';
import {BudgetItem} from './budget/budget-item';
import {BudgetService} from './services/budget.service';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'app',
pipes: [ ],
providers: [BudgetService],
directives: [FORM_DIRECTIVES],
templateUrl: '/assets/templates/app.html',
styles: [ ]
})
export class App implements OnInit {
public budgetItems: BudgetItem[];
public model: BudgetItem = new BudgetItem(0, "");
public total: number;
constructor(private _budgetService: BudgetService) {
}
ngOnInit() {
this.getItems();
}
getItems() {
this.budgetItems = this._budgetService.getItems();
this.countTotal();
}
addItem(model: BudgetItem) {
console.log("you just submitted:");
console.log(model);
this._budgetService.addItem(model);
this.getItems();
}
sumUp() {
this._budgetService.sumUp();
this.getItems();
}
fillWithTestData() {
this._budgetService.fillWithTestData();
this.getItems();
}
countTotal() {
this.total = this.budgetItems.map(_ => _.sum).reduce((a, b) => a + b, 0);
}
}
| Handle empty array case for sumUp() | Handle empty array case for sumUp()
| TypeScript | mit | bluebirrrrd/ng2-budget,bluebirrrrd/ng2-budget,bluebirrrrd/ng2-budget | ---
+++
@@ -54,6 +54,6 @@
}
countTotal() {
- this.total = this.budgetItems.map(_ => _.sum).reduce((a, b) => a + b);
+ this.total = this.budgetItems.map(_ => _.sum).reduce((a, b) => a + b, 0);
}
} |
6540874092e259230083644101cb4e37380ce476 | src/contract/index.ts | src/contract/index.ts | // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
import * as process from "process";
import * as util from "util";
const failCode = -227;
const failMsg: string = "A failure has occurred";
const assertMsg: string = "An assertion failure has occurred";
export function fail(): never {
return failf(failMsg);
}
export function failf(msg: string, ...args: any[]): never {
let msgf: string = util.format(msg, ...args);
console.error(msgf);
console.error(new Error().stack);
process.exit(failCode);
throw new Error(msgf); // this will never be reached, due to the os.exit, but makes TSC happy.
}
export function assert(b: boolean): void {
if (!b) {
failf(assertMsg);
}
}
export function assertf(b: boolean, msg: string, ...args: any[]): void {
if (!b) {
failf(assertMsg, ...args);
}
}
| // Copyright 2016 Joe Duffy. All rights reserved.
"use strict";
import * as process from "process";
import * as util from "util";
const failCode = -227;
const failMsg: string = "A failure has occurred";
const assertMsg: string = "An assertion failure has occurred";
export function fail(): never {
return failfast(failMsg);
}
export function failf(msg: string, ...args: any[]): never {
return failfast(`${failMsg}: ${util.format(msg, ...args)}`);
}
export function assert(b: boolean): void {
if (!b) {
return failfast(assertMsg);
}
}
export function assertf(b: boolean, msg: string, ...args: any[]): void {
if (!b) {
return failfast(`${assertMsg}: ${util.format(msg, ...args)}`);
}
}
function failfast(msg: string): never {
console.error(msg);
console.error(new Error().stack);
process.exit(failCode);
while (true) {} // this will never be reached, thanks to process.exit, but makes TSC happy.
}
| Prepend failure/assert messages to custom text | Prepend failure/assert messages to custom text
| TypeScript | mit | joeduffy/nodets | ---
+++
@@ -10,26 +10,29 @@
const assertMsg: string = "An assertion failure has occurred";
export function fail(): never {
- return failf(failMsg);
+ return failfast(failMsg);
}
export function failf(msg: string, ...args: any[]): never {
- let msgf: string = util.format(msg, ...args);
- console.error(msgf);
- console.error(new Error().stack);
- process.exit(failCode);
- throw new Error(msgf); // this will never be reached, due to the os.exit, but makes TSC happy.
+ return failfast(`${failMsg}: ${util.format(msg, ...args)}`);
}
export function assert(b: boolean): void {
if (!b) {
- failf(assertMsg);
+ return failfast(assertMsg);
}
}
export function assertf(b: boolean, msg: string, ...args: any[]): void {
if (!b) {
- failf(assertMsg, ...args);
+ return failfast(`${assertMsg}: ${util.format(msg, ...args)}`);
}
}
+function failfast(msg: string): never {
+ console.error(msg);
+ console.error(new Error().stack);
+ process.exit(failCode);
+ while (true) {} // this will never be reached, thanks to process.exit, but makes TSC happy.
+}
+ |
c0281dce125e70a78b13a5d26dcadb00733fae03 | clients/webpage/src/bonde-webpage/plugins/Plip/components/PdfButton.tsx | clients/webpage/src/bonde-webpage/plugins/Plip/components/PdfButton.tsx | import React from 'react';
import EyeIcon from '../icons/EyeIcon';
interface PdfButtonProps {
dataPdf: string
}
const PdfButton = (props: PdfButtonProps) => {
const handleClick = (event:any) => {
event?.preventDefault()
window.open(encodeURI(props.dataPdf));
};
return (
<>
<button
onClick={handleClick}>
<EyeIcon />
Ver ficha de assinatura
</button>
</>
);
};
export default PdfButton;
| import React from 'react';
import EyeIcon from '../icons/EyeIcon';
interface PdfButtonProps {
dataPdf: string
}
const PdfButton = (props: PdfButtonProps) => {
const handleClick = (event:any) => {
event?.preventDefault()
window.open(encodeURI(`data:application/pdf;filename=generated.pdf;base64,${props.dataPdf}`));
};
return (
<>
<button
onClick={handleClick}>
<EyeIcon />
Ver ficha de assinatura
</button>
</>
);
};
export default PdfButton;
| Add header when open plip pdf | chore(webpage): Add header when open plip pdf
| TypeScript | agpl-3.0 | nossas/bonde-client,nossas/bonde-client,nossas/bonde-client | ---
+++
@@ -8,7 +8,7 @@
const PdfButton = (props: PdfButtonProps) => {
const handleClick = (event:any) => {
event?.preventDefault()
- window.open(encodeURI(props.dataPdf));
+ window.open(encodeURI(`data:application/pdf;filename=generated.pdf;base64,${props.dataPdf}`));
};
return ( |
293074ae7920040ede7e01d0aec4dabbeeb864ff | server/lib/uploadx.ts | server/lib/uploadx.ts | import express from 'express'
import { getResumableUploadPath } from '@server/helpers/upload'
import { Uploadx } from '@uploadx/core'
const uploadx = new Uploadx({ directory: getResumableUploadPath() })
uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
export {
uploadx
}
| import express from 'express'
import { getResumableUploadPath } from '@server/helpers/upload'
import { Uploadx } from '@uploadx/core'
const uploadx = new Uploadx({
directory: getResumableUploadPath(),
// Could be big with thumbnails/previews
maxMetadataSize: '10MB'
})
uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
export {
uploadx
}
| Fix video upload with big preview | Fix video upload with big preview
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube | ---
+++
@@ -2,7 +2,11 @@
import { getResumableUploadPath } from '@server/helpers/upload'
import { Uploadx } from '@uploadx/core'
-const uploadx = new Uploadx({ directory: getResumableUploadPath() })
+const uploadx = new Uploadx({
+ directory: getResumableUploadPath(),
+ // Could be big with thumbnails/previews
+ maxMetadataSize: '10MB'
+})
uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
export { |
b68927a5338c39f4c6a91e69cfe7f812ea149e00 | lib/vocabularies/validation/limitLength.ts | lib/vocabularies/validation/limitLength.ts | import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type KeywordCxt from "../../compile/context"
import {_, str, operators} from "../../compile/codegen"
import ucs2length from "../../compile/ucs2length"
const error: KeywordErrorDefinition = {
message({keyword, schemaCode}) {
const comp = keyword === "maxLength" ? "more" : "fewer"
return str`should NOT have ${comp} than ${schemaCode} items`
},
params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}
const def: CodeKeywordDefinition = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt: KeywordCxt) {
const {keyword, data, schemaCode, it} = cxt
const op = keyword === "maxLength" ? operators.GT : operators.LT
let len
if (it.opts.unicode === false) {
len = _`${data}.length`
} else {
const u2l = cxt.gen.scopeValue("func", {
ref: ucs2length,
code: _`require("ajv/dist/compile/ucs2length").default`,
})
len = _`${u2l}(${data})`
}
cxt.fail$data(_`${len} ${op} ${schemaCode}`)
},
}
export default def
| import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type KeywordCxt from "../../compile/context"
import {_, str, operators} from "../../compile/codegen"
import ucs2length from "../../compile/ucs2length"
const error: KeywordErrorDefinition = {
message({keyword, schemaCode}) {
const comp = keyword === "maxLength" ? "more" : "fewer"
return str`should NOT have ${comp} than ${schemaCode} characters`
},
params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
}
const def: CodeKeywordDefinition = {
keyword: ["maxLength", "minLength"],
type: "string",
schemaType: "number",
$data: true,
error,
code(cxt: KeywordCxt) {
const {keyword, data, schemaCode, it} = cxt
const op = keyword === "maxLength" ? operators.GT : operators.LT
let len
if (it.opts.unicode === false) {
len = _`${data}.length`
} else {
const u2l = cxt.gen.scopeValue("func", {
ref: ucs2length,
code: _`require("ajv/dist/compile/ucs2length").default`,
})
len = _`${u2l}(${data})`
}
cxt.fail$data(_`${len} ${op} ${schemaCode}`)
},
}
export default def
| Add user-friendly message for maxLength validation | Add user-friendly message for maxLength validation
"should not have fewer than 5 items" feels weird for a string of characters. I think we should revert back to v6 terminology and say "characters" instead of "items". | TypeScript | mit | epoberezkin/ajv,epoberezkin/ajv,epoberezkin/ajv | ---
+++
@@ -6,7 +6,7 @@
const error: KeywordErrorDefinition = {
message({keyword, schemaCode}) {
const comp = keyword === "maxLength" ? "more" : "fewer"
- return str`should NOT have ${comp} than ${schemaCode} items`
+ return str`should NOT have ${comp} than ${schemaCode} characters`
},
params: ({schemaCode}) => _`{limit: ${schemaCode}}`,
} |
5a44fa3ec9e275912516787b0a1ddd892b73eeea | src/utils/data/sorting.ts | src/utils/data/sorting.ts | export function sortByField (array: Array<any>, field: string){
array.sort((e1, e2) => {
var a = e1[field];
var b = e2[field];
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
} | export function sortByField (array: Array<any>, field: string) : void {
array.sort((e1, e2) => {
var a = e1[field];
var b = e2[field];
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
} | Add void return type to sortByField | Add void return type to sortByField
| TypeScript | apache-2.0 | proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic | ---
+++
@@ -1,4 +1,4 @@
-export function sortByField (array: Array<any>, field: string){
+export function sortByField (array: Array<any>, field: string) : void {
array.sort((e1, e2) => {
var a = e1[field];
var b = e2[field]; |
3e84010c4b4fa3016ffaf5afab529aa50fe9575f | src/resourceloader.ts | src/resourceloader.ts | /**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath + "/" + resourceName;
}
| /**
* Map a resource name to a URL.
*
* This particular mapping function works in a nodejs context.
*
* @param resourceName relative path to the resource from the main src directory.
* @return a URL which points to the resource.
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
return "file://" + mainPath.replace(/\\/g, "/") + "/" + resourceName;
}
| Fix for CSS and resource loading on Windows. | Fix for CSS and resource loading on Windows.
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -8,5 +8,5 @@
*/
export function toUrl(resourceName: string): string {
let mainPath = __dirname;
- return "file://" + mainPath + "/" + resourceName;
+ return "file://" + mainPath.replace(/\\/g, "/") + "/" + resourceName;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.