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 |
|---|---|---|---|---|---|---|---|---|---|---|
178ecfb7d20b175dfc45bc43b7cc50fc37fdef4c | AngularJSWithTS/UseTypesEffectivelyInTS/Classes/Inheritance/ComicBookCharacterDefault.ts | AngularJSWithTS/UseTypesEffectivelyInTS/Classes/Inheritance/ComicBookCharacterDefault.ts | // ComicBookCharacterDefault.ts
"use strict";
class ComicBookCharacterDefault {
constructor(
public alias: string,
public health: number,
public strength: number,
private secretIdentity: string
) {}
}
export { ComicBookCharacterDefault };
| // ComicBookCharacterDefault.ts
"use strict";
class ComicBookCharacterDefault {
constructor(
public alias: string,
public health: number,
public strength: number,
protected secretIdentity: string
) {}
}
export { ComicBookCharacterDefault };
| Change access level for secretIdentity | Change access level for secretIdentity
| TypeScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -7,7 +7,7 @@
public alias: string,
public health: number,
public strength: number,
- private secretIdentity: string
+ protected secretIdentity: string
) {}
}
|
1c9afe37394c0f3822d5f36dc7b2dbc16dd98725 | bokehjs/src/coffee/api/typings/types.d.ts | bokehjs/src/coffee/api/typings/types.d.ts | declare namespace Bokeh {
export type Int = number;
export type Percent = number;
export type Color = NamedColor |
[Int, Int, Int] | // RGB (r, g, b)
[Int, Int, Int, Percent]; // RGBA(r, g, b, a)
export type FontSize = string;
export type KeyVal = {[key: string]: any};
}
| declare namespace Bokeh {
export type Int = number;
export type Percent = number;
export type Color = NamedColor |
String |
[Int, Int, Int] | // RGB (r, g, b)
[Int, Int, Int, Percent]; // RGBA(r, g, b, a)
export type FontSize = string;
export type KeyVal = {[key: string]: any};
}
| Allow Color to be a string (at least for now) | Allow Color to be a string (at least for now)
This makes NamedColor pretty much useless.
| TypeScript | bsd-3-clause | ericmjl/bokeh,stonebig/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,bokeh/bokeh,philippjfr/bokeh,clairetang6/bokeh,ericmjl/bokeh,DuCorey/bokeh,azjps/bokeh,justacec/bokeh,rs2/bokeh,KasperPRasmussen/bokeh,dennisobrien/bokeh,jakirkham/bokeh,aavanian/bokeh,aavanian/bokeh,rs2/bokeh,ptitjano/bokeh,DuCorey/bokeh,clairetang6/bokeh,justacec/bokeh,ericmjl/bokeh,clairetang6/bokeh,mindriot101/bokeh,dennisobrien/bokeh,schoolie/bokeh,percyfal/bokeh,quasiben/bokeh,ptitjano/bokeh,ptitjano/bokeh,timsnyder/bokeh,jakirkham/bokeh,bokeh/bokeh,ptitjano/bokeh,timsnyder/bokeh,azjps/bokeh,bokeh/bokeh,quasiben/bokeh,dennisobrien/bokeh,aavanian/bokeh,mindriot101/bokeh,ericmjl/bokeh,philippjfr/bokeh,ericmjl/bokeh,KasperPRasmussen/bokeh,bokeh/bokeh,philippjfr/bokeh,ptitjano/bokeh,jakirkham/bokeh,phobson/bokeh,percyfal/bokeh,percyfal/bokeh,clairetang6/bokeh,aiguofer/bokeh,Karel-van-de-Plassche/bokeh,aavanian/bokeh,stonebig/bokeh,draperjames/bokeh,percyfal/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,KasperPRasmussen/bokeh,aiguofer/bokeh,mindriot101/bokeh,phobson/bokeh,stonebig/bokeh,draperjames/bokeh,bokeh/bokeh,dennisobrien/bokeh,rs2/bokeh,schoolie/bokeh,aavanian/bokeh,justacec/bokeh,philippjfr/bokeh,draperjames/bokeh,schoolie/bokeh,schoolie/bokeh,jakirkham/bokeh,rs2/bokeh,justacec/bokeh,schoolie/bokeh,aiguofer/bokeh,stonebig/bokeh,philippjfr/bokeh,Karel-van-de-Plassche/bokeh,azjps/bokeh,draperjames/bokeh,azjps/bokeh,DuCorey/bokeh,mindriot101/bokeh,phobson/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,draperjames/bokeh,quasiben/bokeh,dennisobrien/bokeh,Karel-van-de-Plassche/bokeh,DuCorey/bokeh,aiguofer/bokeh,timsnyder/bokeh,phobson/bokeh,DuCorey/bokeh,aiguofer/bokeh,percyfal/bokeh,azjps/bokeh,phobson/bokeh,KasperPRasmussen/bokeh,rs2/bokeh | ---
+++
@@ -2,6 +2,7 @@
export type Int = number;
export type Percent = number;
export type Color = NamedColor |
+ String |
[Int, Int, Int] | // RGB (r, g, b)
[Int, Int, Int, Percent]; // RGBA(r, g, b, a)
export type FontSize = string; |
4521434b7076764f2162b35bc9979b762795661b | problems/superstitious-elevators/solution.ts | problems/superstitious-elevators/solution.ts | import {ISolution} from '../solution.interface';
export class Solution implements ISolution<number, string> {
solve(input: number): string {
return "bla";
}
private isSafe(number: number): boolean {
return !(number === 13 || number.toString().indexOf("4") !== -1);
}
}
| import {ISolution} from '../solution.interface';
export class Solution implements ISolution<number, string> {
solve(input: number): string {
let floors = [];
for (let f = -1; f < input; f++) {
if (this.isSafe(f)) {
floors.push(f);
}
}
return "bla";
}
private isSafe(number: number): boolean {
return !(number === 13 || number.toString().indexOf("4") !== -1);
}
}
| Add all safe floors to an array | Add all safe floors to an array
| TypeScript | unlicense | Jameskmonger/challenges | ---
+++
@@ -2,6 +2,12 @@
export class Solution implements ISolution<number, string> {
solve(input: number): string {
+ let floors = [];
+ for (let f = -1; f < input; f++) {
+ if (this.isSafe(f)) {
+ floors.push(f);
+ }
+ }
return "bla";
}
|
d90ab21eeb41d7014366b8ef8a0b906dfca03055 | src/services/DeviceService.ts | src/services/DeviceService.ts | import winston from 'winston';
import DeviceModel from '../models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(mail: string, token: string) {
let device = await DeviceModel.findOne({ mail });
if (!device) {
device = new DeviceModel({
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (mail: ${mail}, token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
await device.save();
}
public static async getDevices(mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ mail });
if (!device) {
const errorMessage = `Could not find Device: Device (mail: ${mail}) does not exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
| import winston from 'winston';
import DeviceModel from '../models/device';
export default class DeviceService {
// region public static methods
public static async addDevice(platform: string, mail: string, token: string) {
let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
platform,
mail,
tokens: [],
});
await device.save();
}
if (device.tokens.indexOf(token) !== -1) {
const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
device.tokens.push(token);
await device.save();
}
public static async getDevices(platform: string, mail: string): Promise<string[]> {
const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
const errorMessage = `Could not find Device: Device (mail: ${mail}) does not exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
return device.tokens;
}
// endregion
// region private static methods
// endregion
// region public members
// endregion
// region private members
// endregion
// region constructor
// endregion
// region public methods
// endregion
// region private methods
// endregion
}
| Add platform to device service | Add platform to device service
| TypeScript | mit | schulcloud/node-notification-service,schulcloud/node-notification-service,schulcloud/node-notification-service | ---
+++
@@ -3,10 +3,11 @@
export default class DeviceService {
// region public static methods
- public static async addDevice(mail: string, token: string) {
- let device = await DeviceModel.findOne({ mail });
+ public static async addDevice(platform: string, mail: string, token: string) {
+ let device = await DeviceModel.findOne({ platform, mail });
if (!device) {
device = new DeviceModel({
+ platform,
mail,
tokens: [],
});
@@ -14,7 +15,8 @@
}
if (device.tokens.indexOf(token) !== -1) {
- const errorMessage = `Could not add Device: Device (mail: ${mail}, token: ${token}) already exists.`;
+ const errorMessage = `Could not add Device: Device (platform: ${platform}, mail: ${mail},
+ token: ${token}) already exists.`;
winston.error(errorMessage);
throw new Error(errorMessage);
}
@@ -23,8 +25,8 @@
await device.save();
}
- public static async getDevices(mail: string): Promise<string[]> {
- const device = await DeviceModel.findOne({ mail });
+ public static async getDevices(platform: string, mail: string): Promise<string[]> {
+ const device = await DeviceModel.findOne({ platform, mail });
if (!device) {
const errorMessage = `Could not find Device: Device (mail: ${mail}) does not exists.`;
winston.error(errorMessage); |
51102291a9692f57d03787fbda86d629419eccf8 | src/client/routes/game/EndScreen.tsx | src/client/routes/game/EndScreen.tsx | import * as React from "react"
import { withStyles, createStyles, Theme } from "@material-ui/core/styles"
const styles = (theme: Theme) => createStyles({
root: {
width: "100vw",
height: "100vh",
position: "fixed",
top: 0,
left: 0,
},
timangi: {
position: "absolute",
pointerEvents: "none",
animation: "timangi 1.5s linear infinite",
},
})
const EndScreen = ({ classes }) => (
<div id="timangit-sataa" className={classes.root}>
{Array.from(Array(75)).map((x, i) => {
const size = Math.random() * 100
const randomAnimationModifier = Math.floor(Math.random() * (98 - 1 + 1) + 1)
return (
<i
key={i}
className={classes.timangi}
style={{
left: `${Math.random() * 100}%`,
animationDelay: `0.${randomAnimationModifier}s`,
fontSize: `${size}px`,
animationDuration: `1.${randomAnimationModifier}s`,
}}
>
💎
</i>
)
})}
</div>
)
export default withStyles(styles)(EndScreen) | import * as React from "react"
import { withStyles, createStyles, Theme } from "@material-ui/core/styles"
const styles = (theme: Theme) => createStyles({
root: {
pointerEvents: "none",
width: "100vw",
height: "100vh",
position: "fixed",
top: 0,
left: 0,
},
timangi: {
position: "absolute",
animation: "timangi 1.5s linear infinite",
},
})
const EndScreen = ({ classes }) => (
<div id="timangit-sataa" className={classes.root}>
{Array.from(Array(75)).map((x, i) => {
const size = Math.random() * 100
const randomAnimationModifier = Math.floor(Math.random() * (98 - 1 + 1) + 1)
return (
<i
key={i}
className={classes.timangi}
style={{
left: `${Math.random() * 100}%`,
animationDelay: `0.${randomAnimationModifier}s`,
fontSize: `${size}px`,
animationDuration: `1.${randomAnimationModifier}s`,
}}
>
💎
</i>
)
})}
</div>
)
export default withStyles(styles)(EndScreen) | Allow clicking through 💎 end screen | Allow clicking through 💎 end screen
| TypeScript | mit | Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki,Majavapaja/Mursushakki | ---
+++
@@ -3,6 +3,7 @@
const styles = (theme: Theme) => createStyles({
root: {
+ pointerEvents: "none",
width: "100vw",
height: "100vh",
position: "fixed",
@@ -11,7 +12,6 @@
},
timangi: {
position: "absolute",
- pointerEvents: "none",
animation: "timangi 1.5s linear infinite",
},
}) |
d27e17db4cb1c1d13609017b9aa861e245663794 | src/cli/yargs.ts | src/cli/yargs.ts | import fs from 'fs';
import libpath from 'path';
import _yargs from 'yargs';
const packageInfo = JSON.parse(fs.readFileSync(libpath.resolve(__dirname, '../../package.json'), 'utf8'));
const yargs = _yargs
.demand(1)
.usage(
`
Upload-GPhotos ${packageInfo.version}
Usage: upload-gphotos file [...] [--no-output-json] [--quiet] [-r retry] [-u username] [-p password] [-a albumname]
`.trim(),
)
.help('help')
.options({
retry: {
alias: 'r',
type: 'number',
default: 3,
desc: 'The number of times to retry when failed uploads.',
},
username: {
alias: 'username',
type: 'string',
desc: 'Google account username.',
},
password: {
alias: 'p',
type: 'string',
desc: 'Google account password.',
},
album: {
alias: 'a',
type: 'array',
default: [] as string[],
desc: 'An albums to put uploaded files.',
},
quiet: {
type: 'boolean',
default: false,
desc: 'Prevent to show progress.',
},
'output-json': {
type: 'boolean',
default: true,
desc: 'Output information of uploading as JSON.',
},
help: {
alias: 'h',
type: 'boolean',
desc: 'Show help.',
},
version: {
alias: 'v',
type: 'boolean',
desc: 'Show version number.',
},
});
export { yargs };
| import fs from 'fs';
import libpath from 'path';
import _yargs from 'yargs';
const packageInfo = JSON.parse(fs.readFileSync(libpath.resolve(__dirname, '../../package.json'), 'utf8'));
const yargs = _yargs
.demand(1)
.usage(
`
Upload-GPhotos ${packageInfo.version}
Usage: upload-gphotos file [...] [--no-output-json] [--quiet] [-r retry] [-u username] [-p password] [-a albumname]
`.trim(),
)
.help('help')
.options({
retry: {
alias: 'r',
type: 'number',
default: 3,
desc: 'The number of times to retry when failed uploads.',
},
username: {
alias: 'u',
type: 'string',
desc: 'Google account username.',
},
password: {
alias: 'p',
type: 'string',
desc: 'Google account password.',
},
album: {
alias: 'a',
type: 'array',
default: [] as string[],
desc: 'An albums to put uploaded files.',
},
quiet: {
type: 'boolean',
default: false,
desc: 'Prevent to show progress.',
},
'output-json': {
type: 'boolean',
default: true,
desc: 'Output information of uploading as JSON.',
},
help: {
alias: 'h',
type: 'boolean',
desc: 'Show help.',
},
version: {
alias: 'v',
type: 'boolean',
desc: 'Show version number.',
},
});
export { yargs };
| Fix alias of username argument | Fix alias of username argument
Fixes #446
| TypeScript | mit | 3846masa/upload-gphotos,3846masa/upload-gphotos | ---
+++
@@ -21,7 +21,7 @@
desc: 'The number of times to retry when failed uploads.',
},
username: {
- alias: 'username',
+ alias: 'u',
type: 'string',
desc: 'Google account username.',
}, |
8f51415733614509a07fbcf47b4171a55facbc68 | demo-shell-ng2/app/main.ts | demo-shell-ng2/app/main.ts | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { bootstrap } from '@angular/platform-browser-dynamic';
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HTTP_PROVIDERS } from '@angular/http';
import { ALFRESCO_CORE_PROVIDERS } from 'ng2-alfresco-core';
import { UploadService } from 'ng2-alfresco-upload';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
ALFRESCO_CORE_PROVIDERS,
UploadService
]);
| /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { bootstrap } from '@angular/platform-browser-dynamic';
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HTTP_PROVIDERS } from '@angular/http';
import { ALFRESCO_SEARCH_PROVIDERS } from 'ng2-alfresco-search';
import { ALFRESCO_CORE_PROVIDERS } from 'ng2-alfresco-core';
import { UploadService } from 'ng2-alfresco-upload';
import { AppComponent } from './app.component';
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
ALFRESCO_CORE_PROVIDERS,
ALFRESCO_SEARCH_PROVIDERS,
UploadService
]);
| Fix demo shell runtime issue with Search | Fix demo shell runtime issue with Search
| TypeScript | apache-2.0 | Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components | ---
+++
@@ -18,6 +18,7 @@
import { bootstrap } from '@angular/platform-browser-dynamic';
import { ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HTTP_PROVIDERS } from '@angular/http';
+import { ALFRESCO_SEARCH_PROVIDERS } from 'ng2-alfresco-search';
import { ALFRESCO_CORE_PROVIDERS } from 'ng2-alfresco-core';
import { UploadService } from 'ng2-alfresco-upload';
import { AppComponent } from './app.component';
@@ -26,5 +27,6 @@
ROUTER_PROVIDERS,
HTTP_PROVIDERS,
ALFRESCO_CORE_PROVIDERS,
+ ALFRESCO_SEARCH_PROVIDERS,
UploadService
]); |
c3aed714e0f605761ae860236b5f5e666feb38c8 | applications/mail/src/app/components/message/helpers/getIframeSandboxAttributes.ts | applications/mail/src/app/components/message/helpers/getIframeSandboxAttributes.ts | import { isSafari } from '@proton/shared/lib/helpers/browser';
const getIframeSandboxAttributes = (isPrint: boolean) => {
/**
* "allow-modals" : For being able to print emails
*
* "allow-scripts" : allows react portals to execute correctly in Safari
*
* "allow-popups-to-escape-sandbox" allows to open links in non modal sandboxed mode
*/
const sandboxAttributes: string = [
'allow-same-origin',
'allow-popups',
'allow-popups-to-escape-sandbox',
...(isPrint ? ['allow-modals'] : []),
...(isSafari() ? ['allow-scripts'] : []),
].join(' ');
return sandboxAttributes;
};
export default getIframeSandboxAttributes;
| import { isSafari } from '@proton/shared/lib/helpers/browser';
const getIframeSandboxAttributes = (isPrint: boolean) => {
/**
* "allow-same-origin"
* Because iframe origin is set to protonmail.com we need
* to be able to access it's origin
* "allow-modals"
* Allow to be able to print emails
* "allow-scripts"
* allows react portals to execute correctly in Safari
* "allow-popups"
* allows target="_blank" links to work
* "allow-popups-to-escape-sandbox"
* allows to open links in non sandboxed mode
* for ex : if allow-scripts is not present opened links are allowed to execute scripts
*
* ATM we do not need to allow the following options
* - allow-forms
* - allow-pointer-lock
* - allow-top-navigation
*/
const sandboxAttributes: string = [
'allow-same-origin',
'allow-popups',
'allow-popups-to-escape-sandbox',
...(isPrint ? ['allow-modals'] : []),
...(isSafari() ? ['allow-scripts'] : []),
].join(' ');
return sandboxAttributes;
};
export default getIframeSandboxAttributes;
| Add documentation about sandbox attribute | Add documentation about sandbox attribute
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -2,11 +2,23 @@
const getIframeSandboxAttributes = (isPrint: boolean) => {
/**
- * "allow-modals" : For being able to print emails
+ * "allow-same-origin"
+ * Because iframe origin is set to protonmail.com we need
+ * to be able to access it's origin
+ * "allow-modals"
+ * Allow to be able to print emails
+ * "allow-scripts"
+ * allows react portals to execute correctly in Safari
+ * "allow-popups"
+ * allows target="_blank" links to work
+ * "allow-popups-to-escape-sandbox"
+ * allows to open links in non sandboxed mode
+ * for ex : if allow-scripts is not present opened links are allowed to execute scripts
*
- * "allow-scripts" : allows react portals to execute correctly in Safari
- *
- * "allow-popups-to-escape-sandbox" allows to open links in non modal sandboxed mode
+ * ATM we do not need to allow the following options
+ * - allow-forms
+ * - allow-pointer-lock
+ * - allow-top-navigation
*/
const sandboxAttributes: string = [
'allow-same-origin', |
2e557708a1a5cfd6c3156b475b123bc2495945d9 | addons/centered/src/styles.ts | addons/centered/src/styles.ts | const styles = {
style: {
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0,
display: 'flex',
alignItems: 'center',
overflow: 'auto',
},
innerStyle: {
margin: 'auto',
maxHeight: '100%', // Hack for centering correctly in IE11
},
} as const;
export default styles;
| const styles = {
style: {
position: 'fixed',
top: '0',
left: '0',
bottom: '0',
right: '0',
display: 'flex',
alignItems: 'center',
overflow: 'auto',
},
innerStyle: {
margin: 'auto',
maxHeight: '100%', // Hack for centering correctly in IE11
},
} as const;
export default styles;
| FIX incorrect style usage of numbers in addon-center | FIX incorrect style usage of numbers in addon-center
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook | ---
+++
@@ -1,10 +1,10 @@
const styles = {
style: {
position: 'fixed',
- top: 0,
- left: 0,
- bottom: 0,
- right: 0,
+ top: '0',
+ left: '0',
+ bottom: '0',
+ right: '0',
display: 'flex',
alignItems: 'center',
overflow: 'auto', |
f3f047b6f146631a4033a3e4cbcaa72a1b9271d2 | types/index.d.ts | types/index.d.ts | declare class OrderedMap<T = any> {
private constructor(content: Array<string | T>)
get(key: string): T | undefined
update(key: string, value: T, newKey?: string): OrderedMap<T>
remove(key: string): OrderedMap<T>
addToStart(key: string, value: T): OrderedMap<T>
addToEnd(key: string, value: T): OrderedMap<T>
addBefore(place: string, key: string, value: T): OrderedMap<T>
forEach(fn: (key: string, value: T) => any): void
prepend(map: MapLike<T>): OrderedMap<T>
append(map: MapLike<T>): OrderedMap<T>
subtract(map: MapLike<T>): OrderedMap<T>
get size(): number
static from<T>(map: MapLike<T>): OrderedMap<T>
}
type MapLike<T = any> = Record<string, T> | OrderedMap<T>
export = OrderedMap
| declare class OrderedMap<T = any> {
private constructor(content: Array<string | T>)
get(key: string): T | undefined
update(key: string, value: T, newKey?: string): OrderedMap<T>
remove(key: string): OrderedMap<T>
addToStart(key: string, value: T): OrderedMap<T>
addToEnd(key: string, value: T): OrderedMap<T>
addBefore(place: string, key: string, value: T): OrderedMap<T>
forEach(fn: (key: string, value: T) => any): void
prepend(map: MapLike<T>): OrderedMap<T>
append(map: MapLike<T>): OrderedMap<T>
subtract(map: MapLike<T>): OrderedMap<T>
readonly size: number
static from<T>(map: MapLike<T>): OrderedMap<T>
}
type MapLike<T = any> = Record<string, T> | OrderedMap<T>
export = OrderedMap
| Make types compatible with TS <= 3.6 | Make types compatible with TS <= 3.6
Closes https://github.com/marijnh/orderedmap/issues/10
| TypeScript | mit | marijnh/orderedmap | ---
+++
@@ -21,7 +21,7 @@
subtract(map: MapLike<T>): OrderedMap<T>
- get size(): number
+ readonly size: number
static from<T>(map: MapLike<T>): OrderedMap<T>
} |
bf5053bfd2c8906ad113e62cdc7fdcf99a9390ed | packages/react-form-with-constraints/src/assert.ts | packages/react-form-with-constraints/src/assert.ts | // https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#assertion-functions
export function assert(condition: boolean, message?: string): asserts condition {
// error TS2569: Type 'IArguments' is not an array type or a string type.
// Use compiler option '--downlevelIteration' to allow iterating of iterators.
//console.assert(...arguments);
if (message === undefined) console.assert(condition);
else console.assert(condition, message);
}
| // https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#assertion-functions
export function assert(condition: boolean, message?: string): asserts condition {
// error TS2569: Type 'IArguments' is not an array type or a string type.
// Use compiler option '--downlevelIteration' to allow iterating of iterators.
//console.assert(...arguments);
if (message === undefined) {
console.assert(condition);
} else {
console.assert(condition, message);
}
}
| Fix jscodeshift "TypeError: Cannot read property 'expression' of undefined" | Fix jscodeshift "TypeError: Cannot read property 'expression' of undefined"
jscodeshift does not like if else syntax without { } | TypeScript | mit | tkrotoff/react-form-with-constraints,tkrotoff/react-form-with-constraints,tkrotoff/react-form-with-constraints | ---
+++
@@ -4,6 +4,9 @@
// Use compiler option '--downlevelIteration' to allow iterating of iterators.
//console.assert(...arguments);
- if (message === undefined) console.assert(condition);
- else console.assert(condition, message);
+ if (message === undefined) {
+ console.assert(condition);
+ } else {
+ console.assert(condition, message);
+ }
} |
1cfa116cc325461c041c2ed2c17a367a2f759795 | src/Avalonia.DesignerSupport/Remote/HtmlTransport/webapp/src/Models/Input/MouseEventHelpers.ts | src/Avalonia.DesignerSupport/Remote/HtmlTransport/webapp/src/Models/Input/MouseEventHelpers.ts | import * as React from "react";
import {InputModifiers} from "src/Models/Input/InputModifiers";
import {MouseButton} from "src/Models/Input/MouseButton";
export function getModifiers(e: React.MouseEvent): Array<InputModifiers> {
let modifiers : Array<InputModifiers> = [];
if (e.altKey)
modifiers.push(InputModifiers.Alt);
if (e.ctrlKey)
modifiers.push(InputModifiers.Control);
if (e.shiftKey)
modifiers.push(InputModifiers.Shift);
if (e.metaKey)
modifiers.push(InputModifiers.Windows);
if ((e.buttons & 1) != 0)
modifiers.push(InputModifiers.LeftMouseButton);
if ((e.buttons & 2) != 0)
modifiers.push(InputModifiers.RightMouseButton);
if ((e.buttons & 4) != 0)
modifiers.push(InputModifiers.MiddleMouseButton);
return modifiers;
}
export function getMouseButton(e: React.MouseEvent) : MouseButton {
if (e.button == 1) {
return MouseButton.Left;
} else if (e.button == 2) {
return MouseButton.Right;
} else if (e.button == 4) {
return MouseButton.Middle
} else {
return MouseButton.None;
}
}
| import * as React from "react";
import {InputModifiers} from "src/Models/Input/InputModifiers";
import {MouseButton} from "src/Models/Input/MouseButton";
export function getModifiers(e: React.MouseEvent): Array<InputModifiers> {
let modifiers : Array<InputModifiers> = [];
if (e.altKey)
modifiers.push(InputModifiers.Alt);
if (e.ctrlKey)
modifiers.push(InputModifiers.Control);
if (e.shiftKey)
modifiers.push(InputModifiers.Shift);
if (e.metaKey)
modifiers.push(InputModifiers.Windows);
if ((e.buttons & 1) != 0)
modifiers.push(InputModifiers.LeftMouseButton);
if ((e.buttons & 2) != 0)
modifiers.push(InputModifiers.RightMouseButton);
if ((e.buttons & 4) != 0)
modifiers.push(InputModifiers.MiddleMouseButton);
return modifiers;
}
export function getMouseButton(e: React.MouseEvent) : MouseButton {
if (e.button == 0) {
return MouseButton.Left;
} else if (e.button == 1) {
return MouseButton.Middle;
} else if (e.button == 2) {
return MouseButton.Right;
} else {
return MouseButton.None;
}
}
| Fix typo in detect mouse button | Fix typo in detect mouse button
| TypeScript | mit | AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia | ---
+++
@@ -25,12 +25,12 @@
}
export function getMouseButton(e: React.MouseEvent) : MouseButton {
- if (e.button == 1) {
+ if (e.button == 0) {
return MouseButton.Left;
+ } else if (e.button == 1) {
+ return MouseButton.Middle;
} else if (e.button == 2) {
return MouseButton.Right;
- } else if (e.button == 4) {
- return MouseButton.Middle
} else {
return MouseButton.None;
} |
d02bf7b4f0e10fc853779b329186c9691e752bba | src/__tests__/gcode-parser.ts | src/__tests__/gcode-parser.ts | import { Parser } from "../gcode-parser";
test('a single gcode cmd should result in 1 layer', () => {
const parser = new Parser();
const gcode =`G1 X0 Y0 Z1`;
const parsed = parser.parseGcode(gcode);
expect(parsed).not.toBeNull();
expect(parsed.layers).not.toBeNull();
expect(parsed.layers.length).toEqual(1)
expect(parsed.layers[0].commands).not.toBeNull();
expect(parsed.layers[0].commands.length).toEqual(1);
});
| import { Parser } from "../gcode-parser";
test('a single gcode cmd should result in 1 layer with 1 command', () => {
const parser = new Parser();
const gcode =`G1 X0 Y0 Z1`;
const parsed = parser.parseGcode(gcode);
expect(parsed).not.toBeNull();
expect(parsed.layers).not.toBeNull();
expect(parsed.layers.length).toEqual(1)
expect(parsed.layers[0].commands).not.toBeNull();
expect(parsed.layers[0].commands.length).toEqual(1);
});
test('2 horizontal moves should result in 1 layer with 2 commands', () => {
const parser = new Parser();
const gcode =`G1 X0 Y0 Z1
G1 X10 Y10 Z1`;
const parsed = parser.parseGcode(gcode);
expect(parsed).not.toBeNull();
expect(parsed.layers).not.toBeNull();
expect(parsed.layers.length).toEqual(1)
expect(parsed.layers[0].commands).not.toBeNull();
expect(parsed.layers[0].commands.length).toEqual(2);
});
test('2 vertical moves should result in 2 layers with 1 command', () => {
const parser = new Parser();
const gcode =`G1 X0 Y0 Z1
G1 X0 Y0 Z2`;
const parsed = parser.parseGcode(gcode);
expect(parsed).not.toBeNull();
expect(parsed.layers).not.toBeNull();
expect(parsed.layers.length).toEqual(2)
expect(parsed.layers[0].commands).not.toBeNull();
expect(parsed.layers[0].commands.length).toEqual(1);
});
| Add tests for the some elementry parsing cases | Add tests for the some elementry parsing cases
| TypeScript | mit | remcoder/gcode-previewer,remcoder/gcode-previewer | ---
+++
@@ -1,6 +1,6 @@
import { Parser } from "../gcode-parser";
-test('a single gcode cmd should result in 1 layer', () => {
+test('a single gcode cmd should result in 1 layer with 1 command', () => {
const parser = new Parser();
const gcode =`G1 X0 Y0 Z1`;
const parsed = parser.parseGcode(gcode);
@@ -10,3 +10,27 @@
expect(parsed.layers[0].commands).not.toBeNull();
expect(parsed.layers[0].commands.length).toEqual(1);
});
+
+test('2 horizontal moves should result in 1 layer with 2 commands', () => {
+ const parser = new Parser();
+ const gcode =`G1 X0 Y0 Z1
+ G1 X10 Y10 Z1`;
+ const parsed = parser.parseGcode(gcode);
+ expect(parsed).not.toBeNull();
+ expect(parsed.layers).not.toBeNull();
+ expect(parsed.layers.length).toEqual(1)
+ expect(parsed.layers[0].commands).not.toBeNull();
+ expect(parsed.layers[0].commands.length).toEqual(2);
+});
+
+test('2 vertical moves should result in 2 layers with 1 command', () => {
+ const parser = new Parser();
+ const gcode =`G1 X0 Y0 Z1
+ G1 X0 Y0 Z2`;
+ const parsed = parser.parseGcode(gcode);
+ expect(parsed).not.toBeNull();
+ expect(parsed.layers).not.toBeNull();
+ expect(parsed.layers.length).toEqual(2)
+ expect(parsed.layers[0].commands).not.toBeNull();
+ expect(parsed.layers[0].commands.length).toEqual(1);
+}); |
a8f544fbc20db7f1ce01023e0d599467d8238008 | e2e/app.e2e-spec.ts | e2e/app.e2e-spec.ts | import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(7);
});
});
| import { Ng2CiAppPage } from './app.po';
describe('ng2-ci-app App', function () {
let page: Ng2CiAppPage;
beforeEach(() => {
page = new Ng2CiAppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('NG Friends!');
});
it('should display some ng friends', () => {
page.navigateTo();
expect(page.getFriends()).toEqual(8);
});
});
| Fix e2e tests for new Carmen Popoviciu feature | test(e2e): Fix e2e tests for new Carmen Popoviciu feature
Fix e2e tests for new Carmen Popoviciu feature
| TypeScript | mit | Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app,Elecash/ng2-ci-app | ---
+++
@@ -14,6 +14,6 @@
it('should display some ng friends', () => {
page.navigateTo();
- expect(page.getFriends()).toEqual(7);
+ expect(page.getFriends()).toEqual(8);
});
}); |
d9d43297a8ccf59f2f244862f4a46a22b39da369 | lib/ui/src/components/sidebar/useLastViewed.ts | lib/ui/src/components/sidebar/useLastViewed.ts | import { window } from 'global';
import { useCallback, useEffect, useState } from 'react';
import { Selection, StoryRef } from './types';
const retrieveLastViewedStoryIds = (): StoryRef[] => {
try {
const raw = window.localStorage.getItem('lastViewedStoryIds');
const val = typeof raw === 'string' && JSON.parse(raw);
if (!val || !Array.isArray(val)) return [];
if (!val.some((item) => typeof item === 'object' && item.storyId && item.refId)) return [];
return val;
} catch (e) {
return [];
}
};
const storeLastViewedStoryIds = (items: StoryRef[]) => {
try {
window.localStorage.setItem('lastViewedStoryIds', JSON.stringify(items));
} catch (e) {
// do nothing
}
};
export const useLastViewed = (selection: Selection) => {
const [lastViewed, setLastViewed] = useState(retrieveLastViewedStoryIds);
const updateLastViewed = useCallback(
(story: StoryRef) =>
setLastViewed((state: StoryRef[]) => {
const index = state.findIndex(
({ storyId, refId }) => storyId === story.storyId && refId === story.refId
);
if (index === 0) return state;
const update =
index === -1
? [story, ...state]
: [story, ...state.slice(0, index), ...state.slice(index + 1)];
storeLastViewedStoryIds(update);
return update;
}),
[]
);
useEffect(() => {
if (selection) updateLastViewed(selection);
}, [selection]);
return lastViewed;
};
| import { useCallback, useEffect, useState } from 'react';
import store from 'store2';
import { Selection, StoryRef } from './types';
const retrieveLastViewedStoryIds = (): StoryRef[] => {
const items = store.get('lastViewedStoryIds');
if (!items || !Array.isArray(items)) return [];
if (!items.some((item) => typeof item === 'object' && item.storyId && item.refId)) return [];
return items;
};
export const useLastViewed = (selection: Selection) => {
const [lastViewed, setLastViewed] = useState(retrieveLastViewedStoryIds);
const updateLastViewed = useCallback(
(story: StoryRef) =>
setLastViewed((state: StoryRef[]) => {
const index = state.findIndex(
({ storyId, refId }) => storyId === story.storyId && refId === story.refId
);
if (index === 0) return state;
const update =
index === -1
? [story, ...state]
: [story, ...state.slice(0, index), ...state.slice(index + 1)];
store.set('lastViewedStoryIds', update);
return update;
}),
[]
);
useEffect(() => {
if (selection) updateLastViewed(selection);
}, [selection]);
return lastViewed;
};
| Use store2 instead of direct localStorage. | Use store2 instead of direct localStorage.
| TypeScript | mit | storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -1,26 +1,13 @@
-import { window } from 'global';
import { useCallback, useEffect, useState } from 'react';
+import store from 'store2';
import { Selection, StoryRef } from './types';
const retrieveLastViewedStoryIds = (): StoryRef[] => {
- try {
- const raw = window.localStorage.getItem('lastViewedStoryIds');
- const val = typeof raw === 'string' && JSON.parse(raw);
- if (!val || !Array.isArray(val)) return [];
- if (!val.some((item) => typeof item === 'object' && item.storyId && item.refId)) return [];
- return val;
- } catch (e) {
- return [];
- }
-};
-
-const storeLastViewedStoryIds = (items: StoryRef[]) => {
- try {
- window.localStorage.setItem('lastViewedStoryIds', JSON.stringify(items));
- } catch (e) {
- // do nothing
- }
+ const items = store.get('lastViewedStoryIds');
+ if (!items || !Array.isArray(items)) return [];
+ if (!items.some((item) => typeof item === 'object' && item.storyId && item.refId)) return [];
+ return items;
};
export const useLastViewed = (selection: Selection) => {
@@ -37,7 +24,7 @@
index === -1
? [story, ...state]
: [story, ...state.slice(0, index), ...state.slice(index + 1)];
- storeLastViewedStoryIds(update);
+ store.set('lastViewedStoryIds', update);
return update;
}),
[] |
89174020fd15a82633ee466ec364def9e5222116 | test/e2e/console/console-live-expressions_test.ts | test/e2e/console/console-live-expressions_test.ts | // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {click, getBrowserAndPages, typeText, waitFor, waitForNone} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {CONSOLE_CREATE_LIVE_EXPRESSION_SELECTOR, CONSOLE_TAB_SELECTOR} from '../helpers/console-helpers.js';
describe('The Console Tab', () => {
it('commits live expression with Enter', async () => {
const {frontend} = getBrowserAndPages();
await click(CONSOLE_TAB_SELECTOR);
await click(CONSOLE_CREATE_LIVE_EXPRESSION_SELECTOR);
const consolePin = await waitFor('.console-pin');
const editorFocusedPromise = waitFor('.cm-editor.cm-focused', consolePin);
const editorUnfocusedPromise = waitForNone('.cm-editor.cm-focused', consolePin);
await editorFocusedPromise;
await typeText('1 + 2 + 3');
await frontend.keyboard.press('Enter');
await editorUnfocusedPromise;
});
});
| // Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {click, getBrowserAndPages, typeText, waitFor, waitForNone} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {CONSOLE_CREATE_LIVE_EXPRESSION_SELECTOR, CONSOLE_TAB_SELECTOR} from '../helpers/console-helpers.js';
describe('The Console Tab', () => {
it('commits live expression with Enter', async () => {
const {frontend} = getBrowserAndPages();
await click(CONSOLE_TAB_SELECTOR);
await click(CONSOLE_CREATE_LIVE_EXPRESSION_SELECTOR);
const consolePin = await waitFor('.console-pin');
await waitFor('.cm-editor.cm-focused', consolePin);
await typeText('1 + 2 + 3');
const editorUnfocusedPromise = waitForNone('.cm-editor.cm-focused', consolePin);
await frontend.keyboard.press('Enter');
await editorUnfocusedPromise;
});
});
| Fix live expression e2e test. | [console] Fix live expression e2e test.
Bug: chromium:1260744
Change-Id: I001298ec21e42d6f469548dc2c82fb9e8f283e04
Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3566004
Commit-Queue: Benedikt Meurer <024a1e0af501338d11c3b837c6193d11c140d792@chromium.org>
Auto-Submit: Benedikt Meurer <024a1e0af501338d11c3b837c6193d11c140d792@chromium.org>
Reviewed-by: Danil Somsikov <f16a5ee11618cab93684e694f9aa762d34f02920@chromium.org>
Commit-Queue: Danil Somsikov <f16a5ee11618cab93684e694f9aa762d34f02920@chromium.org>
| TypeScript | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend | ---
+++
@@ -14,11 +14,11 @@
await click(CONSOLE_CREATE_LIVE_EXPRESSION_SELECTOR);
const consolePin = await waitFor('.console-pin');
- const editorFocusedPromise = waitFor('.cm-editor.cm-focused', consolePin);
+
+ await waitFor('.cm-editor.cm-focused', consolePin);
+ await typeText('1 + 2 + 3');
+
const editorUnfocusedPromise = waitForNone('.cm-editor.cm-focused', consolePin);
-
- await editorFocusedPromise;
- await typeText('1 + 2 + 3');
await frontend.keyboard.press('Enter');
await editorUnfocusedPromise;
}); |
c7030bd3bb3ff76ee47d518a7e035c7ac25a9247 | src/index.ts | src/index.ts | #!/usr/bin/env node
if (!process.env.DEBUG) {
process.env.DEBUG = 'peercalls'
}
import _debug from 'debug'
import forEach from 'lodash/forEach'
import { io } from './server/app'
import app from './server/app'
const debug = _debug('peercalls')
const port = process.env.PORT || 3000
app.listen(port, () => debug('Listening on: %s', port))
| #!/usr/bin/env node
if (!process.env.DEBUG) {
process.env.DEBUG = 'peercalls'
}
import _debug from 'debug'
import app from './server/app'
const debug = _debug('peercalls')
const port = process.env.PORT || 3000
app.listen(port, () => debug('Listening on: %s', port))
process.on('SIGINT', () => process.exit())
process.on('SIGTERM', () => process.exit())
| Add simple handling of SIGINT/SIGTERM for Docker | Add simple handling of SIGINT/SIGTERM for Docker
| TypeScript | mit | jeremija/peer-calls,jeremija/peer-calls,jeremija/peer-calls | ---
+++
@@ -4,11 +4,12 @@
}
import _debug from 'debug'
-import forEach from 'lodash/forEach'
-import { io } from './server/app'
import app from './server/app'
const debug = _debug('peercalls')
const port = process.env.PORT || 3000
app.listen(port, () => debug('Listening on: %s', port))
+
+process.on('SIGINT', () => process.exit())
+process.on('SIGTERM', () => process.exit()) |
ef45ab3448ccb6e25b84af5fae75103a3163dd32 | src/commandpalette/index.ts | src/commandpalette/index.ts | /*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
Token
} from 'phosphor/lib/core/token';
import {
CommandPalette
} from 'phosphor/lib/ui/commandpalette';
/* tslint:disable */
/**
* The command palette token.
*/
export
const ICommandPalette = new Token<ICommandPalette>('jupyter.services.commandpalette');
/* tslint:enable */
export
interface ICommandPalette extends CommandPalette {}
| /*-----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
import {
DisposableDelegate, IDisposable
} from 'phosphor/lib/core/disposable';
import {
Token
} from 'phosphor/lib/core/token';
import {
CommandPalette
} from 'phosphor/lib/ui/commandpalette';
/* tslint:disable */
/**
* The command palette token.
*/
export
const ICommandPalette = new Token<ICommandPalette>('jupyter.services.commandpalette');
/* tslint:enable */
export
interface ICommandPalette {
/**
* Get the command palette input node.
*
* #### Notes
* This is a read-only property.
*/
inputNode: HTMLInputElement;
/**
* Add a command item to the command palette.
*
* @param options - The options for creating the command item.
*
* @returns A disposable that will remove the item from the palette.
*/
add(options: CommandPalette.IItemOptions | CommandPalette.IItemOptions[]): IDisposable;
}
/**
* A thin wrapper around the `CommandPalette` class to conform with the
* JupyterLab interface for the application-wide command palette.
*/
export
class Palette extends CommandPalette {
/**
* Add a command item to the command palette.
*
* @param options - The options for creating the command item.
*
* @returns A disposable that will remove the item from the palette.
*/
add(options: CommandPalette.IItemOptions | CommandPalette.IItemOptions[]): IDisposable {
if (Array.isArray(options)) {
let items = options.map(item => super.addItem(item));
return new DisposableDelegate(() => {
items.forEach(item => super.removeItem(item));
});
}
let item = super.addItem(options as CommandPalette.IItemOptions);
return new DisposableDelegate(() => this.removeItem(item));
}
}
| Update the ICommandPalette interface to shrink the API surface for plugin authors. | Update the ICommandPalette interface to shrink the API surface for plugin authors.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab | ---
+++
@@ -2,6 +2,10 @@
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
+
+import {
+ DisposableDelegate, IDisposable
+} from 'phosphor/lib/core/disposable';
import {
Token
@@ -21,4 +25,48 @@
/* tslint:enable */
export
-interface ICommandPalette extends CommandPalette {}
+interface ICommandPalette {
+ /**
+ * Get the command palette input node.
+ *
+ * #### Notes
+ * This is a read-only property.
+ */
+ inputNode: HTMLInputElement;
+
+ /**
+ * Add a command item to the command palette.
+ *
+ * @param options - The options for creating the command item.
+ *
+ * @returns A disposable that will remove the item from the palette.
+ */
+ add(options: CommandPalette.IItemOptions | CommandPalette.IItemOptions[]): IDisposable;
+}
+
+
+/**
+ * A thin wrapper around the `CommandPalette` class to conform with the
+ * JupyterLab interface for the application-wide command palette.
+ */
+export
+class Palette extends CommandPalette {
+ /**
+ * Add a command item to the command palette.
+ *
+ * @param options - The options for creating the command item.
+ *
+ * @returns A disposable that will remove the item from the palette.
+ */
+ add(options: CommandPalette.IItemOptions | CommandPalette.IItemOptions[]): IDisposable {
+ if (Array.isArray(options)) {
+ let items = options.map(item => super.addItem(item));
+ return new DisposableDelegate(() => {
+ items.forEach(item => super.removeItem(item));
+ });
+ }
+
+ let item = super.addItem(options as CommandPalette.IItemOptions);
+ return new DisposableDelegate(() => this.removeItem(item));
+ }
+} |
356c2c34883c261de015dbf20b5a6ec17d328d62 | src/project.ts | src/project.ts | "use strict";
import * as fs from "fs";
import * as path from "path";
import * as vs from "vscode";
import * as util from "./utils";
export function locateBestProjectRoot(folder: string): string {
if (!folder || !util.isWithinWorkspace(folder))
return null;
let dir = folder;
while (dir.length > 1) {
if (fs.existsSync(path.join(dir, "pubspec.yaml")))
return dir;
dir = path.dirname(dir);
}
return null;
}
| "use strict";
import * as fs from "fs";
import * as path from "path";
import * as vs from "vscode";
import * as util from "./utils";
export function locateBestProjectRoot(folder: string): string {
if (!folder || !util.isWithinWorkspace(folder))
return null;
let dir = folder;
while (dir !== path.dirname(dir)) {
if (fs.existsSync(path.join(dir, "pubspec.yaml")))
return dir;
dir = path.dirname(dir);
}
return null;
}
| Fix endless loop in locateBestProjectRoot | Fix endless loop in locateBestProjectRoot
Fixes #570.
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -10,7 +10,7 @@
return null;
let dir = folder;
- while (dir.length > 1) {
+ while (dir !== path.dirname(dir)) {
if (fs.existsSync(path.join(dir, "pubspec.yaml")))
return dir;
dir = path.dirname(dir); |
cccda401ae56ba257815db6cde001a1e3e60730d | showdesktop_ru.ts | showdesktop_ru.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0">
<context>
<name>ShowDesktop</name>
<message>
<source>Show Desktop: Global shortcut '%1' cannot be registered</source>
<translation>Показать рабочий стол: Глобальное короткие клавиш '%1' не могут быть зарегистрированы</translation>
</message>
<message>
<source>Show Desktop</source>
<translation>Показать рабочий стол</translation>
</message>
</context>
</TS> | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru">
<context>
<name>ShowDesktop</name>
<message>
<location filename="../showdesktop.cpp" line="44"/>
<source>Show desktop</source>
<translation>Показать рабочий стол</translation>
</message>
<message>
<location filename="../showdesktop.cpp" line="54"/>
<source>Show Desktop: Global shortcut '%1' cannot be registered</source>
<translation>Показать рабочий стол: глобальное сочетание клавиш '%1' не может быть зарегистрировано</translation>
</message>
<message>
<location filename="../showdesktop.cpp" line="59"/>
<source>Show Desktop</source>
<translation>Показать рабочий стол</translation>
</message>
</context>
</TS>
| Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)." | Revert "Commit from LXDE Pootle server by user LStranger.: 391 of 391 strings translated (0 need review)."
This reverts commit d538764d91b1cf3ea993cdf0d6200eea2b2c9384.
It appeared this change was wrong because it was out of sync.
| TypeScript | lgpl-2.1 | lxde/lxqt-l10n | ---
+++
@@ -1,11 +1,20 @@
-<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0">
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.1" language="ru">
<context>
<name>ShowDesktop</name>
<message>
- <source>Show Desktop: Global shortcut '%1' cannot be registered</source>
- <translation>Показать рабочий стол: Глобальное короткие клавиш '%1' не могут быть зарегистрированы</translation>
+ <location filename="../showdesktop.cpp" line="44"/>
+ <source>Show desktop</source>
+ <translation>Показать рабочий стол</translation>
</message>
<message>
+ <location filename="../showdesktop.cpp" line="54"/>
+ <source>Show Desktop: Global shortcut '%1' cannot be registered</source>
+ <translation>Показать рабочий стол: глобальное сочетание клавиш '%1' не может быть зарегистрировано</translation>
+ </message>
+ <message>
+ <location filename="../showdesktop.cpp" line="59"/>
<source>Show Desktop</source>
<translation>Показать рабочий стол</translation>
</message> |
c9eb50ed879e33625b97c067f73fe14d9537de08 | src/reducers/hitDatabase.ts | src/reducers/hitDatabase.ts | import { HitDatabaseEntry, HitDatabaseMap } from '../types';
import { FetchStatusDetailSuccess } from '../actions/statusDetail';
import { STATUS_DETAIL_SUCCESS } from '../constants';
import { Map } from 'immutable';
import { conflictsPreserveBonus } from '../utils/hitDatabase';
// import sampleHitDB from '../utils/sampleHitDatabase';
const initial: HitDatabaseMap = Map<string, HitDatabaseEntry>();
export default (
state = initial,
action: FetchStatusDetailSuccess
): HitDatabaseMap => {
switch (action.type) {
case STATUS_DETAIL_SUCCESS:
return state.mergeWith(conflictsPreserveBonus, action.data);
default:
return state;
}
};
| import { HitDatabaseEntry, HitDatabaseMap } from '../types';
import { FetchStatusDetailSuccess } from '../actions/statusDetail';
import { EditBonus } from '../actions/bonus';
import { STATUS_DETAIL_SUCCESS, EDIT_BONUS } from '../constants';
import { Map } from 'immutable';
import { conflictsPreserveBonus } from '../utils/hitDatabase';
// import sampleHitDB from '../utils/sampleHitDatabase';
const initial: HitDatabaseMap = Map<string, HitDatabaseEntry>();
export default (
state = initial,
action: FetchStatusDetailSuccess | EditBonus
): HitDatabaseMap => {
switch (action.type) {
case STATUS_DETAIL_SUCCESS:
return state.mergeWith(conflictsPreserveBonus, action.data);
case EDIT_BONUS:
return state.update(action.id, (hit) => ({
...hit,
bonus: action.bonus
}));
default:
return state;
}
};
| Edit reducer to respond to EDIT_BONUS. | Edit reducer to respond to EDIT_BONUS.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -1,6 +1,7 @@
import { HitDatabaseEntry, HitDatabaseMap } from '../types';
import { FetchStatusDetailSuccess } from '../actions/statusDetail';
-import { STATUS_DETAIL_SUCCESS } from '../constants';
+import { EditBonus } from '../actions/bonus';
+import { STATUS_DETAIL_SUCCESS, EDIT_BONUS } from '../constants';
import { Map } from 'immutable';
import { conflictsPreserveBonus } from '../utils/hitDatabase';
// import sampleHitDB from '../utils/sampleHitDatabase';
@@ -9,11 +10,16 @@
export default (
state = initial,
- action: FetchStatusDetailSuccess
+ action: FetchStatusDetailSuccess | EditBonus
): HitDatabaseMap => {
switch (action.type) {
case STATUS_DETAIL_SUCCESS:
return state.mergeWith(conflictsPreserveBonus, action.data);
+ case EDIT_BONUS:
+ return state.update(action.id, (hit) => ({
+ ...hit,
+ bonus: action.bonus
+ }));
default:
return state;
} |
315051c14c3b1a3be1d5ddc7949781d5537e2c4e | lib/gui/app/pages/main/main.ts | lib/gui/app/pages/main/main.ts | /*
* Copyright 2019 balena.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* This page represents the application main page.
*
* @module Etcher.Pages.Main
*/
import * as angular from 'angular';
// @ts-ignore
import * as angularRouter from 'angular-ui-router';
import { react2angular } from 'react2angular';
import MainPage from './MainPage';
export const MODULE_NAME = 'Etcher.Pages.Main';
const Main = angular.module(MODULE_NAME, [angularRouter]);
Main.component('mainPage', react2angular(MainPage, [], ['$state']));
Main.config(($stateProvider: any) => {
$stateProvider.state('main', {
url: '/main',
template: '<main-page style="width:100%"></main-page>',
});
});
| /*
* Copyright 2019 balena.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This page represents the application main page.
*
* @module Etcher.Pages.Main
*/
import * as angular from 'angular';
// @ts-ignore
import * as angularRouter from 'angular-ui-router';
import { react2angular } from 'react2angular';
import MainPage from './MainPage';
export const MODULE_NAME = 'Etcher.Pages.Main';
const Main = angular.module(MODULE_NAME, [angularRouter]);
Main.component('mainPage', react2angular(MainPage, [], ['$state']));
Main.config(($stateProvider: any) => {
$stateProvider.state('main', {
url: '/main',
template: '<main-page style="width:100%"></main-page>',
});
});
| Remove useless 'use strict' from a ts file | Remove useless 'use strict' from a ts file
Change-type: patch
| TypeScript | apache-2.0 | resin-io/herostratus,resin-io/etcher,resin-io/resin-etcher,resin-io/etcher,resin-io/resin-etcher,resin-io/herostratus,resin-io/etcher,resin-io/etcher,resin-io/etcher | ---
+++
@@ -13,8 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-'use strict';
/**
* This page represents the application main page. |
3634a92b5bda757d3ff8f5fd4871f72d68311ba0 | src/components/Toasts.tsx | src/components/Toasts.tsx | import * as React from 'react';
import { Stack, Spinner, TextContainer } from '@shopify/polaris';
interface GenericProps {
readonly message: string;
}
export const GenericWaitingToast = ({ message }: GenericProps) => (
<Stack>
<Spinner
size="small"
accessibilityLabel="Waiting for a response from MTurk."
/>
<TextContainer>{message}</TextContainer>
</Stack>
);
| import * as React from 'react';
import { Stack, Spinner, TextContainer } from '@shopify/polaris';
interface GenericProps {
readonly message: string;
}
export const GenericWaitingToast = ({ message }: GenericProps) => (
<Stack vertical={false} wrap={false}>
<Spinner
size="small"
accessibilityLabel="Waiting for a response from MTurk."
/>
<TextContainer>{message}</TextContainer>
</Stack>
);
| Fix GenericWaitingToast causing long text to wrap to next line. | Fix GenericWaitingToast causing long text to wrap to next line.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -6,7 +6,7 @@
}
export const GenericWaitingToast = ({ message }: GenericProps) => (
- <Stack>
+ <Stack vertical={false} wrap={false}>
<Spinner
size="small"
accessibilityLabel="Waiting for a response from MTurk." |
18ef8ebb1cca067abf7c8c0416a192ecc894ac5a | src/app/components/search/search.directive.ts | src/app/components/search/search.directive.ts | import { SearchController } from './search.controller';
export function digimapSearch(): ng.IDirective {
return {
restrict: 'E',
templateUrl: '/app/components/search/search.html',
controller: SearchController,
controllerAs: 'vm'
};
}
| import { SearchController } from './search.controller';
export function digimapSearch(): ng.IDirective {
return {
restrict: 'E',
scope: {
extraValues: '='
},
templateUrl: 'app/components/search/search.html',
controller: SearchController,
controllerAs: 'vm'
};
}
| Add scope and fix templateUrl: | Add scope and fix templateUrl:
Removed leading slash for path to template HTML.
Added scope, this seems to have helped to make the test run
but I can't say for sure.
| TypeScript | mit | marksmall/mapuse,marksmall/mapuse,marksmall/mapuse | ---
+++
@@ -5,7 +5,10 @@
return {
restrict: 'E',
- templateUrl: '/app/components/search/search.html',
+ scope: {
+ extraValues: '='
+ },
+ templateUrl: 'app/components/search/search.html',
controller: SearchController,
controllerAs: 'vm'
}; |
66e8e572fa16042ef4fae95680aefefe63fc1ac7 | src/constants/enums.ts | src/constants/enums.ts | export enum AudioSource {
NEW_SEARCH_RESULT = 'https://k003.kiwi6.com/hotlink/bbgk5w2fhz/ping.ogg',
SUCCESSFUL_WATCHER_ACCEPT = 'https://k003.kiwi6.com/hotlink/sd6quj2ecs/horn.ogg'
}
export enum TabIndex {
SEARCH = 0,
QUEUE = 1,
WATCHERS = 2,
BLOCKLIST = 3,
ACCOUNT = 4,
SETTINGS = 5
}
export enum Duration {
SECONDS = 'seconds',
HOURS = 'hours',
DAYS = 'days',
WEEKS = 'weeks'
}
| export enum AudioSource {
NEW_SEARCH_RESULT = 'https://k003.kiwi6.com/hotlink/bbgk5w2fhz/ping.ogg',
SUCCESSFUL_WATCHER_ACCEPT = 'https://k003.kiwi6.com/hotlink/sd6quj2ecs/horn.ogg'
}
export enum TabIndex {
SEARCH = 0,
QUEUE = 1,
WATCHERS = 2,
BLOCKLIST = 3,
ACCOUNT = 4,
SETTINGS = 5
}
export enum Duration {
SECONDS = 'seconds',
HOURS = 'hours',
DAYS = 'days',
WEEKS = 'weeks',
MONTHS = 'months'
}
| Add MONTHS to Duration enum. | Add MONTHS to Duration enum.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -16,5 +16,6 @@
SECONDS = 'seconds',
HOURS = 'hours',
DAYS = 'days',
- WEEKS = 'weeks'
+ WEEKS = 'weeks',
+ MONTHS = 'months'
} |
36e2df71d00db559159d6ae8eb48f5c8621fee65 | lib/browser/closeOtherTabs.ts | lib/browser/closeOtherTabs.ts | import assertDefined from '../assertDefined.js';
export default async function closeOtherTabs() {
const [sourceTab, windows] = await Promise.all([
browser.tabs.getCurrent(),
browser.windows.getAll({ populate: true })
]);
// Identify the window that hosts the sourceTab
let sourceWindow = assertDefined(windows.find(w => assertDefined(w.id) === sourceTab.windowId));
// Close other windows
for (let w of windows) {
if (w === sourceWindow) { continue; }
browser.windows.remove(assertDefined(w.id));
}
// Close other tabs
let tabIds = assertDefined(sourceWindow.tabs).map(t => assertDefined(t.id)).filter(id => id !== sourceTab.id);
browser.tabs.remove(tabIds);
} | import assertDefined from '../assertDefined.js';
export default async function closeOtherTabs() {
const [sourceTab, windows] = await Promise.all([
browser.tabs.getCurrent(),
browser.windows.getAll({ populate: true })
]);
// Identify the window that hosts the sourceTab
let sourceWindow = assertDefined(windows.find(w => assertDefined(w.id) === sourceTab.windowId));
// Close other windows
for (let w of windows) {
if (w === sourceWindow) { continue; }
if (w.type === 'popup') { continue; }
browser.windows.remove(assertDefined(w.id));
}
// Close other tabs
let tabIds = assertDefined(sourceWindow.tabs).map(t => assertDefined(t.id)).filter(id => id !== sourceTab.id);
browser.tabs.remove(tabIds);
} | Fix "close all tabs" closing the popup | Fix "close all tabs" closing the popup
| TypeScript | agpl-3.0 | JannesMeyer/TabAttack,JannesMeyer/TabAttack,JannesMeyer/TabAttack | ---
+++
@@ -10,6 +10,7 @@
// Close other windows
for (let w of windows) {
if (w === sourceWindow) { continue; }
+ if (w.type === 'popup') { continue; }
browser.windows.remove(assertDefined(w.id));
}
// Close other tabs |
93a29d5722aa54a4b26502a999c1788ee33d84b0 | src/pages/item/index.ts | src/pages/item/index.ts | import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HackerNewsApi } from '../../services/api';
@inject(Router, HackerNewsApi)
export class Item {
id: number;
item: any;
comments: any[];
private readonly router: Router;
private readonly api: HackerNewsApi;
constructor(router: Router, api: HackerNewsApi) {
this.router = router;
this.api = api;
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.id === undefined || isNaN(params.id) || params.id < 0) {
this.router.navigateToRoute('news');
return;
}
this.id = params.id;
this.comments = [];
this.item = await this.api.fetchItem(this.id);
if (this.item.kids !== undefined && this.item.kids.length >= 1) {
this.comments = await this.api.fetchItems(this.item.kids);
}
}
}
| import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { HackerNewsApi } from '../../services/api';
@inject(Router, HackerNewsApi)
export class Item {
item: any;
comments: any[];
private readonly router: Router;
private readonly api: HackerNewsApi;
constructor(router: Router, api: HackerNewsApi) {
this.router = router;
this.api = api;
}
async activate(params: any): Promise<void> {
window.scrollTo(0, 0);
if (params.id === undefined || isNaN(params.id) || params.id < 0) {
this.router.navigateToRoute('news');
return;
}
this.comments = [];
this.item = await this.api.fetchItem(params.id);
if (this.item.kids !== undefined && this.item.kids.length >= 1) {
this.comments = await this.api.fetchItems(this.item.kids);
}
}
}
| Remove unnecessary class level variable in item page | Remove unnecessary class level variable in item page
| TypeScript | isc | michaelbull/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news,michaelbull/aurelia-hacker-news,MikeBull94/aurelia-hacker-news | ---
+++
@@ -4,7 +4,6 @@
@inject(Router, HackerNewsApi)
export class Item {
- id: number;
item: any;
comments: any[];
@@ -24,10 +23,8 @@
return;
}
- this.id = params.id;
this.comments = [];
-
- this.item = await this.api.fetchItem(this.id);
+ this.item = await this.api.fetchItem(params.id);
if (this.item.kids !== undefined && this.item.kids.length >= 1) {
this.comments = await this.api.fetchItems(this.item.kids); |
cc7416d8713f67d4e31843ce4e00b4889ee4ec0c | angular-typescript-webpack-jasmine/src/modules/application/angular/components/twitterApplication/TwitterApplicationComponent.ts | angular-typescript-webpack-jasmine/src/modules/application/angular/components/twitterApplication/TwitterApplicationComponent.ts | export class TwitterApplicationComponent implements ng.IComponentOptions {
public template: string = `
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button"
class="navbar-toggle collapsed"
data-toggle="collapse"
data-target="#navbar"
aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#/">Tweet app</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#/" title="Tweets">Tweets</a></li>
<li><a href="#/about" title="About">About</a></li>
</ul>
</div>
</div>
</nav>
<div ng-view></div>`;
} | export class TwitterApplicationComponent implements ng.IComponentOptions {
public template: string = `
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button"
class="navbar-toggle collapsed"
data-toggle="collapse"
data-target="#navbar"
aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#/">Tweet app</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#/" title="Tweets">Tweets</a></li>
<li><a href="#/about" title="About">About</a></li>
</ul>
</div>
</div>
</nav>
<div ng-view></div>`;
}
| Delete useless trailing white spaces | Delete useless trailing white spaces
| TypeScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -3,11 +3,11 @@
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
- <button type="button"
- class="navbar-toggle collapsed"
- data-toggle="collapse"
- data-target="#navbar"
- aria-expanded="false"
+ <button type="button"
+ class="navbar-toggle collapsed"
+ data-toggle="collapse"
+ data-target="#navbar"
+ aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span> |
a35351453d050d945f9b205bcfeb99a59c62ac07 | src/selfupdater.ts | src/selfupdater.ts | import fs from './fs';
import { Controller, Events } from './controller';
import { ControllerWrapper } from './controller-wrapper';
import { Manifest } from './data';
export abstract class SelfUpdater {
static async attach(manifestFile: string): Promise<SelfUpdaterInstance> {
const manifestStr = await fs.readFile(manifestFile, 'utf8');
const manifest: Manifest = JSON.parse(manifestStr);
if (!manifest.runningInfo) {
throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`);
}
const controller = new Controller(manifest.runningInfo.port, {
process: manifest.runningInfo.pid,
keepConnected: true,
});
controller.connect();
return new SelfUpdaterInstance(controller);
}
}
export type SelfUpdaterEvents = Events;
export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> {
constructor(controller: Controller) {
super(controller);
}
async checkForUpdates(options?: { authToken?: string; metadata?: string }) {
options = options || {};
const result = await this.controller.sendCheckForUpdates(
'',
'',
options.authToken,
options.metadata
);
return result.success;
}
async updateBegin() {
const result = await this.controller.sendUpdateBegin();
return result.success;
}
async updateApply() {
const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2));
return result.success;
}
}
| import fs from './fs';
import { Controller, Events } from './controller';
import { ControllerWrapper } from './controller-wrapper';
import { Manifest } from './data';
export abstract class SelfUpdater {
static async attach(manifestFile: string): Promise<SelfUpdaterInstance> {
const manifestStr = await fs.readFile(manifestFile, 'utf8');
const manifest: Manifest = JSON.parse(manifestStr);
if (!manifest.runningInfo) {
throw new Error(`Manifest doesn't have a running info, cannot connect to self updater`);
}
const controller = new Controller(manifest.runningInfo.port, {
process: manifest.runningInfo.pid,
keepConnected: true,
});
controller.connect();
return new SelfUpdaterInstance(controller);
}
}
export type SelfUpdaterEvents = Events;
export class SelfUpdaterInstance extends ControllerWrapper<SelfUpdaterEvents> {
constructor(controller: Controller) {
super(controller);
}
async checkForUpdates(options?: { authToken?: string; metadata?: string }) {
options = options || {};
const result = await this.controller.sendCheckForUpdates(
'',
'',
options.authToken,
options.metadata
);
return result;
}
async updateBegin() {
const result = await this.controller.sendUpdateBegin();
return result;
}
async updateApply() {
const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2));
return result;
}
}
| Return the actual results from the self updater | Return the actual results from the self updater
The caller will find it very useful to have the actual response to handle error cases on its own
| TypeScript | mit | gamejolt/client-voodoo,gamejolt/client-voodoo | ---
+++
@@ -37,16 +37,16 @@
options.authToken,
options.metadata
);
- return result.success;
+ return result;
}
async updateBegin() {
const result = await this.controller.sendUpdateBegin();
- return result.success;
+ return result;
}
async updateApply() {
const result = await this.controller.sendUpdateApply(process.env, process.argv.slice(2));
- return result.success;
+ return result;
}
} |
59cfa7d492f7109e89ab8fd7860c0430f262a4fa | models/params/daum-param.ts | models/params/daum-param.ts | import { ParserParam } from '../parser-param';
const parserParam: ParserParam = {
type: 'daum',
url: 'http://www.daum.net',
querySelector: 'ol.list_hotissue > li .rank_cont:not([aria-hidden])',
parserSelector: ($, elem) => {
const data = $(elem);
return {
title: data.find('.txt_issue > a').attr('title'),
rank: '',
status: data.find('em.rank_result .ir_wa').text(),
value: data.find('em.rank_result').text().replace(/[^0-9]/g, ''),
};
},
};
export default parserParam;
| import { ParserParam } from '../parser-param';
const parserParam: ParserParam = {
type: 'daum',
url: 'http://www.daum.net',
querySelector:
'.hotissue_layer .list_hotissue.issue_row:not(.list_mini) > li .rank_cont[aria-hidden=true]',
parserSelector: ($, elem) => {
const data = $(elem);
return {
title: data.find('.txt_issue > a.link_issue:first-child').text(),
rank: '',
status: data.find('.rank_result .ico_pctop .ir_wa').text(),
value: data.find('.rank_result').text().replace(/[^0-9]/g, ''),
};
},
};
export default parserParam;
| Change parser params for changed daum html structure | Change parser params for changed daum html structure
| TypeScript | mit | endlessdev/rankr,endlessdev/rankr | ---
+++
@@ -3,14 +3,15 @@
const parserParam: ParserParam = {
type: 'daum',
url: 'http://www.daum.net',
- querySelector: 'ol.list_hotissue > li .rank_cont:not([aria-hidden])',
+ querySelector:
+ '.hotissue_layer .list_hotissue.issue_row:not(.list_mini) > li .rank_cont[aria-hidden=true]',
parserSelector: ($, elem) => {
const data = $(elem);
return {
- title: data.find('.txt_issue > a').attr('title'),
+ title: data.find('.txt_issue > a.link_issue:first-child').text(),
rank: '',
- status: data.find('em.rank_result .ir_wa').text(),
- value: data.find('em.rank_result').text().replace(/[^0-9]/g, ''),
+ status: data.find('.rank_result .ico_pctop .ir_wa').text(),
+ value: data.find('.rank_result').text().replace(/[^0-9]/g, ''),
};
},
}; |
5df222f4164f2695bd2f9ee858691fd1647c1022 | src/helpers.ts | src/helpers.ts | import * as vscode from 'vscode';
import { readFile } from 'fs';
export function isTerraformDocument(document: vscode.TextDocument): boolean {
return document.languageId === "terraform";
}
export function read(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
readFile(path, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.toString('utf8'));
}
});
});
} | import * as vscode from 'vscode';
import { readFile } from 'fs';
export function isTerraformDocument(document: vscode.TextDocument): boolean {
return document.languageId === "terraform";
}
export function read(path: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
readFile(path, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.toString('utf8'));
}
});
});
}
export function uriFromRelativePath(path: string, folder?: vscode.WorkspaceFolder): vscode.Uri {
if (!folder) {
folder = vscode.workspace.workspaceFolders[0];
}
return folder.uri.with({
path: [folder.uri.path, path].join('/')
});
} | Add a helper which returns an Uri to a path relative to the workspace | Add a helper which returns an Uri to a path relative to the workspace
| TypeScript | mpl-2.0 | hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform | ---
+++
@@ -16,3 +16,13 @@
});
});
}
+
+export function uriFromRelativePath(path: string, folder?: vscode.WorkspaceFolder): vscode.Uri {
+ if (!folder) {
+ folder = vscode.workspace.workspaceFolders[0];
+ }
+
+ return folder.uri.with({
+ path: [folder.uri.path, path].join('/')
+ });
+} |
119dc902b34599dd92788fc7a551d5deb80c5c6a | src/shared/components/iframeLoader/IFrameLoader.tsx | src/shared/components/iframeLoader/IFrameLoader.tsx | import * as React from 'react';
import {ThreeBounce} from 'better-react-spinkit';
import LoadingIndicator from "../loadingIndicator/LoadingIndicator";
import {observer} from "mobx-react";
import {observable} from "mobx";
import autobind from "autobind-decorator";
@observer
export default class IFrameLoader extends React.Component<{ url:string; iframeId?:string; height:number }, {}> {
@observable iframeLoaded = false;
@autobind
private onLoad() {
this.iframeLoaded = true;
}
//NOTE: we need zindex to be higher than that of global loader
render(){
return (
<div style={{position:'relative'}}>
<LoadingIndicator center={true} size={"big"} isLoading={!this.iframeLoaded} />
<iframe id={this.props.iframeId||""}
style={{ width:'100%', position:'relative', zIndex:100, height:this.props.height, border:'none'}}
src={this.props.url}
onLoad={this.onLoad}
>
</iframe>
</div>
)
}
} | import * as React from 'react';
import {ThreeBounce} from 'better-react-spinkit';
import LoadingIndicator from "../loadingIndicator/LoadingIndicator";
import {observer} from "mobx-react";
import {observable} from "mobx";
import autobind from "autobind-decorator";
@observer
export default class IFrameLoader extends React.Component<{ url:string; className?:string; iframeId?:string; height?:number }, {}> {
@observable iframeLoaded = false;
@autobind
private onLoad() {
this.iframeLoaded = true;
}
//NOTE: we need zindex to be higher than that of global loader
render(){
return (
<div style={{position:'relative'}}>
<LoadingIndicator center={true} size={"big"} isLoading={!this.iframeLoaded} />
<iframe id={this.props.iframeId||""}
className={this.props.className||""}
style={{ width:'100%', position:'relative', zIndex:100, height:this.props.height, border:'none'}}
src={this.props.url}
onLoad={this.onLoad}
>
</iframe>
</div>
)
}
} | Allow for CSS class name assigned to iframe | Allow for CSS class name assigned to iframe
Signed-off-by: Chris Wakefield <cwakefield@mdanderson.org>
Former-commit-id: 3364aa94ede3e20d84cb8da544ae1f81df20f4f2 | TypeScript | agpl-3.0 | cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend | ---
+++
@@ -6,7 +6,7 @@
import autobind from "autobind-decorator";
@observer
-export default class IFrameLoader extends React.Component<{ url:string; iframeId?:string; height:number }, {}> {
+export default class IFrameLoader extends React.Component<{ url:string; className?:string; iframeId?:string; height?:number }, {}> {
@observable iframeLoaded = false;
@@ -22,6 +22,7 @@
<LoadingIndicator center={true} size={"big"} isLoading={!this.iframeLoaded} />
<iframe id={this.props.iframeId||""}
+ className={this.props.className||""}
style={{ width:'100%', position:'relative', zIndex:100, height:this.props.height, border:'none'}}
src={this.props.url}
onLoad={this.onLoad} |
2e940fc4a2ab6b85f6065a84e6fe2950160abb69 | queries.test.ts | queries.test.ts | import { sslTest, dnssec, headers, dmarcSpf } from './queries';
import test from 'ava';
test('SSL positive', async t => {
const result = await sslTest({ host: 'google.com' });
t.is(result.endpoints.length, 2);
t.is(result.endpoints[0].grade, 'A');
t.is(result.endpoints[1].grade, 'A');
t.true(result.endpoints[0].details.supportsAlpn);
t.true(result.endpoints[1].details.supportsAlpn);
});
test('DNSSEC positive', async t => {
const result = await dnssec({ host: 'verisigninc.com' });
t.true(result.secure);
});
test('DNSSEC negative', async t => {
const result = await dnssec({ host: 'google.com' });
t.false(result.secure);
});
test('Security headers positive', async t => {
const result = await headers({ url: 'https://securityheaders.io' });
const sts = result.get('strict-transport-security');
if (!sts) {
t.fail('STS header should be set.');
} else {
t.true('preload' in sts);
t.true('includeSubDomains' in sts);
t.true(Number(sts['max-age']) >= 31536000);
}
});
test('DMARC/SPF positive', async t => {
t.true(await dmarcSpf({ hostname: 'valimail.com' }));
});
| import { sslTest, dnssec, headers, dmarcSpf } from './queries';
import test from 'ava';
test('SSL positive', async t => {
const result = await sslTest({ host: 'google.com' });
t.is(result.endpoints.length, 2);
t.is(result.endpoints[0].grade, 'B');
t.is(result.endpoints[1].grade, 'B');
t.true(result.endpoints[0].details.supportsAlpn);
t.true(result.endpoints[1].details.supportsAlpn);
});
test('DNSSEC positive', async t => {
const result = await dnssec({ host: 'verisigninc.com' });
t.true(result.secure);
});
test('DNSSEC negative', async t => {
const result = await dnssec({ host: 'google.com' });
t.false(result.secure);
});
test('Security headers positive', async t => {
const result = await headers({ url: 'https://securityheaders.io' });
const sts = result.get('strict-transport-security');
if (!sts) {
t.fail('STS header should be set.');
} else {
t.true('preload' in sts);
t.true('includeSubDomains' in sts);
t.true(Number(sts['max-age']) >= 31536000);
}
});
test('DMARC/SPF positive', async t => {
t.true(await dmarcSpf({ hostname: 'valimail.com' }));
});
| Change SSLLabs grade for google.com to B | Change SSLLabs grade for google.com to B
Google supports TLS 1.0 and 1.1 so the grade is capped to B.
See: https://blog.qualys.com/ssllabs/2018/11/19/grade-change-for-tls-1-0-and-tls-1-1-protocols
| TypeScript | apache-2.0 | wiktor-k/infrastructure-tests | ---
+++
@@ -5,8 +5,8 @@
test('SSL positive', async t => {
const result = await sslTest({ host: 'google.com' });
t.is(result.endpoints.length, 2);
- t.is(result.endpoints[0].grade, 'A');
- t.is(result.endpoints[1].grade, 'A');
+ t.is(result.endpoints[0].grade, 'B');
+ t.is(result.endpoints[1].grade, 'B');
t.true(result.endpoints[0].details.supportsAlpn);
t.true(result.endpoints[1].details.supportsAlpn);
}); |
d628a4b1fe9b8b5eb3de2cd969e5810c7a9cea55 | packages/schematics/src/scam/index.ts | packages/schematics/src/scam/index.ts | import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
const project = getProject(tree, options.project);
const modulePath = findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
});
tree.read(modulePath);
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
import { Schema as NgComponentOptions } from '@schematics/angular/component/schema';
import { findModuleFromOptions } from '@schematics/angular/utility/find-module';
import { buildDefaultPath, getProject } from '@schematics/angular/utility/project';
export interface ScamOptions extends NgComponentOptions {
separateModule: boolean;
}
export const _mergeModuleIntoComponentFile: (options: ScamOptions) => Rule = (options) => (tree, context) => {
const project = getProject(tree, options.project);
const modulePath = findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
});
tree.read(modulePath);
// @todo: read module content.
// @todo: merge module content in component.
// @todo: remove module file.
return tree;
};
export function scam(options: ScamOptions): Rule {
let ruleList = [
externalSchematic('@schematics/angular', 'module', options),
externalSchematic('@schematics/angular', 'component', {
...options,
export: true,
module: options.name
})
];
if (!options.separateModule) {
ruleList = [
...ruleList,
_mergeModuleIntoComponentFile(options)
];
}
return chain(ruleList);
}
| Merge module and component as default behavior. | @wishtack/schematics:scam: Merge module and component as default behavior.
| TypeScript | mit | wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids | ---
+++
@@ -17,6 +17,10 @@
});
tree.read(modulePath);
+
+ // @todo: read module content.
+ // @todo: merge module content in component.
+ // @todo: remove module file.
return tree;
|
a70e971459bc168888c11e24f0e081488521b277 | src/main/ts/app.ts | src/main/ts/app.ts | import * as $ from 'jquery';
window['jQuery'] = $;
import 'foundation-sites';
class MixitApp{
bootstrap(){
this._initServiceWorker();
}
_initServiceWorker() {
let isLocalhost = Boolean(window.location.hostname === 'localhost' ||
window.location.hostname === '[::1]' ||
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
if (typeof registration.update === 'function') {
registration.update();
}
registration.onupdatefound = function() {
if (navigator.serviceWorker.controller) {
var installingWorker = registration.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
console.error('New content is available; please refresh.');
break;
case 'redundant':
throw new Error('The installing service worker became redundant.');
default:
// Ignore
}
};
}
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}
}
}
new MixitApp().bootstrap();
$(() => {
$(document).foundation();
}); | import * as $ from 'jquery';
window['jQuery'] = $;
import 'foundation-sites';
class MixitApp{
bootstrap(){
//this._initServiceWorker();
}
_initServiceWorker() {
let isLocalhost = Boolean(window.location.hostname === 'localhost' ||
window.location.hostname === '[::1]' ||
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) {
navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
if (typeof registration.update === 'function') {
registration.update();
}
registration.onupdatefound = function() {
if (navigator.serviceWorker.controller) {
var installingWorker = registration.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
console.error('New content is available; please refresh.');
break;
case 'redundant':
throw new Error('The installing service worker became redundant.');
default:
// Ignore
}
};
}
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}
}
}
new MixitApp().bootstrap();
$(() => {
$(document).foundation();
}); | Disable service workers for now | Disable service workers for now
That allows to fix dev mode with Chrome
| TypeScript | apache-2.0 | mixitconf/mixit,mix-it/mixit,mix-it/mixit,mix-it/mixit,mixitconf/mixit,mixitconf/mixit,sdeleuze/mixit,mix-it/mixit,mix-it/mixit,mixitconf/mixit,sdeleuze/mixit,sdeleuze/mixit,sdeleuze/mixit | ---
+++
@@ -4,7 +4,7 @@
class MixitApp{
bootstrap(){
- this._initServiceWorker();
+ //this._initServiceWorker();
}
_initServiceWorker() { |
492627d6efba71445236791ffbeb2a8ab75eb32c | frontend/src/app/app.component.ts | frontend/src/app/app.component.ts | import { Component, Inject } from '@angular/core'
import { TranslateService } from '@ngx-translate/core'
import { Title } from '@angular/platform-browser'
import { DOCUMENT } from '@angular/common'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor (@Inject(DOCUMENT) private _document: HTMLDocument, private titleService: Title, private translate: TranslateService) {
this.translate.setDefaultLang('en')
}
setTitle (newTitle: string) {
this.titleService.setTitle(newTitle)
}
}
| import { Component, Inject } from '@angular/core'
import { TranslateService } from '@ngx-translate/core'
import { DOCUMENT } from '@angular/common'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor (@Inject(DOCUMENT) private _document: HTMLDocument, private translate: TranslateService) {
this.translate.setDefaultLang('en')
}
}
| Remove unused frontend-side title change | Remove unused frontend-side title change
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -1,6 +1,5 @@
import { Component, Inject } from '@angular/core'
import { TranslateService } from '@ngx-translate/core'
-import { Title } from '@angular/platform-browser'
import { DOCUMENT } from '@angular/common'
@Component({
@@ -10,11 +9,7 @@
})
export class AppComponent {
- constructor (@Inject(DOCUMENT) private _document: HTMLDocument, private titleService: Title, private translate: TranslateService) {
+ constructor (@Inject(DOCUMENT) private _document: HTMLDocument, private translate: TranslateService) {
this.translate.setDefaultLang('en')
}
-
- setTitle (newTitle: string) {
- this.titleService.setTitle(newTitle)
- }
} |
81e61986526d2106553dccc477183ac65ecfcf70 | ts/util/findAndFormatContact.ts | ts/util/findAndFormatContact.ts | // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { ConversationType } from '../state/ducks/conversations';
import { format, isValidNumber } from '../types/PhoneNumber';
type FormattedContact = Partial<ConversationType> &
Pick<
ConversationType,
| 'acceptedMessageRequest'
| 'id'
| 'isMe'
| 'sharedGroupNames'
| 'title'
| 'type'
| 'unblurredAvatarPath'
>;
const PLACEHOLDER_CONTACT: FormattedContact = {
acceptedMessageRequest: false,
id: 'placeholder-contact',
isMe: false,
sharedGroupNames: [],
title: window.i18n('unknownContact'),
type: 'direct',
};
export function findAndFormatContact(identifier?: string): FormattedContact {
if (!identifier) {
return PLACEHOLDER_CONTACT;
}
const contactModel = window.ConversationController.get(identifier);
if (contactModel) {
return contactModel.format();
}
const regionCode = window.storage.get('regionCode');
if (!isValidNumber(identifier, { regionCode })) {
return PLACEHOLDER_CONTACT;
}
const phoneNumber = format(identifier, { ourRegionCode: regionCode });
return {
acceptedMessageRequest: false,
id: 'phone-only',
isMe: false,
phoneNumber,
sharedGroupNames: [],
title: phoneNumber,
type: 'direct',
};
}
| // Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { ConversationType } from '../state/ducks/conversations';
import { format, isValidNumber } from '../types/PhoneNumber';
import { normalizeUuid } from './normalizeUuid';
type FormattedContact = Partial<ConversationType> &
Pick<
ConversationType,
| 'acceptedMessageRequest'
| 'id'
| 'isMe'
| 'sharedGroupNames'
| 'title'
| 'type'
| 'unblurredAvatarPath'
>;
const PLACEHOLDER_CONTACT: FormattedContact = {
acceptedMessageRequest: false,
id: 'placeholder-contact',
isMe: false,
sharedGroupNames: [],
title: window.i18n('unknownContact'),
type: 'direct',
};
export function findAndFormatContact(identifier?: string): FormattedContact {
if (!identifier) {
return PLACEHOLDER_CONTACT;
}
const contactModel = window.ConversationController.get(
normalizeUuid(identifier, 'findAndFormatContact')
);
if (contactModel) {
return contactModel.format();
}
const regionCode = window.storage.get('regionCode');
if (!isValidNumber(identifier, { regionCode })) {
return PLACEHOLDER_CONTACT;
}
const phoneNumber = format(identifier, { ourRegionCode: regionCode });
return {
acceptedMessageRequest: false,
id: 'phone-only',
isMe: false,
phoneNumber,
sharedGroupNames: [],
title: phoneNumber,
type: 'direct',
};
}
| Normalize UUID for formatting contact | Normalize UUID for formatting contact
| TypeScript | agpl-3.0 | nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop | ---
+++
@@ -3,6 +3,7 @@
import { ConversationType } from '../state/ducks/conversations';
import { format, isValidNumber } from '../types/PhoneNumber';
+import { normalizeUuid } from './normalizeUuid';
type FormattedContact = Partial<ConversationType> &
Pick<
@@ -30,7 +31,9 @@
return PLACEHOLDER_CONTACT;
}
- const contactModel = window.ConversationController.get(identifier);
+ const contactModel = window.ConversationController.get(
+ normalizeUuid(identifier, 'findAndFormatContact')
+ );
if (contactModel) {
return contactModel.format();
} |
31656424ba71ff0ac16a4d54d39b679481dbf2dc | src/extension.ts | src/extension.ts | 'use strict';
import * as vscode from 'vscode';
import cp = require('child_process');
import path = require('path');
export function activate(context: vscode.ExtensionContext) {
let p8Config = vscode.workspace.getConfiguration('pico8');
let disposable = vscode.commands.registerTextEditorCommand('pico8.run', (textEditor: vscode.TextEditor) => {
let fileName = textEditor.document.fileName;
cp.execFile(p8Config['executablePath'], ["-windowed", "1", "-run", fileName], { env: process.env }, (err, stdout, stderr) => {
if (err) {
console.log(err);
}
})
});
context.subscriptions.push(disposable);
} | 'use strict';
import * as vscode from 'vscode';
import cp = require('child_process');
import path = require('path');
export function activate(context: vscode.ExtensionContext) {
let p8Config = vscode.workspace.getConfiguration('pico8');
let disposable = vscode.commands.registerTextEditorCommand('pico8.run', (textEditor: vscode.TextEditor) => {
let fileName = textEditor.document.fileName;
let args = ["-windowed", "1", "-run", fileName];
let workspace = vscode.workspace;
if (workspace) {
args.push("-home", workspace.rootPath);
}
cp.execFile(p8Config['executablePath'], args, { env: process.env }, (err, stdout, stderr) => {
if (err) {
console.log(err);
}
})
});
context.subscriptions.push(disposable);
} | Set pico8 home if in workspace mode | Set pico8 home if in workspace mode
| TypeScript | mit | joho/pico8-vscode | ---
+++
@@ -11,8 +11,14 @@
let disposable = vscode.commands.registerTextEditorCommand('pico8.run', (textEditor: vscode.TextEditor) => {
let fileName = textEditor.document.fileName;
+ let args = ["-windowed", "1", "-run", fileName];
- cp.execFile(p8Config['executablePath'], ["-windowed", "1", "-run", fileName], { env: process.env }, (err, stdout, stderr) => {
+ let workspace = vscode.workspace;
+ if (workspace) {
+ args.push("-home", workspace.rootPath);
+ }
+
+ cp.execFile(p8Config['executablePath'], args, { env: process.env }, (err, stdout, stderr) => {
if (err) {
console.log(err);
} |
e451fe20666250961c4e8df81cf5d5e6b280010e | src/routes/http.ts | src/routes/http.ts | import * as http from 'http';
import * as https from 'https';
export default {
test: (uri: string): boolean => /^https*:\/\//.test(uri),
read: (url: string): Promise<http.IncomingMessage> => {
return new Promise((resolve, reject) => {
const get = url.indexOf('https') === 0 ? https.get : http.get;
// @ts-ignore
get(url, (res) => {
const statusCode = res['statusCode'];
const contentType = res['headers']['content-type'];
if (statusCode === 200 && contentType.indexOf('audio/mpeg') > -1) {
resolve(res);
} else {
reject({
statusCode: statusCode,
contentType: contentType
});
}
});
});
}
}
| import * as http from 'http';
import * as https from 'https';
export default {
test: (uri: string): boolean => /^https*:\/\//.test(uri),
read: (url: string): Promise<http.IncomingMessage> => {
return new Promise((resolve, reject) => {
const get = url.indexOf('https') === 0 ? https.get : http.get;
let res_ = null;
const onError = (err) => {
if (res_) {
res_.emit('error', err);
}
};
const clientRequest = get(url, (res) => {
const statusCode = res['statusCode'];
const contentType = res['headers']['content-type'];
if (statusCode === 200 && contentType.indexOf('audio/mpeg') > -1) {
const onEnd = () => {
clientRequest.off('error', onError);
res.off('end', onEnd);
};
res.on('end', onEnd);
res_ = res;
resolve(res);
} else {
reject({
statusCode: statusCode,
contentType: contentType
});
}
});
clientRequest.on('error', onError);
});
},
};
| Fix uncaught exception in request | Fix uncaught exception in request
| TypeScript | mit | kicumkicum/stupid-player,kicumkicum/stupid-player | ---
+++
@@ -8,12 +8,27 @@
return new Promise((resolve, reject) => {
const get = url.indexOf('https') === 0 ? https.get : http.get;
- // @ts-ignore
- get(url, (res) => {
+ let res_ = null;
+
+ const onError = (err) => {
+ if (res_) {
+ res_.emit('error', err);
+ }
+ };
+
+ const clientRequest = get(url, (res) => {
const statusCode = res['statusCode'];
const contentType = res['headers']['content-type'];
if (statusCode === 200 && contentType.indexOf('audio/mpeg') > -1) {
+ const onEnd = () => {
+ clientRequest.off('error', onError);
+ res.off('end', onEnd);
+ };
+
+ res.on('end', onEnd);
+ res_ = res;
+
resolve(res);
} else {
reject({
@@ -22,6 +37,8 @@
});
}
});
+
+ clientRequest.on('error', onError);
});
- }
-}
+ },
+}; |
e08d27b016895b0cd200729169c918b152b038cc | src/kaptan.ts | src/kaptan.ts | import { EventEmitter } from 'events';
import { Logger } from './util';
import { ServiceConstructor, ServiceContainer } from './service';
export class Kaptan extends EventEmitter {
public readonly logger: Logger;
public readonly services: ServiceContainer;
constructor(label: string = 'kaptan') {
super();
this.logger = new Logger(label);
this.services = new ServiceContainer(this);
}
public use(service: ServiceConstructor, options: {[key:string]: any} = {}) {
if (!service.Options) {
service.Options = {};
}
service.Options = { ...service.Options, ...options };
this.services.add(service);
}
public start() {
this.services.spawn();
}
}
| import { EventEmitter } from 'events';
import { Logger } from './util';
import { Service, ServiceConstructor, ServiceContainer } from './service';
export class Kaptan extends EventEmitter {
public readonly logger: Logger;
public readonly services: ServiceContainer;
constructor(label: string = 'kaptan') {
super();
this.logger = new Logger(label);
this.services = new ServiceContainer(this);
}
public use(service: ServiceConstructor, options: {[key:string]: any} = {}) {
service = Service.copy(Service.getServiceName(service), service);
if (!service.Options) {
service.Options = {};
}
service.Options = { ...service.Options, ...options };
this.services.add(service);
}
public start() {
this.services.spawn();
}
}
| Add duplicate service to the services instead of the original one | Add duplicate service to the services instead of the original one
| TypeScript | mit | ibrahimduran/node-kaptan | ---
+++
@@ -1,7 +1,7 @@
import { EventEmitter } from 'events';
import { Logger } from './util';
-import { ServiceConstructor, ServiceContainer } from './service';
+import { Service, ServiceConstructor, ServiceContainer } from './service';
export class Kaptan extends EventEmitter {
public readonly logger: Logger;
@@ -15,6 +15,8 @@
}
public use(service: ServiceConstructor, options: {[key:string]: any} = {}) {
+ service = Service.copy(Service.getServiceName(service), service);
+
if (!service.Options) {
service.Options = {};
} |
c98447f603324ca0e31abbb4e7d6aa83976ce529 | webapp/source/plugins-for-local-libre-or-standard-services/chat-text/chat-text-plugin.ts | webapp/source/plugins-for-local-libre-or-standard-services/chat-text/chat-text-plugin.ts | "use strict";
import m = require("mithril");
export function initialize() {
console.log("Chat Text plugin initialized");
}
function displayChatLog() {
return m("div", "Chat log goes here");
}
function displayChatEntry() {
return m("div", "Chat entry goes here");
}
export function display() {
return m("div.chatTextPlugin", [
m("hr"),
m("strong", "Chat Text plugin"), m("br"),
displayChatLog(),
displayChatEntry()
]);
} | "use strict";
import m = require("mithril");
export function initialize() {
console.log("Chat Text plugin initialized");
}
var messages = [];
function displayChatLog() {
return m("div", [
"Chat log:", m("br"),
messages.map((message) => {
return m("div.message", message);
})
]);
}
function sendMessage() {
console.log("send message", currentMessage);
messages.push(currentMessage);
currentMessage = ""
}
function currentMessageChanged(message) {
currentMessage = message;
}
var currentMessage = "";
function inputKeyPress(event) {
var keycode = event.keycode || event.which || 0;
// console.log("inputKeyPress", keycode);
if (keycode === 13) {
event.preventDefault();
return sendMessage();
}
// Do not redraw for a character press as currentMessage will be out of sync with input field
m.redraw.strategy("none");
}
function displayChatEntry() {
return m("div", [
"Message:",
m("input", {
value: currentMessage,
onchange: m.withAttr("value", currentMessageChanged),
onkeyup: inputKeyPress,
size: "80"
}),
m("button", {onclick: sendMessage}, "Send!")
]
);
}
export function display() {
return m("div.chatTextPlugin", [
m("hr"),
m("strong", "Chat Text plugin"), m("br"),
displayChatLog(),
displayChatEntry()
]);
} | Improve text chat plugin so can enter and send (test local) messages | Improve text chat plugin so can enter and send (test local) messages | TypeScript | mpl-2.0 | pdfernhout/Twirlip2,pdfernhout/Twirlip2,pdfernhout/Twirlip2 | ---
+++
@@ -6,12 +6,52 @@
console.log("Chat Text plugin initialized");
}
+var messages = [];
+
function displayChatLog() {
- return m("div", "Chat log goes here");
+ return m("div", [
+ "Chat log:", m("br"),
+ messages.map((message) => {
+ return m("div.message", message);
+ })
+ ]);
}
+function sendMessage() {
+ console.log("send message", currentMessage);
+ messages.push(currentMessage);
+ currentMessage = ""
+}
+
+function currentMessageChanged(message) {
+ currentMessage = message;
+}
+
+var currentMessage = "";
+
+function inputKeyPress(event) {
+ var keycode = event.keycode || event.which || 0;
+ // console.log("inputKeyPress", keycode);
+ if (keycode === 13) {
+ event.preventDefault();
+ return sendMessage();
+ }
+ // Do not redraw for a character press as currentMessage will be out of sync with input field
+ m.redraw.strategy("none");
+}
+
function displayChatEntry() {
- return m("div", "Chat entry goes here");
+ return m("div", [
+ "Message:",
+ m("input", {
+ value: currentMessage,
+ onchange: m.withAttr("value", currentMessageChanged),
+ onkeyup: inputKeyPress,
+ size: "80"
+ }),
+ m("button", {onclick: sendMessage}, "Send!")
+ ]
+ );
}
export function display() { |
f2fd894c8d20b8dbded062442fdcb402f0192cd5 | index.d.ts | index.d.ts | declare namespace MessageFormat {
type Msg = { (params: {}): string; toString(global?: string): string };
type Formatter = (val: any, lc: string, arg?: string) => string;
type SrcMessage = string | SrcObject;
interface SrcObject {
[key: string]: SrcMessage;
}
}
declare class MessageFormat {
constructor(message: { [pluralFuncs: string]: Function });
constructor(message: string[]);
constructor(message: string);
constructor();
addFormatters: (format: { [name: string]: MessageFormat.Formatter }) => this;
disablePluralKeyChecks: () => this;
setBiDiSupport: (enable: boolean) => this;
setStrictNumberSign: (enable: boolean) => this;
compile: (messages: MessageFormat.SrcMessage, locale?: string) => MessageFormat.Msg;
}
export = MessageFormat;
| declare namespace MessageFormat {
type Msg = { (params: {}): string; toString(global?: string): string };
type Formatter = (val: any, lc: string, arg?: string) => string;
type SrcMessage = string | SrcObject;
interface SrcObject {
[key: string]: SrcMessage;
}
}
declare class MessageFormat {
constructor(
message?: { [pluralFuncs: string]: Function } | string[] | string
);
addFormatters: (format: { [name: string]: MessageFormat.Formatter }) => this;
disablePluralKeyChecks: () => this;
setBiDiSupport: (enable: boolean) => this;
setStrictNumberSign: (enable: boolean) => this;
compile: (messages: MessageFormat.SrcMessage, locale?: string) => MessageFormat.Msg;
}
export = MessageFormat;
| Use type union parameter for MessageFormat constructor | Use type union parameter for MessageFormat constructor | TypeScript | mit | SlexAxton/messageformat.js,SlexAxton/messageformat.js,eemeli/messageformat.js,messageformat/messageformat.js,messageformat/messageformat.js,eemeli/messageformat.js | ---
+++
@@ -9,10 +9,9 @@
}
declare class MessageFormat {
- constructor(message: { [pluralFuncs: string]: Function });
- constructor(message: string[]);
- constructor(message: string);
- constructor();
+ constructor(
+ message?: { [pluralFuncs: string]: Function } | string[] | string
+ );
addFormatters: (format: { [name: string]: MessageFormat.Formatter }) => this;
disablePluralKeyChecks: () => this;
setBiDiSupport: (enable: boolean) => this; |
fc67aa4ea4a0a996fa4bc3eddd5b955d0f90ddc3 | react-mobx-todos/src/Main.tsx | react-mobx-todos/src/Main.tsx | import * as React from 'react'
import { BrowserRouter } from 'react-router-dom'
import { render } from 'react-dom'
import { Route } from 'react-router'
import { allRoutes } from './routes'
import './main.scss'
render(
<BrowserRouter>
{allRoutes.map(route =>
<Route key={route.routePath} component={route.component} path={route.routePath}/>
)}
</BrowserRouter>,
document.getElementById('app')
) | import * as React from 'react'
import { BrowserRouter } from 'react-router-dom'
import { render } from 'react-dom'
import { Route } from 'react-router'
// import { allRoutes } from './routes'
import { ConnectedApp } from './ConnectedApp'
import './main.scss'
render(
<BrowserRouter>
<div>
<Route exact={true} path="/" component={ConnectedApp}/>
<Route path="/:filter" component={ConnectedApp}/>
{/*{allRoutes.map(route =>
<Route key={route.routePath} component={route.component} path={route.routePath}/>
)}*/}
</div>
</BrowserRouter>,
document.getElementById('app')
) | Make the app show render, but filters still broken | Make the app show render, but filters still broken
| TypeScript | unlicense | janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations,janaagaard75/framework-investigations | ---
+++
@@ -3,15 +3,20 @@
import { render } from 'react-dom'
import { Route } from 'react-router'
-import { allRoutes } from './routes'
+// import { allRoutes } from './routes'
+import { ConnectedApp } from './ConnectedApp'
import './main.scss'
render(
<BrowserRouter>
- {allRoutes.map(route =>
- <Route key={route.routePath} component={route.component} path={route.routePath}/>
- )}
+ <div>
+ <Route exact={true} path="/" component={ConnectedApp}/>
+ <Route path="/:filter" component={ConnectedApp}/>
+ {/*{allRoutes.map(route =>
+ <Route key={route.routePath} component={route.component} path={route.routePath}/>
+ )}*/}
+ </div>
</BrowserRouter>,
document.getElementById('app')
) |
314adcc776fc412762bbf29f8affe36d4f15177d | lib/tasks/Clean.ts | lib/tasks/Clean.ts | import {buildHelper as helper, taskRunner} from "../Container";
import * as del from "del";
export default function Clean() {
return del([helper.getDistFolder(), helper.getTempFolder()], {force: true});
} | import {buildHelper as helper, taskRunner} from "../Container";
import * as del from "del";
export default function Clean() {
return del([helper.getDistFolder(), helper.getTempFolder()]);
} | Remove force delete from clean | Remove force delete from clean
| TypeScript | mit | mtfranchetto/smild,mtfranchetto/smild,mtfranchetto/smild | ---
+++
@@ -2,5 +2,5 @@
import * as del from "del";
export default function Clean() {
- return del([helper.getDistFolder(), helper.getTempFolder()], {force: true});
+ return del([helper.getDistFolder(), helper.getTempFolder()]);
} |
aaf8384f2b353b895ed1727bdd8b977ad4977bd2 | src/Diploms.WebUI/ClientApp/app/departments/components/add/add.component.ts | src/Diploms.WebUI/ClientApp/app/departments/components/add/add.component.ts | import { Component, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'departments-add',
templateUrl: './add.component.html'
})
export class DepartmentsAddComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
"name": ["", Validators.required],
"shortName": [""]
});
}
}
| import { Component, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'departments-add',
templateUrl: './add.component.html'
})
export class DepartmentsAddComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder,
private httpClient: HttpClient) {
this.form = this.formBuilder.group({
"name": ["", Validators.required],
"shortName": [""]
});
}
submit(form:any) {
this.httpClient.put("/api/departments/add", form).subscribe(e=>{});
}
}
| Add submit handler and configure it to send form value to DepartmentController | Add submit handler and configure it to send form value to DepartmentController
| TypeScript | mit | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | ---
+++
@@ -1,5 +1,6 @@
import { Component, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
+import { HttpClient } from '@angular/common/http';
@Component({
selector: 'departments-add',
@@ -8,10 +9,15 @@
export class DepartmentsAddComponent {
form: FormGroup;
- constructor(private formBuilder: FormBuilder) {
+ constructor(private formBuilder: FormBuilder,
+ private httpClient: HttpClient) {
this.form = this.formBuilder.group({
"name": ["", Validators.required],
"shortName": [""]
});
}
+
+ submit(form:any) {
+ this.httpClient.put("/api/departments/add", form).subscribe(e=>{});
+ }
} |
f2a8361832bc7fd26bbbd39957735985b19c1bdd | dashboard/src/components/widget/toggle-button/che-toggle-button.directive.ts | dashboard/src/components/widget/toggle-button/che-toggle-button.directive.ts | /*
* Copyright (c) 2015-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*/
'use strict';
/**
* Defines a directive for a toggle button.
* @author Florent Benoit
*/
export class CheToggleButton {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor () {
this.restrict='E';
this.templateUrl = 'components/widget/toggle-button/che-toggle-button.html';
// scope values
this.scope = {
title:'@cheTitle',
fontIcon: '@cheFontIcon',
ngDisabled: '@ngDisabled'
};
}
link($scope) {
$scope.controller = $scope.$parent.$parent.cheToggleCtrl;
}
}
| /*
* Copyright (c) 2015-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*/
'use strict';
/**
* Defines a directive for a toggle button.
* @author Florent Benoit
*/
export class CheToggleButton {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor () {
this.restrict='E';
this.templateUrl = 'components/widget/toggle-button/che-toggle-button.html';
// scope values
this.scope = {
title:'@cheTitle',
fontIcon: '@cheFontIcon',
ngDisabled: '@ngDisabled'
};
}
link($scope) {
$scope.controller = $scope.$parent.$parent.cheToggleCtrl || $scope.$parent.$parent.$parent.cheToggleCtrl;
}
}
| Fix setting scope of toggle button to work with repeat | Fix setting scope of toggle button to work with repeat
Signed-off-by: Ann Shumilova <c0ede6ced76ec63a297e8c2e1ba28f92de3dd6cf@codenvy.com>
| TypeScript | epl-1.0 | akervern/che,bartlomiej-laczkowski/che,sleshchenko/che,davidfestal/che,bartlomiej-laczkowski/che,Patricol/che,snjeza/che,sunix/che,gazarenkov/che-sketch,sunix/che,cdietrich/che,lehmanju/che,davidfestal/che,TypeFox/che,gazarenkov/che-sketch,gazarenkov/che-sketch,jonahkichwacoders/che,TypeFox/che,TypeFox/che,codenvy/che,cdietrich/che,sleshchenko/che,davidfestal/che,jonahkichwacoders/che,davidfestal/che,snjeza/che,akervern/che,akervern/che,cemalkilic/che,sunix/che,jonahkichwacoders/che,sleshchenko/che,Patricol/che,lehmanju/che,gazarenkov/che-sketch,sudaraka94/che,TypeFox/che,TypeFox/che,akervern/che,Patricol/che,bartlomiej-laczkowski/che,TypeFox/che,gazarenkov/che-sketch,jonahkichwacoders/che,jonahkichwacoders/che,bartlomiej-laczkowski/che,cdietrich/che,lehmanju/che,bartlomiej-laczkowski/che,bartlomiej-laczkowski/che,snjeza/che,bartlomiej-laczkowski/che,sudaraka94/che,TypeFox/che,cdietrich/che,Patricol/che,jonahkichwacoders/che,gazarenkov/che-sketch,lehmanju/che,davidfestal/che,lehmanju/che,cdietrich/che,akervern/che,cemalkilic/che,lehmanju/che,cdietrich/che,cemalkilic/che,TypeFox/che,cdietrich/che,sudaraka94/che,sunix/che,sudaraka94/che,Patricol/che,gazarenkov/che-sketch,sleshchenko/che,Patricol/che,davidfestal/che,davidfestal/che,akervern/che,davidfestal/che,sleshchenko/che,codenvy/che,sudaraka94/che,sleshchenko/che,sudaraka94/che,Patricol/che,codenvy/che,snjeza/che,sunix/che,Patricol/che,cemalkilic/che,sudaraka94/che,Patricol/che,akervern/che,sudaraka94/che,lehmanju/che,sunix/che,bartlomiej-laczkowski/che,akervern/che,snjeza/che,sleshchenko/che,sudaraka94/che,snjeza/che,sleshchenko/che,jonahkichwacoders/che,cdietrich/che,jonahkichwacoders/che,sleshchenko/che,akervern/che,gazarenkov/che-sketch,davidfestal/che,lehmanju/che,cemalkilic/che,gazarenkov/che-sketch,Patricol/che,davidfestal/che,snjeza/che,sunix/che,jonahkichwacoders/che,snjeza/che,lehmanju/che,bartlomiej-laczkowski/che,sunix/che,TypeFox/che,cemalkilic/che,cdietrich/che,sunix/che,cemalkilic/che,codenvy/che,TypeFox/che,snjeza/che,sudaraka94/che,sleshchenko/che,cemalkilic/che,cemalkilic/che,jonahkichwacoders/che | ---
+++
@@ -31,12 +31,10 @@
ngDisabled: '@ngDisabled'
};
-
-
}
link($scope) {
- $scope.controller = $scope.$parent.$parent.cheToggleCtrl;
+ $scope.controller = $scope.$parent.$parent.cheToggleCtrl || $scope.$parent.$parent.$parent.cheToggleCtrl;
}
|
ef7d83a3a558d0886b2d3c2d4b90b1ae71d80ae9 | runtime/src/lore/runtime/types/typeof.ts | runtime/src/lore/runtime/types/typeof.ts | import { Value } from '../values.ts'
import { Type, Types } from './types.ts'
/**
* Calculates the Lore type of a value.
*/
export function typeOf(value: any): Type {
switch (typeof value) {
case 'number':
if (Number.isInteger(value)) {
return Types.int
} else {
return Types.real
}
case 'boolean':
return Types.boolean
case 'string':
return Types.string
case 'object':
// TODO: In the case of a Javascript object being given that does not have a type field, we should return some
// kind of "dynamic" type. Of course, this first requires us to define a similar notion within Lore
// itself.
if (value.hasOwnProperty('lore$type')) {
return (<Value> value).lore$type
}
break
}
// TODO: Throw a "corresponding Lore type not found" error.
return Types.any
}
| import { Value } from '../values.ts'
import { Type, Types } from './types.ts'
/**
* Calculates the Lore type of a value.
*
* TODO: If the compiler is sure that a given value is a struct, shape value, etc. with a lore$type attribute,
* we should inline the lore$type access to remove the need of calling typeOf. This should bring sizable
* performance gains.
*/
export function typeOf(value: any): Type {
switch (typeof value) {
case 'number':
if (Number.isInteger(value)) {
return Types.int
} else {
return Types.real
}
case 'boolean':
return Types.boolean
case 'string':
return Types.string
case 'object':
// TODO: In the case of a Javascript object being given that does not have a type field, we should return some
// kind of "dynamic" type. Of course, this first requires us to define a similar notion within Lore
// itself.
if ((<Value> value).lore$type) {
return (<Value> value).lore$type
}
break
}
// TODO: Throw a "corresponding Lore type not found" error.
return Types.any
}
| Remove hasOwnProperty call from typeOf. | Remove hasOwnProperty call from typeOf.
Also note down a potential further optimization to inline typeOf calls if the compiler can sufficiently narrow down an argument's type.
| TypeScript | mit | marcopennekamp/lore,marcopennekamp/lore | ---
+++
@@ -3,6 +3,10 @@
/**
* Calculates the Lore type of a value.
+ *
+ * TODO: If the compiler is sure that a given value is a struct, shape value, etc. with a lore$type attribute,
+ * we should inline the lore$type access to remove the need of calling typeOf. This should bring sizable
+ * performance gains.
*/
export function typeOf(value: any): Type {
switch (typeof value) {
@@ -20,7 +24,7 @@
// TODO: In the case of a Javascript object being given that does not have a type field, we should return some
// kind of "dynamic" type. Of course, this first requires us to define a similar notion within Lore
// itself.
- if (value.hasOwnProperty('lore$type')) {
+ if ((<Value> value).lore$type) {
return (<Value> value).lore$type
}
break |
9f129f980d87ec01acdc2182c826f498f3a8aa08 | libs/presentation/src/lib/slide-routes.ts | libs/presentation/src/lib/slide-routes.ts | export class SlidesRoutes {
static get(Component: any) {
return [
{path: `:id`, component: Component},
{path: `**`, component: Component}
];
}
}
| export class SlidesRoutes {
static get(Component: any) {
return [
{path: '', redirectTo: '0', pathMatch: 'full'},
{path: ':id', component: Component},
{path: '**', component: Component},
];
}
}
| Add a smart redirect to get rid of having /0 in the end of URLs | Add a smart redirect to get rid of having /0 in the end of URLs
| TypeScript | apache-2.0 | nycJSorg/angular-presentation,nycJSorg/angular-presentation,nycJSorg/angular-presentation | ---
+++
@@ -1,8 +1,9 @@
export class SlidesRoutes {
static get(Component: any) {
return [
- {path: `:id`, component: Component},
- {path: `**`, component: Component}
+ {path: '', redirectTo: '0', pathMatch: 'full'},
+ {path: ':id', component: Component},
+ {path: '**', component: Component},
];
}
} |
1a24b896b6e6f0a03f17d16932df39276d969485 | app/routes/configuration/usermanagement/edit.ts | app/routes/configuration/usermanagement/edit.ts | import BaseRoute from 'explorviz-frontend/routes/base-route';
// @ts-ignore
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import AlertifyHandler from 'explorviz-frontend/mixins/alertify-handler';
import { inject as service } from "@ember/service";
import DS from 'ember-data';
import User from 'explorviz-frontend/models/user';
export default class UserManagementEditRoute extends BaseRoute.extend(AuthenticatedRouteMixin, AlertifyHandler) {
@service('store')
store!: DS.Store;
model(this:UserManagementEditRoute, { user_id }:{ user_id:string }) {
return this.get('store').findRecord('user', user_id, {reload: true}).then((user:User) => {
return {
user
};
});
}
actions = {
// @Override BaseRoute
resetRoute(this: UserManagementEditRoute) {
this.transitionTo('configuration.usermanagement');
},
goBack(this: UserManagementEditRoute) {
this.transitionTo('configuration.usermanagement');
},
error(this: UserManagementEditRoute, error:any) {
let notFound = error === 'not-found' ||
(error &&
error.errors &&
error.errors[0] &&
error.errors[0].status == 404);
// routes that can't find models
if (notFound) {
this.showAlertifyMessage('Error: User was not found.');
this.transitionTo('configuration.usermanagement');
return;
} else {
return true;
}
}
}
}
| import BaseRoute from 'explorviz-frontend/routes/base-route';
// @ts-ignore
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import AlertifyHandler from 'explorviz-frontend/mixins/alertify-handler';
import { inject as service } from "@ember/service";
import DS from 'ember-data';
import User from 'explorviz-frontend/models/user';
export default class UserManagementEditRoute extends BaseRoute.extend(AuthenticatedRouteMixin, AlertifyHandler) {
@service('store')
store!: DS.Store;
model(this:UserManagementEditRoute, { user_id }:{ user_id:string }) {
return this.get('store').findRecord('user', user_id, {reload: true}).then((user:User) => {
return {
user
};
}, () => {
this.showAlertifyWarning('User was not found.');
this.transitionTo('configuration.usermanagement');
});
}
actions = {
// @Override BaseRoute
resetRoute(this: UserManagementEditRoute) {
this.transitionTo('configuration.usermanagement');
},
goBack(this: UserManagementEditRoute) {
this.transitionTo('configuration.usermanagement');
}
}
}
| Handle user not being found | Handle user not being found
| TypeScript | apache-2.0 | ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend | ---
+++
@@ -17,6 +17,9 @@
return {
user
};
+ }, () => {
+ this.showAlertifyWarning('User was not found.');
+ this.transitionTo('configuration.usermanagement');
});
}
@@ -28,23 +31,6 @@
goBack(this: UserManagementEditRoute) {
this.transitionTo('configuration.usermanagement');
- },
-
- error(this: UserManagementEditRoute, error:any) {
- let notFound = error === 'not-found' ||
- (error &&
- error.errors &&
- error.errors[0] &&
- error.errors[0].status == 404);
-
- // routes that can't find models
- if (notFound) {
- this.showAlertifyMessage('Error: User was not found.');
- this.transitionTo('configuration.usermanagement');
- return;
- } else {
- return true;
- }
}
}
} |
b3146ea00538b3c708305a38aae8b49ec44adb18 | src/components/Avatar/index.ts | src/components/Avatar/index.ts | import { UIComponentSources, UIComponentSinks } from '../';
import xs, { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import { SvgIconSinks } from '../SvgIcon';
import { FontIconSinks } from '../FontIcon';
export interface AvatarSources extends UIComponentSources {
backgroundColor$?: Stream<string>;
children$?: Stream<VNode | string>;
color$?: Stream<string>;
icon$?: Stream<SvgIconSinks | FontIconSinks>;
size$?: Stream<number>;
src$?: Stream<string>;
}
export interface AvatarSinks extends UIComponentSinks { }
| import { UIComponentSources, UIComponentSinks } from '../';
import xs, { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import { SvgIconSinks } from '../SvgIcon';
import { FontIconSinks } from '../FontIcon';
export interface AvatarSources extends UIComponentSources {
backgroundColor$?: Stream<string>;
children$?: Stream<VNode | string>;
color$?: Stream<string>;
icon?: SvgIconSinks | FontIconSinks;
size$?: Stream<number>;
src$?: Stream<string>;
}
export interface AvatarSinks extends UIComponentSinks { }
| Fix icon definition in AvatarSources interface | Fix icon definition in AvatarSources interface
| TypeScript | mit | cyclic-ui/cyclic-ui,cyclic-ui/cyclic-ui | ---
+++
@@ -8,7 +8,7 @@
backgroundColor$?: Stream<string>;
children$?: Stream<VNode | string>;
color$?: Stream<string>;
- icon$?: Stream<SvgIconSinks | FontIconSinks>;
+ icon?: SvgIconSinks | FontIconSinks;
size$?: Stream<number>;
src$?: Stream<string>;
} |
b637d7e0479f6d3372a8fb0baa7a5c7e6e14d264 | src/bin-open.ts | src/bin-open.ts | import { open } from 'typings-core'
import { logError } from './support/cli'
export function help () {
return `
typings open <location>
<location> A known Typings location with scheme
`
}
export function exec (args: string[]) {
if (args.length === 0) {
logError(help())
return
}
console.log(open(args[0]))
}
| import { open } from 'typings-core'
import { logError } from './support/cli'
export function help () {
return `
typings open <location>
<location> A known Typings location with scheme (see typings install -h)
`
}
export function exec (args: string[]) {
if (args.length === 0) {
logError(help())
return
}
console.log(open(args[0]))
}
| Add note to `typings open -h` | Add note to `typings open -h` | TypeScript | mit | typings/typings,typings/typings | ---
+++
@@ -5,7 +5,7 @@
return `
typings open <location>
- <location> A known Typings location with scheme
+ <location> A known Typings location with scheme (see typings install -h)
`
}
|
f696c0411f19edb4add0755c4635ad63102779d8 | src/utils/index.ts | src/utils/index.ts | export * from './component'
export * from './fun'
export * from './log'
export * from './reattach'
export * from './style'
export * from './worker'
// mori helpers
import * as _Mori from './mori'
export const Mori = _Mori
| export * from './component'
export * from './fun'
export * from './log'
export * from './reattach'
export * from './style'
export * from './worker'
| Remove mori helper from core | Remove mori helper from core
| TypeScript | mit | FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal | ---
+++
@@ -4,7 +4,3 @@
export * from './reattach'
export * from './style'
export * from './worker'
-
-// mori helpers
-import * as _Mori from './mori'
-export const Mori = _Mori |
7fea76984735e7c63c1016d4a0f00b6cc0b49416 | src/api/variants/getVolumes.ts | src/api/variants/getVolumes.ts | import getImageInfo from './getImageInfo';
/**
* Return a list of the volumes that an Image has
*/
export default async((host: Concierge.Host, dockerImage: string) => {
const info = await(getImageInfo(host, dockerImage));
const config = info.ContainerConfig;
const volumes = config.Volumes;
return Object.keys(volumes);
}); | import getImageInfo from './getImageInfo';
/**
* Return a list of the volumes that an Image has
*/
export default async((host: Concierge.Host, dockerImage: string) => {
const info = await(getImageInfo(host, dockerImage));
const config = info.ContainerConfig;
const volumes = config.Volumes || {};
return Object.keys(volumes);
}); | Fix bug caused by image having no volumes | Fix bug caused by image having no volumes
| TypeScript | mit | the-concierge/concierge,the-concierge/concierge,paypac/node-concierge,the-concierge/concierge,paypac/node-concierge,paypac/node-concierge,paypac/node-concierge | ---
+++
@@ -6,7 +6,7 @@
export default async((host: Concierge.Host, dockerImage: string) => {
const info = await(getImageInfo(host, dockerImage));
const config = info.ContainerConfig;
- const volumes = config.Volumes;
+ const volumes = config.Volumes || {};
return Object.keys(volumes);
}); |
193fb7fef79ceabd9da6c510b87fcbeab443c01f | test/timecode-parsing.test.ts | test/timecode-parsing.test.ts | import { padToHoursMinutesSeconds, parseTimestampToSeconds } from "../src/renderer/parseTimestamp"
describe("Parsing raw timecodes into durations of seconds to hand to the player", () => {
it("should convert short timestamps to seconds", () => {
const shortTimestamp = "[2:47]"
const expectedSeconds = 167
expect(parseTimestampToSeconds(shortTimestamp)).toBeCloseTo(expectedSeconds)
const shortTimestamp2 = "[3:38.66]"
const expectedSeconds2 = 218.66
expect(padToHoursMinutesSeconds(shortTimestamp2)).toBe("00:3:38.66")
expect(parseTimestampToSeconds(shortTimestamp2)).toEqual(expectedSeconds2)
})
it("should convert padded short timestamps to seconds", () => {
const paddedShortTimestamp = "[03:33]"
const expectedSeconds = 213
expect(parseTimestampToSeconds(paddedShortTimestamp)).toBeCloseTo(expectedSeconds)
})
it("should properly parse hours-minutes-seconds", () => {
const hoursMinutesSeconds = "[1:02:00.00]"
const expectedSeconds = 3720
expect(parseTimestampToSeconds(hoursMinutesSeconds)).toBeCloseTo(expectedSeconds)
})
})
| import {
padToHoursMinutesSeconds,
parseTimestampToSeconds,
} from "../src/renderer/parseTimestamp"
describe("Parsing raw timecodes into durations of seconds to hand to the player", (): void => {
it("should convert short timestamps to seconds", (): void => {
const shortTimestamp = "[2:47]"
const expectedSeconds = 167
expect(parseTimestampToSeconds(shortTimestamp)).toBeCloseTo(expectedSeconds)
const shortTimestamp2 = "[3:38.66]"
const expectedSeconds2 = 218.66
expect(padToHoursMinutesSeconds(shortTimestamp2)).toBe("00:3:38.66")
expect(parseTimestampToSeconds(shortTimestamp2)).toEqual(expectedSeconds2)
})
it("should convert padded short timestamps to seconds", (): void => {
const paddedShortTimestamp = "[03:33]"
const expectedSeconds = 213
expect(parseTimestampToSeconds(paddedShortTimestamp)).toBeCloseTo(
expectedSeconds,
)
})
it("should properly parse hours-minutes-seconds", (): void => {
const hoursMinutesSeconds = "[1:02:00.00]"
const expectedSeconds = 3720
expect(parseTimestampToSeconds(hoursMinutesSeconds)).toBeCloseTo(
expectedSeconds,
)
})
})
| Fix ESLint errors in timecode parsing | Fix ESLint errors in timecode parsing
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -1,7 +1,10 @@
-import { padToHoursMinutesSeconds, parseTimestampToSeconds } from "../src/renderer/parseTimestamp"
+import {
+ padToHoursMinutesSeconds,
+ parseTimestampToSeconds,
+} from "../src/renderer/parseTimestamp"
-describe("Parsing raw timecodes into durations of seconds to hand to the player", () => {
- it("should convert short timestamps to seconds", () => {
+describe("Parsing raw timecodes into durations of seconds to hand to the player", (): void => {
+ it("should convert short timestamps to seconds", (): void => {
const shortTimestamp = "[2:47]"
const expectedSeconds = 167
@@ -13,16 +16,20 @@
expect(padToHoursMinutesSeconds(shortTimestamp2)).toBe("00:3:38.66")
expect(parseTimestampToSeconds(shortTimestamp2)).toEqual(expectedSeconds2)
})
- it("should convert padded short timestamps to seconds", () => {
+ it("should convert padded short timestamps to seconds", (): void => {
const paddedShortTimestamp = "[03:33]"
const expectedSeconds = 213
- expect(parseTimestampToSeconds(paddedShortTimestamp)).toBeCloseTo(expectedSeconds)
+ expect(parseTimestampToSeconds(paddedShortTimestamp)).toBeCloseTo(
+ expectedSeconds,
+ )
})
- it("should properly parse hours-minutes-seconds", () => {
+ it("should properly parse hours-minutes-seconds", (): void => {
const hoursMinutesSeconds = "[1:02:00.00]"
const expectedSeconds = 3720
- expect(parseTimestampToSeconds(hoursMinutesSeconds)).toBeCloseTo(expectedSeconds)
+ expect(parseTimestampToSeconds(hoursMinutesSeconds)).toBeCloseTo(
+ expectedSeconds,
+ )
})
}) |
1fd0d903da49de96078c705432e4982fca0162a8 | src/vscode/projectQuickPick.ts | src/vscode/projectQuickPick.ts | 'use strict';
import Promise = require('bluebird');
import { window, QuickPickItem, commands, Uri } from 'vscode';
import { promiseList, projectDirectory } from '../../src/workspace/projectList';
export interface projectQuickPickItem extends QuickPickItem {
path: string;
}
export function showProjectQuickPick() : Thenable<any>{
return promiseList().then((projects) => {
return Promise.map(projects, buildQuickPickProject)
.then(window.showQuickPick);
});
}
function buildQuickPickProject(project: projectDirectory) : projectQuickPickItem{
return {
description: project.workspace,
detail: project.path,
label: project.name,
path: project.path
};
}
export function openProject(projectItem: projectQuickPickItem) {
let projectUri = Uri.parse(projectItem.path);
return commands.executeCommand('vscode.openFolder', projectUri).then(null, console.log);
}
export function showProjectListAndOpen(): Thenable<any>{
return showProjectQuickPick().then(openProject);
} | 'use strict';
import Promise = require('bluebird');
import { window, QuickPickItem, commands, Uri } from 'vscode';
import { promiseList, projectDirectory } from '../../src/workspace/projectList';
export interface projectQuickPickItem extends QuickPickItem {
path: string;
}
export function showProjectQuickPick() : Thenable<any>{
return promiseList().then((projects) => {
return Promise.map(projects, buildQuickPickProject)
.then(window.showQuickPick);
});
}
function buildQuickPickProject(project: projectDirectory) : projectQuickPickItem{
return {
description: project.workspace,
detail: project.path,
label: project.name,
path: project.path
};
}
export function openProject(projectItem: projectQuickPickItem) {
if(projectItem){
let projectUri = Uri.parse(projectItem.path);
return commands.executeCommand('vscode.openFolder', projectUri).then(null, console.log);
} else {
console.warn('No project selected');
return;
}
}
export function showProjectListAndOpen(): Thenable<any>{
return showProjectQuickPick().then(openProject);
} | Handle when no project selected | Handle when no project selected
| TypeScript | mit | joeferraro/MavensMate-VisualStudioCode | ---
+++
@@ -25,8 +25,13 @@
}
export function openProject(projectItem: projectQuickPickItem) {
- let projectUri = Uri.parse(projectItem.path);
- return commands.executeCommand('vscode.openFolder', projectUri).then(null, console.log);
+ if(projectItem){
+ let projectUri = Uri.parse(projectItem.path);
+ return commands.executeCommand('vscode.openFolder', projectUri).then(null, console.log);
+ } else {
+ console.warn('No project selected');
+ return;
+ }
}
export function showProjectListAndOpen(): Thenable<any>{ |
66436fb9ffaa3c2f23efcd706d5413bb31d862cb | packages/core/src/Pipeline.ts | packages/core/src/Pipeline.ts | /**
* @copyright 2017-2018, Miles Johnson
* @license https://opensource.org/licenses/MIT
*/
import Context from './Context';
import CrashLogger from './CrashLogger';
import Routine from './Routine';
import CoreTool from './Tool';
export default class Pipeline<Ctx extends Context, Tool extends CoreTool<any, any>> extends Routine<
Ctx,
Tool,
Tool['config']
> {
constructor(tool: Tool, context: Ctx) {
super('root', 'Pipeline');
if (tool instanceof CoreTool) {
tool.initialize();
} else {
throw new TypeError('A `Tool` instance is required to operate the pipeline.');
}
this.tool = tool;
this.tool.debug('Instantiating pipeline');
this.setContext(context);
}
/**
* Execute all routines in order.
*/
async run<T>(initialValue?: T): Promise<any> {
const { console: cli } = this.tool;
let result = null;
this.tool.debug('Running pipeline');
cli.start([this.routines]);
try {
result = await this.serializeRoutines(initialValue);
cli.exit(null, 0);
} catch (error) {
result = error;
cli.exit(error, 1);
// Create a log of the failure
new CrashLogger(this.tool).log(error);
}
return result;
}
}
| /**
* @copyright 2017-2018, Miles Johnson
* @license https://opensource.org/licenses/MIT
*/
import Context from './Context';
import CrashLogger from './CrashLogger';
import Routine from './Routine';
import CoreTool from './Tool';
export default class Pipeline<Ctx extends Context, Tool extends CoreTool<any, any>> extends Routine<
Ctx,
Tool,
Tool['config']
> {
constructor(tool: Tool, context: Ctx) {
super('root', 'Pipeline');
if (tool instanceof CoreTool) {
tool.initialize();
} else {
throw new TypeError('A `Tool` instance is required to operate the pipeline.');
}
this.tool = tool;
this.tool.debug('Instantiating pipeline');
this.setContext(context);
}
/**
* Execute all routines in order.
*/
async run<T>(initialValue?: T): Promise<any> {
const { console: cli } = this.tool;
let result = null;
this.tool.debug('Running pipeline');
cli.start([this.routines]);
try {
result = await this.serializeRoutines(initialValue);
cli.exit(null, 0);
} catch (error) {
// Create a log of the failure
new CrashLogger(this.tool).log(error);
result = error;
cli.exit(error, 1);
}
return result;
}
}
| Write crash log before exit. | Write crash log before exit.
| TypeScript | mit | milesj/boost,milesj/boost | ---
+++
@@ -43,11 +43,11 @@
result = await this.serializeRoutines(initialValue);
cli.exit(null, 0);
} catch (error) {
+ // Create a log of the failure
+ new CrashLogger(this.tool).log(error);
+
result = error;
cli.exit(error, 1);
-
- // Create a log of the failure
- new CrashLogger(this.tool).log(error);
}
return result; |
d14db4b1c0918527b2c0d5cb7a9daa6a09f3254b | test/runTest.ts | test/runTest.ts | import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to the extension test script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error('Failed to run tests');
console.error(err.stack);
process.exit(1);
}
}
main();
| import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../../');
// The path to the extension test script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error('Failed to run tests');
console.error(err.stack);
process.exit(1);
}
}
main();
| Change extension path to directory above | Change extension path to directory above
| TypeScript | mit | neild3r/vscode-php-docblocker | ---
+++
@@ -6,7 +6,7 @@
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
- const extensionDevelopmentPath = path.resolve(__dirname, '../../');
+ const extensionDevelopmentPath = path.resolve(__dirname, '../../../');
// The path to the extension test script
// Passed to --extensionTestsPath |
08d65850106eaee40dcd504671604b63ca32e44b | src/ResourceParams.ts | src/ResourceParams.ts | import { Type } from '@angular/core';
import { ResourceParamsBase } from './Interfaces';
import { ResourceProviders } from './ResourceProviders';
import { Resource } from './Resource';
export function ResourceParams(params: ResourceParamsBase = {}) {
return function (target: Type<Resource>) {
target.prototype.getResourceOptions = function () {
return params;
};
if (params.add2Provides !== false) {
ResourceProviders.add(target, params.providersSubSet);
}
if (typeof params.removeTrailingSlash !== 'undefined') {
target.prototype.removeTrailingSlash = function () {
return !!params.removeTrailingSlash;
};
}
if (params.url) {
target.prototype._getUrl = function () {
return params.url;
};
}
if (params.path) {
target.prototype._getPath = function () {
return params.path;
};
}
if (params.headers) {
target.prototype._getHeaders = function () {
return params.headers;
};
}
if (params.params) {
target.prototype._getParams = function () {
return params.params;
};
}
if (params.data) {
target.prototype._getData = function () {
return params.data;
};
}
};
}
| import { Type } from '@angular/core';
import { ResourceParamsBase } from './Interfaces';
import { ResourceProviders } from './ResourceProviders';
import { Resource } from './Resource';
export function ResourceParams(params: ResourceParamsBase = {}) {
return function (target: Type<Resource>) {
target.prototype.getResourceOptions = function () {
return params;
};
if (params.add2Provides !== false) {
ResourceProviders.add(target, params.providersSubSet);
}
if (typeof params.removeTrailingSlash !== 'undefined') {
target.prototype.removeTrailingSlash = function () {
return !!params.removeTrailingSlash;
};
}
if (params.url) {
target.prototype.$_getUrl = function () {
return params.url;
};
}
if (params.path) {
target.prototype.$_getPath = function () {
return params.path;
};
}
if (params.headers) {
target.prototype.$_getHeaders = function () {
return params.headers;
};
}
if (params.params) {
target.prototype.$_getParams = function () {
return params.params;
};
}
if (params.data) {
target.prototype.$_getData = function () {
return params.data;
};
}
};
}
| Rename methods for version 3.x.x | Rename methods for version 3.x.x
Since this commit: https://github.com/troyanskiy/ngx-resource/commit/c990ed8561513728adffa9fbc065767c6322c5b0
methods have been renamed | TypeScript | mit | troyanskiy/ng2-resource-rest,troyanskiy/ng2-resource-rest | ---
+++
@@ -25,31 +25,31 @@
}
if (params.url) {
- target.prototype._getUrl = function () {
+ target.prototype.$_getUrl = function () {
return params.url;
};
}
if (params.path) {
- target.prototype._getPath = function () {
+ target.prototype.$_getPath = function () {
return params.path;
};
}
if (params.headers) {
- target.prototype._getHeaders = function () {
+ target.prototype.$_getHeaders = function () {
return params.headers;
};
}
if (params.params) {
- target.prototype._getParams = function () {
+ target.prototype.$_getParams = function () {
return params.params;
};
}
if (params.data) {
- target.prototype._getData = function () {
+ target.prototype.$_getData = function () {
return params.data;
};
} |
e61c1d3c2fb1152c577453d670eb6231d2283a3c | modules/html-content/index.tsx | modules/html-content/index.tsx | import * as React from 'react'
import {WebView} from 'react-native-webview'
import {openUrl, canOpenUrl} from '@frogpond/open-url'
import type {StyleProp, ViewStyle} from 'react-native'
type Props = {
html: string
baseUrl?: string
style?: StyleProp<ViewStyle>
}
export class HtmlContent extends React.Component<Props> {
_webview: WebView
onNavigationStateChange = ({url}: {url: string}) => {
// iOS navigates to about:blank when you provide raw HTML to a webview.
// Android navigates to data:text/html;$stuff (that is, the document you passed) instead.
if (!canOpenUrl(url)) {
return
}
// We don't want to open the web browser unless the user actually clicked
// on a link.
if (url === this.props.baseUrl) {
return
}
this._webview.stopLoading()
this._webview.goBack()
return openUrl(url)
}
render() {
return (
<WebView
ref={(ref) => (this._webview = ref)}
onNavigationStateChange={this.onNavigationStateChange}
source={{html: this.props.html, baseUrl: this.props.baseUrl}}
style={this.props.style}
/>
)
}
}
| import * as React from 'react'
import {WebView} from 'react-native-webview'
import {openUrl, canOpenUrl} from '@frogpond/open-url'
import type {StyleProp, ViewStyle} from 'react-native'
type Props = {
html: string
baseUrl?: string
style?: StyleProp<ViewStyle>
}
export class HtmlContent extends React.Component<Props> {
_webview: WebView | null = null
onNavigationStateChange = ({url}: {url: string}) => {
// iOS navigates to about:blank when you provide raw HTML to a webview.
// Android navigates to data:text/html;$stuff (that is, the document you passed) instead.
if (!canOpenUrl(url)) {
return
}
// We don't want to open the web browser unless the user actually clicked
// on a link.
if (url === this.props.baseUrl) {
return
}
this._webview.stopLoading()
this._webview.goBack()
return openUrl(url)
}
render() {
return (
<WebView
ref={(ref) => (this._webview = ref)}
onNavigationStateChange={this.onNavigationStateChange}
source={{html: this.props.html, baseUrl: this.props.baseUrl}}
style={this.props.style}
/>
)
}
}
| Mark _webview as possibly null | m/html-content: Mark _webview as possibly null
Signed-off-by: Kristofer Rye <1ed31cfd0b53bc3d1689a6fee6dbfc9507dffd22@gmail.com>
| TypeScript | agpl-3.0 | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | ---
+++
@@ -10,7 +10,7 @@
}
export class HtmlContent extends React.Component<Props> {
- _webview: WebView
+ _webview: WebView | null = null
onNavigationStateChange = ({url}: {url: string}) => {
// iOS navigates to about:blank when you provide raw HTML to a webview. |
69f63cddccc269c37d254c9ce5dc0e5a9b92a270 | src/setupTests.ts | src/setupTests.ts | import createFetchMock from 'vitest-fetch-mock';
import '@testing-library/jest-dom';
// Suppress oaf-react-router warning about missing title
document.title = 'React Starter';
// Mock fetch
createFetchMock(vi).enableMocks();
// Mock matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// eslint-disable-next-line import/first
import 'common/i18next';
| import createFetchMock from 'vitest-fetch-mock';
import '@testing-library/jest-dom';
// Suppress oaf-react-router warning about missing title
document.title = 'React Starter';
// Mock fetch
createFetchMock(vi).enableMocks();
// Mock matchMedia
vi.stubGlobal('matchMedia', (query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
// eslint-disable-next-line import/first
import 'common/i18next';
| Fix matchMedia mock for tests | Fix matchMedia mock for tests
| TypeScript | mit | Kamahl19/react-starter,Kamahl19/react-starter,Kamahl19/react-starter,Kamahl19/react-starter | ---
+++
@@ -9,19 +9,16 @@
createFetchMock(vi).enableMocks();
// Mock matchMedia
-Object.defineProperty(window, 'matchMedia', {
- writable: true,
- value: vi.fn().mockImplementation((query: string) => ({
- matches: false,
- media: query,
- onchange: null,
- addListener: vi.fn(),
- removeListener: vi.fn(),
- addEventListener: vi.fn(),
- removeEventListener: vi.fn(),
- dispatchEvent: vi.fn(),
- })),
-});
+vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+}));
// eslint-disable-next-line import/first
import 'common/i18next'; |
1fb5b3c155f7695057cc778229f12661551699d8 | app/src/lib/auth.ts | app/src/lib/auth.ts | import { Account } from '../models/account'
/** Get the auth key for the user. */
export function getKeyForAccount(account: Account): string {
return getKeyForEndpoint(account.endpoint)
}
/** Get the auth key for the endpoint. */
export function getKeyForEndpoint(endpoint: string): string {
return `GitHub - ${endpoint}`
}
| import { Account } from '../models/account'
/** Get the auth key for the user. */
export function getKeyForAccount(account: Account): string {
return getKeyForEndpoint(account.endpoint)
}
/** Get the auth key for the endpoint. */
export function getKeyForEndpoint(endpoint: string): string {
const appName = __DEV__
? 'GitHub Desktop Dev'
: 'GitHub'
return `${appName} - ${endpoint}`
}
| Store the Dev token separate from the prod token | Store the Dev token separate from the prod token
| TypeScript | mit | artivilla/desktop,shiftkey/desktop,gengjiawen/desktop,hjobrien/desktop,hjobrien/desktop,kactus-io/kactus,desktop/desktop,gengjiawen/desktop,desktop/desktop,say25/desktop,artivilla/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,desktop/desktop,j-f1/forked-desktop,hjobrien/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,say25/desktop,say25/desktop,shiftkey/desktop,hjobrien/desktop,gengjiawen/desktop,artivilla/desktop,j-f1/forked-desktop,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,desktop/desktop,j-f1/forked-desktop | ---
+++
@@ -7,5 +7,9 @@
/** Get the auth key for the endpoint. */
export function getKeyForEndpoint(endpoint: string): string {
- return `GitHub - ${endpoint}`
+ const appName = __DEV__
+ ? 'GitHub Desktop Dev'
+ : 'GitHub'
+
+ return `${appName} - ${endpoint}`
} |
c57b99de9d8ae236c16ecfbc794f9404a6bcbaa2 | src/js/ui/players/playerXhr.ts | src/js/ui/players/playerXhr.ts | import { fetchJSON } from '../../http';
import { User, Rankings } from '../../lichess/interfaces/user'
export function autocomplete(term: string): Promise<Array<string>> {
return fetchJSON('/player/autocomplete', { query: { term }});
}
export function suggestions(userId: string) {
return fetchJSON(`/@/${userId}/suggestions`, {}, true);
}
export function onlinePlayers(): Promise<Array<User>> {
return fetchJSON('/player/online', { query: { nb: 100 }}, true);
}
export function ranking(): Promise<Rankings> {
return fetchJSON('/player', {}, true);
}
| import { fetchJSON } from '../../http';
import { User, Rankings } from '../../lichess/interfaces/user'
export function autocomplete(term: string): Promise<Array<string>> {
return fetchJSON('/player/autocomplete?friend=1', { query: { term }});
}
export function suggestions(userId: string) {
return fetchJSON(`/@/${userId}/suggestions`, {}, true);
}
export function onlinePlayers(): Promise<Array<User>> {
return fetchJSON('/player/online', { query: { nb: 100 }}, true);
}
export function ranking(): Promise<Rankings> {
return fetchJSON('/player', {}, true);
}
| Return only friends from search until no friends match. Then search everyone. | Return only friends from search until no friends match. Then search everyone.
| TypeScript | mit | btrent/lichobile,btrent/lichobile,btrent/lichobile,btrent/lichobile | ---
+++
@@ -2,7 +2,7 @@
import { User, Rankings } from '../../lichess/interfaces/user'
export function autocomplete(term: string): Promise<Array<string>> {
- return fetchJSON('/player/autocomplete', { query: { term }});
+ return fetchJSON('/player/autocomplete?friend=1', { query: { term }});
}
export function suggestions(userId: string) { |
ab731e292bc9bdd8f18724b375b637341578ef1a | src/utils/dialogs.ts | src/utils/dialogs.ts | import { app, BrowserWindow, dialog } from 'electron'
import { basename } from 'path'
import { supportedFiles } from '../ui/settings/supported-files'
export function showOpenDialog(mainWindow: BrowserWindow): Promise<string> {
return new Promise((resolve) => {
dialog.showOpenDialog(
mainWindow!,
{
filters: [{ name: '', extensions: removeDotFromExtensions(supportedFiles) }],
properties: ['openFile']
},
(filePaths: string[]) => {
if (!filePaths) return
resolve(filePaths[0])
}
)
})
}
export function showExportDialog(mainWindow: BrowserWindow,
fileName: string): Promise<string> {
return new Promise((resolve) => {
dialog.showSaveDialog(
mainWindow!,
{
defaultPath: `${app.getPath('downloads')}/${basename(fileName)}.png`
},
(selectedFileName: string) => {
if (!selectedFileName) return
resolve(selectedFileName)
}
)
})
}
function removeDotFromExtensions(extt: string[]): string[] {
const res: string[] = []
extt.forEach((element) => {
res.push(element.substring(1))
})
return res
}
| import { BrowserWindow, dialog } from 'electron'
import { basename } from 'path'
import { supportedFiles } from '../ui/settings/supported-files'
export function showOpenDialog(mainWindow: BrowserWindow): Promise<string> {
return new Promise((resolve) => {
dialog.showOpenDialog(
mainWindow!,
{
filters: [{ name: '', extensions: removeDotFromExtensions(supportedFiles) }],
properties: ['openFile']
},
(filePaths: string[]) => {
if (!filePaths) return
resolve(filePaths[0])
}
)
})
}
export function showExportDialog(mainWindow: BrowserWindow,
fileName: string): Promise<string> {
return new Promise((resolve) => {
dialog.showSaveDialog(
mainWindow!,
{
defaultPath: `${basename(fileName)}.png`
},
(selectedFileName: string) => {
if (!selectedFileName) return
resolve(selectedFileName)
}
)
})
}
function removeDotFromExtensions(extension: string[]): string[] {
const result: string[] = []
extension.forEach((element) => {
result.push(element.substring(1))
})
return result
}
| Set default export path to file location path | Set default export path to file location path
| TypeScript | mit | nrlquaker/nfov,nrlquaker/nfov | ---
+++
@@ -1,4 +1,4 @@
-import { app, BrowserWindow, dialog } from 'electron'
+import { BrowserWindow, dialog } from 'electron'
import { basename } from 'path'
import { supportedFiles } from '../ui/settings/supported-files'
@@ -24,7 +24,7 @@
dialog.showSaveDialog(
mainWindow!,
{
- defaultPath: `${app.getPath('downloads')}/${basename(fileName)}.png`
+ defaultPath: `${basename(fileName)}.png`
},
(selectedFileName: string) => {
if (!selectedFileName) return
@@ -34,10 +34,10 @@
})
}
-function removeDotFromExtensions(extt: string[]): string[] {
- const res: string[] = []
- extt.forEach((element) => {
- res.push(element.substring(1))
+function removeDotFromExtensions(extension: string[]): string[] {
+ const result: string[] = []
+ extension.forEach((element) => {
+ result.push(element.substring(1))
})
- return res
+ return result
} |
06630c610867fff7607541d34db680833d6ef6b4 | src/definitions/SkillContext.ts | src/definitions/SkillContext.ts | import {Callback, Context as LambdaContext} from "aws-lambda";
import {AlexaRequestBody} from "./AlexaService";
namespace Skill {
export class Context {
constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback, _this?: any) {
if (_this) {
Object.assign(this, _this);
}
this.request = request;
this.event = event;
this.callback = callback;
}
request: AlexaRequestBody;
event: LambdaContext;
callback: Callback;
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
}
}
export = Skill;
| import {Callback, Context as LambdaContext} from "aws-lambda";
import {AlexaRequestBody} from "./AlexaService";
export class RequestContext {
constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback) {
this.request = request;
this.event = event;
this.callback = callback;
}
request: AlexaRequestBody;
event: LambdaContext;
callback: Callback;
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
}
export class Attributes {
constructor(props?: any) {
if (props) {
Object.assign(this, props);
}
}
get(prop): any {
console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
return this[prop];
}
set(prop, value): boolean {
console.log(`Adding prop ${prop}...`);
return this[prop] = value;
}
delete(prop): boolean {
console.log(`Deleting prop ${prop}...`);
return delete this[prop];
}
} | Remove unnecessary namespace and export. | Remove unnecessary namespace and export.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -1,41 +1,58 @@
import {Callback, Context as LambdaContext} from "aws-lambda";
import {AlexaRequestBody} from "./AlexaService";
-namespace Skill {
- export class Context {
- constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback, _this?: any) {
- if (_this) {
- Object.assign(this, _this);
- }
+export class RequestContext {
+ constructor(request: AlexaRequestBody, event: LambdaContext, callback: Callback) {
+ this.request = request;
+ this.event = event;
+ this.callback = callback;
+ }
- this.request = request;
- this.event = event;
- this.callback = callback;
- }
+ request: AlexaRequestBody;
- request: AlexaRequestBody;
+ event: LambdaContext;
- event: LambdaContext;
+ callback: Callback;
- callback: Callback;
+ get(prop): any {
+ console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
+ return this[prop];
+ }
- get(prop): any {
- console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
- return this[prop];
- }
+ set(prop, value): boolean {
+ console.log(`Adding prop ${prop}...`);
- set(prop, value): boolean {
- console.log(`Adding prop ${prop}...`);
+ return this[prop] = value;
+ }
- return this[prop] = value;
- }
+ delete(prop): boolean {
+ console.log(`Deleting prop ${prop}...`);
- delete(prop): boolean {
- console.log(`Deleting prop ${prop}...`);
-
- return delete this[prop];
- }
+ return delete this[prop];
}
}
-export = Skill;
+export class Attributes {
+ constructor(props?: any) {
+ if (props) {
+ Object.assign(this, props);
+ }
+ }
+
+ get(prop): any {
+ console.log(`Fetching prop ${prop}, ${prop in this ? "found" : "not found"}.`);
+ return this[prop];
+ }
+
+ set(prop, value): boolean {
+ console.log(`Adding prop ${prop}...`);
+
+ return this[prop] = value;
+ }
+
+ delete(prop): boolean {
+ console.log(`Deleting prop ${prop}...`);
+
+ return delete this[prop];
+ }
+} |
44eb5b33ea4c7477ccb87c9018ed93e8cbdfab51 | lib/mobx-angular.ts | lib/mobx-angular.ts | import { NgModule } from '@angular/core';
import { MobxAutorunDirective } from './directives/mobx-autorun.directive';
import { MobxAutorunSyncDirective } from './directives/mobx-autorun-sync.directive';
import { MobxReactionDirective } from './directives/mobx-reaction.directive';
import {
action as mobxAction,
IObservableFactory,
IObservableFactories,
IEnhancer
} from 'mobx';
import { computed as mobxComputed } from 'mobx';
import { observable as mobxObservable } from 'mobx';
export {
MobxAutorunDirective,
MobxAutorunSyncDirective,
MobxReactionDirective
};
const DIRECTIVES = [
MobxAutorunDirective,
MobxAutorunSyncDirective,
MobxReactionDirective
];
@NgModule({
declarations: [...DIRECTIVES],
exports: [...DIRECTIVES],
imports: [],
providers: []
})
export class MobxAngularModule {}
export function actionInternal(...args) {
return (mobxAction as any)(...args);
}
export const action: typeof mobxAction = Object.assign(
actionInternal,
mobxAction
) as any;
function computedInternal(...args) {
return (mobxComputed as any)(...args);
}
export const computed: typeof mobxComputed = Object.assign(
computedInternal,
mobxComputed
) as any;
function observableInternal(...args) {
return (mobxObservable as any)(...args);
}
export const observable: typeof mobxObservable = Object.assign(
observableInternal,
mobxObservable
) as any;
| import { NgModule } from '@angular/core';
import { MobxAutorunDirective } from './directives/mobx-autorun.directive';
import { MobxAutorunSyncDirective } from './directives/mobx-autorun-sync.directive';
import { MobxReactionDirective } from './directives/mobx-reaction.directive';
import {
action as mobxAction,
IObservableFactory,
IObservableFactories,
IEnhancer
} from 'mobx';
import { computed as mobxComputed } from 'mobx';
import { observable as mobxObservable } from 'mobx';
export {
MobxAutorunDirective,
MobxAutorunSyncDirective,
MobxReactionDirective
};
const DIRECTIVES = [
MobxAutorunDirective,
MobxAutorunSyncDirective,
MobxReactionDirective
];
@NgModule({
declarations: DIRECTIVES,
exports: DIRECTIVES,
imports: [],
providers: []
})
export class MobxAngularModule {}
export function actionInternal(...args) {
return (mobxAction as any)(...args);
}
export const action: typeof mobxAction = Object.assign(
actionInternal,
mobxAction
) as any;
function computedInternal(...args) {
return (mobxComputed as any)(...args);
}
export const computed: typeof mobxComputed = Object.assign(
computedInternal,
mobxComputed
) as any;
function observableInternal(...args) {
return (mobxObservable as any)(...args);
}
export const observable: typeof mobxObservable = Object.assign(
observableInternal,
mobxObservable
) as any;
| Remove spread operator in module declaration | Remove spread operator in module declaration | TypeScript | mit | 500tech/ng2-mobx,500tech/ng2-mobx,mobxjs/mobx-angular,mobxjs/mobx-angular,500tech/ng2-mobx,mobxjs/mobx-angular,mobxjs/mobx-angular | ---
+++
@@ -23,8 +23,8 @@
MobxReactionDirective
];
@NgModule({
- declarations: [...DIRECTIVES],
- exports: [...DIRECTIVES],
+ declarations: DIRECTIVES,
+ exports: DIRECTIVES,
imports: [],
providers: []
}) |
d96ded7841c9f2a0e8521fcb61a2d570dd06cf7c | app/src/app.run.ts | app/src/app.run.ts | module app {
import IDialogService = angular.material.IDialogService;
import IDialogOptions = angular.material.IDialogOptions;
import DataschemaImportController = app.dialogs.dataschemaimport.DataschemaImportController;
class Runner {
static $inject = ['$mdDialog'];
constructor($mdDialog:IDialogService) {
var options:IDialogOptions = {
parent: angular.element(document.body),
templateUrl: 'app/src/components/dialogs/dataschemaImport/dataschemaImport.html',
controller: DataschemaImportController,
controllerAs: 'dialog'
};
$mdDialog.show(options);
}
}
angular.module('app').run(Runner);
} | module app {
import IDialogService = angular.material.IDialogService;
import IDialogOptions = angular.material.IDialogOptions;
import DataschemaImportController = app.dialogs.dataschemaimport.DataschemaImportController;
import ILocationService = angular.ILocationService;
class Runner {
static $inject = ['$mdDialog', '$location'];
constructor($mdDialog:IDialogService, $location:ILocationService) {
if ($location.path() === '/edit') {
var options:IDialogOptions = {
parent: angular.element(document.body),
templateUrl: 'app/src/components/dialogs/dataschemaImport/dataschemaImport.html',
controller: DataschemaImportController,
controllerAs: 'dialog'
};
$mdDialog.show(options);
}
}
}
angular.module('app').run(Runner);
} | Hide upload dialog in freshly created preview tab | Hide upload dialog in freshly created preview tab
| TypeScript | mit | FelixThieleTUM/JsonFormsEditor,eclipsesource/JsonFormsEditor,eclipsesource/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,pancho111203/JsonFormsEditor,pancho111203/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor,eclipsesource/JsonFormsEditor,pancho111203/JsonFormsEditor,eclipsesource/JsonFormsEditor,pancho111203/JsonFormsEditor,FelixThieleTUM/JsonFormsEditor | ---
+++
@@ -3,20 +3,23 @@
import IDialogService = angular.material.IDialogService;
import IDialogOptions = angular.material.IDialogOptions;
import DataschemaImportController = app.dialogs.dataschemaimport.DataschemaImportController;
+ import ILocationService = angular.ILocationService;
class Runner {
- static $inject = ['$mdDialog'];
+ static $inject = ['$mdDialog', '$location'];
- constructor($mdDialog:IDialogService) {
- var options:IDialogOptions = {
- parent: angular.element(document.body),
- templateUrl: 'app/src/components/dialogs/dataschemaImport/dataschemaImport.html',
- controller: DataschemaImportController,
- controllerAs: 'dialog'
- };
+ constructor($mdDialog:IDialogService, $location:ILocationService) {
+ if ($location.path() === '/edit') {
+ var options:IDialogOptions = {
+ parent: angular.element(document.body),
+ templateUrl: 'app/src/components/dialogs/dataschemaImport/dataschemaImport.html',
+ controller: DataschemaImportController,
+ controllerAs: 'dialog'
+ };
- $mdDialog.show(options);
+ $mdDialog.show(options);
+ }
}
}
|
609a2105cc77d2b47f4192ff79118d2b4cecc2da | src/OKShareCount.ts | src/OKShareCount.ts | import jsonp from 'jsonp';
import objectToGetParams from './utils/objectToGetParams';
import createShareCount from './hocs/createShareCount';
declare global {
interface Window {
OK: {
Share: {
count: (index: number, _count: number) => void;
};
callbacks: ((count?: number) => void)[];
};
ODKL: {
updateCount: (a: any, b: any) => void;
};
}
}
function getOKShareCount(shareUrl: string, callback: (shareCount?: number) => void) {
if (!window.OK) {
window.OK = {
Share: {
count: function count(index, _count) {
window.OK.callbacks[index](_count);
},
},
callbacks: [],
};
}
const url = 'https://connect.ok.ru/dk';
const index = window.OK.callbacks.length;
window.ODKL = {
updateCount(a, b) {
window.OK.callbacks[index](b);
},
};
window.OK.callbacks.push(callback);
return jsonp(
url +
objectToGetParams({
'st.cmd': 'extLike',
uid: 'odklcnt0',
ref: shareUrl,
}),
);
}
export default createShareCount(getOKShareCount);
| import jsonp from 'jsonp';
import objectToGetParams from './utils/objectToGetParams';
import createShareCount from './hocs/createShareCount';
declare global {
interface Window {
OK: {
Share: {
count: (index: number, _count: number) => void;
};
callbacks: ((count?: number) => void)[];
};
ODKL: {
updateCount: (a: any, b: any) => void;
};
}
}
function getOKShareCount(shareUrl: string, callback: (shareCount?: number) => void) {
if (!window.OK) {
window.OK = {
Share: {
count: function count(index, _count) {
window.OK.callbacks[index](_count);
},
},
callbacks: [],
};
}
const url = 'https://connect.ok.ru/dk';
const index = window.OK.callbacks.length;
window.ODKL = {
updateCount(a, b) {
window.OK.callbacks[parseInt(a)](b);
},
};
window.OK.callbacks.push(callback);
return jsonp(
url +
objectToGetParams({
'st.cmd': 'extLike',
uid: index,
ref: shareUrl,
}),
);
}
export default createShareCount(getOKShareCount);
| Call correct callback with multiple OK share button | Call correct callback with multiple OK share button
| TypeScript | mit | nygardk/react-share,nygardk/react-share | ---
+++
@@ -34,7 +34,7 @@
window.ODKL = {
updateCount(a, b) {
- window.OK.callbacks[index](b);
+ window.OK.callbacks[parseInt(a)](b);
},
};
window.OK.callbacks.push(callback);
@@ -43,7 +43,7 @@
url +
objectToGetParams({
'st.cmd': 'extLike',
- uid: 'odklcnt0',
+ uid: index,
ref: shareUrl,
}),
); |
69911da7839ac0e0af9c3c81d96b313a8f3726fc | src/util/schemas.ts | src/util/schemas.ts |
import {Schema, transform, arrayOf} from "idealizr";
export const game = new Schema("games");
export const user = new Schema("users");
export const collection = new Schema("collections");
export const downloadKey = new Schema("downloadKeys");
function parseDate(input: string) {
// without `+0` it parses a local date - this is the fastest
// way to parse a UTC date.
// see https://jsperf.com/parse-utc-date
return new Date(input + "+0");
}
const date = transform(parseDate);
game.define({
user,
created_at: date,
published_at: date,
});
collection.define({
games: arrayOf(game),
created_at: date,
updated_at: date,
});
downloadKey.define({
game,
created_at: date,
updated_at: date,
});
|
import {Schema, transform, arrayOf} from "idealizr";
export const game = new Schema("games");
export const user = new Schema("users");
export const collection = new Schema("collections");
export const downloadKey = new Schema("downloadKeys");
function parseDate(input: string) {
// without `+0` it parses a local date - this is the fastest
// way to parse a UTC date.
// see https://jsperf.com/parse-utc-date
const date = new Date(input + "+0");
// we don't store milliseconds in the db anyway,
// so let's just discard it here
date.setMilliseconds(0);
return date;
}
const date = transform(parseDate);
game.define({
user,
created_at: date,
published_at: date,
});
collection.define({
games: arrayOf(game),
created_at: date,
updated_at: date,
});
downloadKey.define({
game,
created_at: date,
updated_at: date,
});
| Discard milliseconds when parsing dates (sqlite doesn't do milliseconds for datetime) | Discard milliseconds when parsing dates (sqlite doesn't do milliseconds for datetime)
| TypeScript | mit | itchio/itch,itchio/itch,leafo/itchio-app,itchio/itchio-app,itchio/itchio-app,itchio/itch,itchio/itch,leafo/itchio-app,leafo/itchio-app,itchio/itch,itchio/itchio-app,itchio/itch | ---
+++
@@ -10,7 +10,11 @@
// without `+0` it parses a local date - this is the fastest
// way to parse a UTC date.
// see https://jsperf.com/parse-utc-date
- return new Date(input + "+0");
+ const date = new Date(input + "+0");
+ // we don't store milliseconds in the db anyway,
+ // so let's just discard it here
+ date.setMilliseconds(0);
+ return date;
}
const date = transform(parseDate); |
cf510fc80edfe4b75cc8e469324f6a3d48c6b935 | src/definitions/Handler.ts | src/definitions/Handler.ts | import {Context} from "./SkillContext";
let Frames = require("../definitions/FrameDirectory");
namespace Handlers {
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
this.unhandled = unhandled;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
unhandled: ReturnsFrame;
actions: ActionMap;
}
export class ResponseContext {
constructor(model: ResponseModel) {
this.model = model;
}
model: ResponseModel;
}
export class ResponseModel {
speech: string;
reprompt: string;
}
export interface ReturnsResponseContext {
(Context: Context): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Context: Context): Frame | Promise<Frame>;
}
}
export = Handlers; | import * as Frames from "../definitions/FrameDirectory";
import {Attributes, RequestContext} from "./SkillContext";
export class Frame {
constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
this.id = id;
this.entry = entry;
this.actions = FrameMap;
this.unhandled = unhandled;
Frames[id] = this;
}
id: string;
entry: ReturnsResponseContext;
unhandled: ReturnsFrame;
actions: ActionMap;
}
export class ResponseContext {
constructor(model: ResponseModel) {
this.model = model;
}
model: ResponseModel;
}
export class ResponseModel {
speech: string;
reprompt: string;
}
export interface ReturnsResponseContext {
(Attributes: Attributes, Context?: RequestContext): ResponseContext | Promise<ResponseContext>;
}
export interface ActionMap {
[key: string]: ReturnsFrame | undefined;
}
export interface ReturnsFrame {
(Attributes: Attributes, Context?: RequestContext): Frame | Promise<Frame>;
} | Use imports instead of require. Remove unnecessary namespace. | Use imports instead of require. Remove unnecessary namespace.
| TypeScript | agpl-3.0 | deegles/cookietime,deegles/cookietime | ---
+++
@@ -1,51 +1,46 @@
-import {Context} from "./SkillContext";
-let Frames = require("../definitions/FrameDirectory");
+import * as Frames from "../definitions/FrameDirectory";
+import {Attributes, RequestContext} from "./SkillContext";
-namespace Handlers {
+export class Frame {
+ constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
+ this.id = id;
+ this.entry = entry;
+ this.actions = FrameMap;
+ this.unhandled = unhandled;
- export class Frame {
- constructor(id: string, entry: ReturnsResponseContext, unhandled: ReturnsFrame, FrameMap: ActionMap) {
- this.id = id;
- this.entry = entry;
- this.actions = FrameMap;
- this.unhandled = unhandled;
-
- Frames[id] = this;
- }
-
- id: string;
-
- entry: ReturnsResponseContext;
-
- unhandled: ReturnsFrame;
-
- actions: ActionMap;
+ Frames[id] = this;
}
- export class ResponseContext {
- constructor(model: ResponseModel) {
- this.model = model;
- }
+ id: string;
- model: ResponseModel;
+ entry: ReturnsResponseContext;
+
+ unhandled: ReturnsFrame;
+
+ actions: ActionMap;
+}
+
+export class ResponseContext {
+ constructor(model: ResponseModel) {
+ this.model = model;
}
- export class ResponseModel {
- speech: string;
- reprompt: string;
- }
-
- export interface ReturnsResponseContext {
- (Context: Context): ResponseContext | Promise<ResponseContext>;
- }
-
- export interface ActionMap {
- [key: string]: ReturnsFrame | undefined;
- }
-
- export interface ReturnsFrame {
- (Context: Context): Frame | Promise<Frame>;
- }
+ model: ResponseModel;
}
-export = Handlers;
+export class ResponseModel {
+ speech: string;
+ reprompt: string;
+}
+
+export interface ReturnsResponseContext {
+ (Attributes: Attributes, Context?: RequestContext): ResponseContext | Promise<ResponseContext>;
+}
+
+export interface ActionMap {
+ [key: string]: ReturnsFrame | undefined;
+}
+
+export interface ReturnsFrame {
+ (Attributes: Attributes, Context?: RequestContext): Frame | Promise<Frame>;
+} |
8c2e8a2176ef6b54ae0f27885a62dd65583df6e8 | ui/src/shared/actions/errors.ts | ui/src/shared/actions/errors.ts | enum AlertType {
'info',
}
export type ErrorThrownActionCreator = (
error: Error,
altText?: string,
alertType?: AlertType
) => ErrorThrownAction
interface ErrorThrownAction {
type: 'ERROR_THROWN'
error: Error
altText?: string
alertType?: AlertType
}
export const errorThrown = (
error: Error,
altText?: string,
alertType?: AlertType
): ErrorThrownAction => ({
type: 'ERROR_THROWN',
error,
altText,
alertType,
})
| enum AlertType {
'info',
}
export type ErrorThrownActionCreator = (
error: Error,
altText?: string,
alertType?: AlertType
) => ErrorThrownAction
interface ErrorThrownAction {
type: 'ERROR_THROWN'
error: ErrorDescription
altText?: string
alertType?: AlertType
}
export const errorThrown = (
error: ErrorDescription,
altText?: string,
alertType?: AlertType
): ErrorThrownAction => ({
type: 'ERROR_THROWN',
error,
altText,
alertType,
})
interface ErrorDescription {
status: number
auth: {
links: {
me: string
}
}
}
| Add ErrorDescription with auth and links | Add ErrorDescription with auth and links
ErrorThrownAction triggers an AUTH_EXPIRED in middleware. AuthReducer
extracts auth links to upddate state.links. It's unclear what the shape
is of auth.links:
Errors.test.js utilizes an auth.links of type
arrayOf({
name: string,
label:string,
login: string,
logout: string,
callback: string,
})
OrganizationsPage consumes links w/ shape of
shape({
organizations: string.isRequired,
config: shape({
auth: string.isRequired,
}).isRequired,
})
UsersPage consumes links w/ shape of
shape({
users: string.isRequired,
}),
ProvidersPage consumes links w/ shape of
shape({
organizations: string.isRequired,
}),
Purgatory consumes links w/ shape of
shape({
me: string,
}),
UserNavBlock at some point expected
shape({
me: string,
external: shape({
custom: arrayOf(
shape({
name: string.isRequired,
url: string.isRequired,
})
),
}),
})
| TypeScript | mit | influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,influxdb/influxdb | ---
+++
@@ -10,12 +10,12 @@
interface ErrorThrownAction {
type: 'ERROR_THROWN'
- error: Error
+ error: ErrorDescription
altText?: string
alertType?: AlertType
}
export const errorThrown = (
- error: Error,
+ error: ErrorDescription,
altText?: string,
alertType?: AlertType
): ErrorThrownAction => ({
@@ -24,3 +24,12 @@
altText,
alertType,
})
+
+interface ErrorDescription {
+ status: number
+ auth: {
+ links: {
+ me: string
+ }
+ }
+} |
6bd8233a57e2b74010be8a33bab195ced820db58 | src/query/options/HasConstraint.ts | src/query/options/HasConstraint.ts | import Query from '../Query'
export type Constraint = (query: Query) => boolean
export default Constraint
| import Query from '../Query'
export type Constraint = (query: Query) => boolean | void
export default Constraint
| Change return type of has constraint to not expect a boolean | Change return type of has constraint to not expect a boolean
| TypeScript | mit | revolver-app/vuex-orm,revolver-app/vuex-orm | ---
+++
@@ -1,5 +1,5 @@
import Query from '../Query'
-export type Constraint = (query: Query) => boolean
+export type Constraint = (query: Query) => boolean | void
export default Constraint |
090ff88fe5a4fc8be9f40d9517af006143dc9de3 | src/test/e2e/welcome.po.ts | src/test/e2e/welcome.po.ts | /// <reference path="../../../dts/protractor.d.ts" />
declare var by: AureliaSeleniumPlugins;
class PageObject_Welcome {
constructor() {
}
getGreeting() {
return element(by.tagName('h2')).getText();
}
setFirstname(value) {
return element(by.valueBind('firstName')).clear()["sendKeys"](value);
}
setLastname(value) {
return element(by.valueBind('lastName')).clear()["sendKeys"](value);
}
getFullname() {
return element(by.css('.help-block')).getText();
}
pressSubmitButton() {
return element(by.css('button[type="submit"]')).click();
}
openAlertDialog() {
return browser.wait(() => {
this.pressSubmitButton();
return browser.switchTo().alert().then(
// use alert.accept instead of alert.dismiss which results in a browser crash
function(alert) { alert.accept(); return true; },
function() { return false; }
);
}, 100);
}
}
export = PageObject_Welcome;
| /// <reference path="../../../dts/protractor.d.ts" />
declare var by: AureliaSeleniumPlugins;
class PageObject_Welcome {
constructor() {
}
getGreeting() {
return element(by.tagName('h2')).getText();
}
setFirstname(value) {
var el = element(by.valueBind('firstName'));
el.clear();
return el.sendKeys(value);
}
setLastname(value) {
var el = element(by.valueBind('lastName'));
el.clear();
return el.sendKeys(value);
}
getFullname() {
return element(by.css('.help-block')).getText();
}
pressSubmitButton() {
return element(by.css('button[type="submit"]')).click();
}
openAlertDialog() {
return browser.wait(() => {
this.pressSubmitButton();
return browser.switchTo().alert().then(
// use alert.accept instead of alert.dismiss which results in a browser crash
function(alert) { alert.accept(); return true; },
function() { return false; }
);
}, 100);
}
}
export = PageObject_Welcome;
| Rewrite e2e test to avoid compilation warning | Rewrite e2e test to avoid compilation warning
| TypeScript | mit | bohnen/aurelia-skeleton-navigation-gulp-typescript,Enrapt/aurelia-skeleton-navigation-gulp-typescript,Enrapt/aurelia-skeleton-navigation-gulp-typescript,bohnen/aurelia-skeleton-navigation-gulp-typescript,bohnen/aurelia-skeleton-navigation-gulp-typescript,Enrapt/aurelia-skeleton-navigation-gulp-typescript | ---
+++
@@ -13,11 +13,15 @@
}
setFirstname(value) {
- return element(by.valueBind('firstName')).clear()["sendKeys"](value);
+ var el = element(by.valueBind('firstName'));
+ el.clear();
+ return el.sendKeys(value);
}
setLastname(value) {
- return element(by.valueBind('lastName')).clear()["sendKeys"](value);
+ var el = element(by.valueBind('lastName'));
+ el.clear();
+ return el.sendKeys(value);
}
getFullname() { |
c3347661047dc7cc25e7e3300c9097e702a0cbc5 | src/tests/full-icu.spec.ts | src/tests/full-icu.spec.ts | import { getResolvedLocale } from '../helpers/get-resolved-locale.js';
import { APP_INDEX_URL } from './constants.js';
import {
ok, strictEqual,
} from './helpers/typed-assert.js';
describe('timezones', () => {
before(async () => {
await browser.url(APP_INDEX_URL);
});
function hasFullICU() {
try {
const january = new Date(9e8);
const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
return spanish.format(january) === 'enero';
} catch (err) {
return false;
}
}
it(`supports full ICU`, async () => {
ok(hasFullICU());
strictEqual(
Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
}).format(new Date('2020-02-02')),
'Feb 2, 2020'
);
strictEqual(getResolvedLocale(), 'en-US');
const content = await browser.executeAsync(async () => {
const a = document.createElement('app-datepicker');
document.body.appendChild(a);
await a.updateComplete;
return (
Array.from(
a.shadowRoot?.querySelectorAll('.full-calendar__day') ?? []
)[2]?.outerHTML ?? 'nil'
);
});
console.debug('1', content);
strictEqual(content, '');
});
});
| import { getResolvedLocale } from '../helpers/get-resolved-locale.js';
import { APP_INDEX_URL } from './constants.js';
import {
ok, strictEqual,
} from './helpers/typed-assert.js';
describe('timezones', () => {
before(async () => {
await browser.url(APP_INDEX_URL);
});
function hasFullICU() {
try {
const january = new Date(9e8);
const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
return spanish.format(january) === 'enero';
} catch (err) {
return false;
}
}
it(`supports full ICU`, async () => {
ok(hasFullICU());
strictEqual(
Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
}).format(new Date('2020-02-02')),
'Feb 2, 2020'
);
strictEqual(getResolvedLocale(), 'en-US');
const content = await browser.executeAsync(async (done) => {
const a = document.createElement('app-datepicker');
document.body.appendChild(a);
await a.updateComplete;
done(
Array.from(
a.shadowRoot?.querySelectorAll('.full-calendar__day') ?? []
)[2]?.outerHTML ?? 'nil'
);
});
console.debug('1', content);
strictEqual(content, '');
});
});
| Call done() when async task finishes | ci: Call done() when async task finishes
| TypeScript | mit | motss/app-datepicker,motss/app-datepicker,motss/app-datepicker,motss/jv-datepicker | ---
+++
@@ -31,14 +31,14 @@
);
strictEqual(getResolvedLocale(), 'en-US');
- const content = await browser.executeAsync(async () => {
+ const content = await browser.executeAsync(async (done) => {
const a = document.createElement('app-datepicker');
document.body.appendChild(a);
await a.updateComplete;
- return (
+ done(
Array.from(
a.shadowRoot?.querySelectorAll('.full-calendar__day') ?? []
)[2]?.outerHTML ?? 'nil' |
1eb63ba789319df24bbe98863d5aee91e0b80e1a | backend/src/resolvers/index.ts | backend/src/resolvers/index.ts | import { Query } from './Query';
import { auth } from './Mutation/auth';
import { cities } from './Mutation/cities';
import { tests } from './Mutation/tests';
import { schools } from './Mutation/schools';
import { olympiads } from './Mutation/olympiads';
import { questions } from './Mutation/questions';
import { AuthPayload } from './AuthPayload';
export default {
Query,
// https://github.com/prisma/prisma/issues/2225#issuecomment-413265367
Node: {
__resolveType(obj, ctx, info) {
return obj.__typename;
},
},
Mutation: {
...cities,
...auth,
...tests,
...schools,
...olympiads,
...questions,
},
AuthPayload,
};
| import { Query } from './Query';
import { auth } from './Mutation/auth';
import { cities } from './Mutation/cities';
import { tests } from './Mutation/tests';
import { schools } from './Mutation/schools';
import { olympiads } from './Mutation/olympiads';
import { questions } from './Mutation/questions';
import { AuthPayload } from './AuthPayload';
import { prisma } from '../generated/prisma-client';
export default {
Query,
// Isto é necessário porque o cliente Prisma só busca o valores 'escalares',
// mas não as 'relações'. O campo 'questions' não é buscado pelo cliente
// quando invocamos os métodos 'test' or 'tests', como é feito nos resolvers
// 'test' ou 'tests', respectivamente (veja Query.ts).
// https://www.prisma.io/tutorials/a-guide-to-common-resolver-patterns-ct08/#scenario:-implementing-relations-with-prisma-client
Test: {
/**
* Busca as questões relacionadas a uma prova.
* @param parent instância da prova (Test)
*/
questions(parent) {
return prisma.test({ id: parent.id }).questions();
},
},
// https://github.com/prisma/prisma/issues/2225#issuecomment-413265367
Node: {
__resolveType(obj, ctx, info) {
return obj.__typename;
},
},
Mutation: {
...cities,
...auth,
...tests,
...schools,
...olympiads,
...questions,
},
AuthPayload,
};
| Add 'type resolver' for the Test type | Add 'type resolver' for the Test type
This is necessary because Prisma client only resolves 'scalar' values,
no relations. The 'questions' field is not fetched by the client when
invoking the 'test' or 'tests' method as is done in the 'test' or
'tests' resolvers, respectively.
| TypeScript | agpl-3.0 | iquabius/olimat,iquabius/olimat,iquabius/olimat | ---
+++
@@ -6,9 +6,24 @@
import { olympiads } from './Mutation/olympiads';
import { questions } from './Mutation/questions';
import { AuthPayload } from './AuthPayload';
+import { prisma } from '../generated/prisma-client';
export default {
Query,
+ // Isto é necessário porque o cliente Prisma só busca o valores 'escalares',
+ // mas não as 'relações'. O campo 'questions' não é buscado pelo cliente
+ // quando invocamos os métodos 'test' or 'tests', como é feito nos resolvers
+ // 'test' ou 'tests', respectivamente (veja Query.ts).
+ // https://www.prisma.io/tutorials/a-guide-to-common-resolver-patterns-ct08/#scenario:-implementing-relations-with-prisma-client
+ Test: {
+ /**
+ * Busca as questões relacionadas a uma prova.
+ * @param parent instância da prova (Test)
+ */
+ questions(parent) {
+ return prisma.test({ id: parent.id }).questions();
+ },
+ },
// https://github.com/prisma/prisma/issues/2225#issuecomment-413265367
Node: {
__resolveType(obj, ctx, info) { |
3a45a960d665ff5daa024625b91cef64bc44ea0d | templates/app/src/_name.ts | templates/app/src/_name.ts | import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
angular.module("<%= appName %>", [
"ui.router"
])
.config(<%= pAppName %>Config); | import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
import { <%= pAppName %>Run } from "./<%= hAppName %>.run";
angular.module("<%= appName %>", [
"ui.router"
])
.config(<%= pAppName %>Config)
.run(<%= pAppName %>Run); | Add the run function to entry point | Add the run function to entry point
| TypeScript | mit | Kurtz1993/ngts-cli,Kurtz1993/ngts-cli,Kurtz1993/ngts-cli | ---
+++
@@ -1,6 +1,8 @@
import { <%= pAppName %>Config } from "./<%= hAppName %>.config";
+import { <%= pAppName %>Run } from "./<%= hAppName %>.run";
angular.module("<%= appName %>", [
"ui.router"
])
-.config(<%= pAppName %>Config);
+.config(<%= pAppName %>Config)
+.run(<%= pAppName %>Run); |
77d5dc82b3791d87536278104c4a54d1bd02c289 | fetcher/index.ts | fetcher/index.ts | 'use strict'; // XXX
import * as https from 'https';
import * as fs from 'fs';
import * as path from 'path';
import * as mkdirp from 'mkdirp';
import * as request from 'request';
function download(org: string, url: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const dirPath = path.join(__dirname, 'data', org);
mkdirp.sync(dirPath);
const htmlPath = path.join(dirPath, 'index.html');
const writeStream = fs.createWriteStream(htmlPath);
writeStream.on('error', (err) => {
reject(err);
});
writeStream.on('finish', () => {
resolve();
});
request(url).pipe(writeStream);
});
}
export function fetch() {
return Promise.all([
download('w3c', 'https://w3c.github.io/html/'),
download('whatwg', 'https://html.spec.whatwg.org/'),
])
} | 'use strict'; // XXX
import * as https from 'https';
import * as fs from 'fs';
import * as path from 'path';
import * as mkdirp from 'mkdirp';
import * as request from 'request';
function download(org: string, url: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const dirPath = path.join(__dirname, 'data', org);
mkdirp.sync(dirPath);
const htmlPath = path.join(dirPath, 'index.html');
const writeStream = fs.createWriteStream(htmlPath);
writeStream.on('error', (err) => {
reject(err);
});
writeStream.on('finish', () => {
resolve();
});
request(url).pipe(writeStream);
});
}
export function fetch() {
return Promise.all([
download('w3c', 'https://w3c.github.io/html/single-page.html'),
download('whatwg', 'https://html.spec.whatwg.org/'),
])
} | Update W3C HTML 5.1 URL | Update W3C HTML 5.1 URL
| TypeScript | mit | takenspc/diffofhtmlsgenerator | ---
+++
@@ -27,7 +27,7 @@
export function fetch() {
return Promise.all([
- download('w3c', 'https://w3c.github.io/html/'),
+ download('w3c', 'https://w3c.github.io/html/single-page.html'),
download('whatwg', 'https://html.spec.whatwg.org/'),
])
} |
81e1841b1c3bb88b8e6e14b74ffddabe3711ee43 | src/Types.ts | src/Types.ts | import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
| import { IncomingMessage } from 'http';
import { Buffer } from 'buffer';
/**
* Simple utility Hash array type
*/
export type ObjectMap<T> = {[key: string]: T};
/**
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
/**
* Enumaration of valid HTTP verbs.
*/
export const HttpVerbs: ObjectMap<HttpVerb> = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
OPTIONS: 'OPTIONS',
PATCH: 'PATCH'
};
/**
* An HTTP Request response containing both the response's message information and the response's body.
*
* Used by `ProxyHandler`.
* @type {IncomingMessage}
*/
export interface ProxyResponse {
message: IncomingMessage,
body: string | Buffer
}
/**
* Accessible types for a CORS Policy Access-Control headers.
*/
export type CorsAccessControlValue<T> = T[]|'*'|undefined;
| Add an enumeration of HTTP verb. | Add an enumeration of HTTP verb.
| TypeScript | mit | syrp-nz/ts-lambda-handler,syrp-nz/ts-lambda-handler | ---
+++
@@ -10,6 +10,18 @@
* A Valid HTTP operation
*/
export type HttpVerb = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'PATCH';
+
+/**
+ * Enumaration of valid HTTP verbs.
+ */
+export const HttpVerbs: ObjectMap<HttpVerb> = {
+ GET: 'GET',
+ POST: 'POST',
+ PUT: 'PUT',
+ DELETE: 'DELETE',
+ OPTIONS: 'OPTIONS',
+ PATCH: 'PATCH'
+};
/**
* An HTTP Request response containing both the response's message information and the response's body. |
adc24e3a7187e8dbf5ce3f8913a845e99fb478d6 | packages/platform/common/src/utils/getStaticsOptions.ts | packages/platform/common/src/utils/getStaticsOptions.ts | import {PlatformStaticsOptions, PlatformStaticsSettings} from "../config/interfaces/PlatformStaticsSettings";
function mapOptions(options: any) {
const opts: PlatformStaticsOptions =
typeof options === "string"
? {
root: options,
hook: "$afterRoutesInit"
}
: options;
return opts;
}
export function getStaticsOptions(statics?: PlatformStaticsSettings): {path: string; options: PlatformStaticsOptions}[] {
return Object.entries(statics || {}).reduce((statics, [path, items]) => {
[].concat(items as any).forEach((options) => {
statics.push({path, options: mapOptions(options)});
});
return statics;
}, [] as {path: string; options: PlatformStaticsOptions}[]);
}
| import {getValue} from "@tsed/core";
import {PlatformStaticsOptions, PlatformStaticsSettings} from "../config/interfaces/PlatformStaticsSettings";
function mapOptions(options: any): any {
const opts: PlatformStaticsOptions = typeof options === "string" ? {root: options} : options;
return {
...opts,
hook: getValue(opts, "hook", "$afterRoutesInit")
};
}
export function getStaticsOptions(statics?: PlatformStaticsSettings): {path: string; options: PlatformStaticsOptions}[] {
return Object.entries(statics || {}).reduce((statics, [path, items]) => {
[].concat(items as any).forEach((options) => {
statics.push({path, options: mapOptions(options)});
});
return statics;
}, [] as {path: string; options: PlatformStaticsOptions}[]);
}
| Fix regression on statics options | fix(common): Fix regression on statics options
Closes: #1600
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,14 +1,12 @@
+import {getValue} from "@tsed/core";
import {PlatformStaticsOptions, PlatformStaticsSettings} from "../config/interfaces/PlatformStaticsSettings";
-function mapOptions(options: any) {
- const opts: PlatformStaticsOptions =
- typeof options === "string"
- ? {
- root: options,
- hook: "$afterRoutesInit"
- }
- : options;
- return opts;
+function mapOptions(options: any): any {
+ const opts: PlatformStaticsOptions = typeof options === "string" ? {root: options} : options;
+ return {
+ ...opts,
+ hook: getValue(opts, "hook", "$afterRoutesInit")
+ };
}
export function getStaticsOptions(statics?: PlatformStaticsSettings): {path: string; options: PlatformStaticsOptions}[] { |
1be4bd4d8db31f69e562a4b8a07ba7feb75ddcbc | type/index.d.ts | type/index.d.ts | // Type definitions for super-image 2.0.0
// Project: https://github.com/openfresh/super-image
import * as React from 'react';
declare namespace SuperImage {
export interface Source {
srcSet?: string;
sizes?: string;
media?: string;
type?: string;
}
export interface Props {
src: string;
sources?: Source[];
width?: string;
height?: string;
alt?: string;
className?: string;
fit?: 'contain' | 'cover';
fitFallback?: boolean;
flexible?: boolean;
}
}
declare class SuperImage extends React.Component<SuperImage.Props> {}
export = SuperImage;
| // Type definitions for super-image 2.0.0
// Project: https://github.com/openfresh/super-image
import * as React from 'react';
declare namespace SuperImage {
export interface Props {
src: string;
sources?: React.SourceHTMLAttributes<HTMLSourceElement>[];
width?: number | string;
height?: number | string;
alt?: string;
className?: string;
fit?: 'contain' | 'cover';
fitFallback?: boolean;
flexible?: boolean;
}
}
declare class SuperImage extends React.Component<SuperImage.Props> {}
export = SuperImage;
| Fix to correctly type source attributes | Fix to correctly type source attributes
| TypeScript | mit | openfresh/super-image | ---
+++
@@ -4,18 +4,11 @@
import * as React from 'react';
declare namespace SuperImage {
- export interface Source {
- srcSet?: string;
- sizes?: string;
- media?: string;
- type?: string;
- }
-
export interface Props {
src: string;
- sources?: Source[];
- width?: string;
- height?: string;
+ sources?: React.SourceHTMLAttributes<HTMLSourceElement>[];
+ width?: number | string;
+ height?: number | string;
alt?: string;
className?: string;
fit?: 'contain' | 'cover'; |
50d7d73affc1f9bfc31a6ba8e39c1d79e0d34f52 | src/documentlink.ts | src/documentlink.ts | import * as vscode from 'vscode';
import { findResourceFormat } from './autocompletion/model';
import { getConfiguration } from './configuration';
import { Index } from './index';
export class DocumentLinkProvider implements vscode.DocumentLinkProvider {
constructor(private index: Index) { }
provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DocumentLink[]> {
let index = this.index.getOrIndexDocument(document, { exclude: getConfiguration().indexing.exclude });
if (!index)
return [];
return index.sections.map((s) => {
if (!s.type)
return null;
let doc = findResourceFormat(s.sectionType, s.type);
if (!doc)
return null;
return new vscode.DocumentLink(s.typeLocation.range, vscode.Uri.parse(doc.url));
}).filter((d) => d != null);
}
}; | import * as vscode from 'vscode';
import { findResourceFormat } from './autocompletion/model';
import { getConfiguration } from './configuration';
import { Index } from './index';
import { IndexLocator } from './index/index-locator';
export class DocumentLinkProvider implements vscode.DocumentLinkProvider {
constructor(private indexLocator: IndexLocator) { }
provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DocumentLink[]> {
let index = this.indexLocator.getIndexForDoc(document).getOrIndexDocument(document, { exclude: getConfiguration().indexing.exclude });
if (!index)
return [];
return index.sections.map((s) => {
if (!s.type)
return null;
let doc = findResourceFormat(s.sectionType, s.type);
if (!doc)
return null;
return new vscode.DocumentLink(s.typeLocation.range, vscode.Uri.parse(doc.url));
}).filter((d) => d != null);
}
}; | Use IndexLocator instead of Index | DocumentLinkProvider: Use IndexLocator instead of Index
| TypeScript | mpl-2.0 | hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform,mauve/vscode-terraform,mauve/vscode-terraform,hashicorp/vscode-terraform | ---
+++
@@ -2,12 +2,13 @@
import { findResourceFormat } from './autocompletion/model';
import { getConfiguration } from './configuration';
import { Index } from './index';
+import { IndexLocator } from './index/index-locator';
export class DocumentLinkProvider implements vscode.DocumentLinkProvider {
- constructor(private index: Index) { }
+ constructor(private indexLocator: IndexLocator) { }
provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DocumentLink[]> {
- let index = this.index.getOrIndexDocument(document, { exclude: getConfiguration().indexing.exclude });
+ let index = this.indexLocator.getIndexForDoc(document).getOrIndexDocument(document, { exclude: getConfiguration().indexing.exclude });
if (!index)
return [];
return index.sections.map((s) => { |
c9348e0a0088b30e2ba9a4a2211559e78d203244 | package/test/test-browser.ts | package/test/test-browser.ts | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
);
if ((<any>window).MONACO) {
runTest();
} else {
(<any>window).REGISTER_MONACO_INIT_CALLBACK(() => {
runTest();
});
}
function runTest(): void {
const context = require.context('../src/browser', true, /\.spec\.ts$/);
context.keys().map(context);
}
| // This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
);
const context = require.context('../src/browser', true, /\.spec\.ts$/);
context.keys().map(context);
| Fix old settings which for monaco editor | Fix old settings which for monaco editor
| TypeScript | mit | seokju-na/geeks-diary,seokju-na/geeks-diary,seokju-na/geeks-diary | ---
+++
@@ -16,17 +16,5 @@
platformBrowserDynamicTesting(),
);
-
-if ((<any>window).MONACO) {
- runTest();
-} else {
- (<any>window).REGISTER_MONACO_INIT_CALLBACK(() => {
- runTest();
- });
-}
-
-
-function runTest(): void {
- const context = require.context('../src/browser', true, /\.spec\.ts$/);
- context.keys().map(context);
-}
+const context = require.context('../src/browser', true, /\.spec\.ts$/);
+context.keys().map(context); |
943f762e7d6b0f578e06a5347e8ccc4acd6fd58f | lib/theming/src/themes/light.ts | lib/theming/src/themes/light.ts | import { color, typography, background } from '../base';
import { ThemeVars } from '../types';
const theme: ThemeVars = {
base: 'light',
// Storybook-specific color palette
colorPrimary: '#FF4785', // coral
colorSecondary: '#1EA7FD', // ocean
// UI
appBg: background.app,
appContentBg: color.lightest,
appBorderColor: color.border,
appBorderRadius: 4,
// Fonts
fontBase: typography.fonts.base,
fontCode: typography.fonts.mono,
// Text colors
textColor: color.darkest,
textInverseColor: color.lightest,
textMutedColor: color.dark,
// Toolbar default and active colors
barTextColor: color.dark,
barSelectedColor: color.secondary,
barBg: color.lightest,
// Form colors
inputBg: color.lightest,
inputBorder: color.border,
inputTextColor: color.darkest,
inputBorderRadius: 4,
};
export default theme;
| import { color, typography, background } from '../base';
import { ThemeVars } from '../types';
const theme: ThemeVars = {
base: 'light',
// Storybook-specific color palette
colorPrimary: '#FF4785', // coral
colorSecondary: '#1EA7FD', // ocean
// UI
appBg: background.app,
appContentBg: color.lightest,
appBorderColor: color.border,
appBorderRadius: 4,
// Fonts
fontBase: typography.fonts.base,
fontCode: typography.fonts.mono,
// Text colors
textColor: color.darkest,
textInverseColor: color.lightest,
textMutedColor: color.dark,
// Toolbar default and active colors
barTextColor: color.mediumdark,
barSelectedColor: color.secondary,
barBg: color.lightest,
// Form colors
inputBg: color.lightest,
inputBorder: color.border,
inputTextColor: color.darkest,
inputBorderRadius: 4,
};
export default theme;
| Undo theme change – need to consider this in context of a larger redesign not a piecemeal change | Undo theme change – need to consider this in context of a larger redesign not a piecemeal change
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -24,7 +24,7 @@
textMutedColor: color.dark,
// Toolbar default and active colors
- barTextColor: color.dark,
+ barTextColor: color.mediumdark,
barSelectedColor: color.secondary,
barBg: color.lightest,
|
69431de0b646a030fdbf0943697350c2d0944ed2 | src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/config.template.ts | src/picturepark-sdk-v1-angular/projects/picturepark-sdk-v1-angular/src/tests/config.template.ts | import { HttpClientModule } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import {} from 'jasmine';
import { AuthService } from '../lib/services/auth.service';
import { AccessTokenAuthService } from '../lib/services/access-token-auth.service';
import { PICTUREPARK_CONFIGURATION } from '../lib/services/base.service';
import { PictureparkConfiguration } from '../lib/models/configuration';
import { PICTUREPARK_API_URL } from '../lib/services/api-services';
export const testUrl = '{Server}';
export const testAccessToken = '{AccessToken}';
export const testCustomerAlias = '{CustomerAlias}';
export function configureTest() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [
{ provide: AuthService, useClass: AccessTokenAuthService },
{ provide: PICTUREPARK_API_URL, useValue: testUrl },
{
provide: PICTUREPARK_CONFIGURATION,
useValue: <PictureparkConfiguration>{
customerAlias: testCustomerAlias,
accessToken: testAccessToken,
},
},
],
});
TestBed.compileComponents();
}
| import { HttpClientModule } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import {} from 'jasmine';
import { AuthService } from '../lib/services/auth.service';
import { AccessTokenAuthService } from '../lib/services/access-token-auth.service';
import { PICTUREPARK_CONFIGURATION } from '../lib/services/base.service';
import { PictureparkConfiguration } from '../lib/models/configuration';
import { PICTUREPARK_API_URL } from '../lib/services/api-services';
export const testUrl = '{Server}';
export const testAccessToken = '{AccessToken}';
export const testCustomerAlias = '{CustomerAlias}';
export function configureTest() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 25000;
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [
{ provide: AuthService, useClass: AccessTokenAuthService },
{ provide: PICTUREPARK_API_URL, useValue: testUrl },
{
provide: PICTUREPARK_CONFIGURATION,
useValue: <PictureparkConfiguration>{
customerAlias: testCustomerAlias,
accessToken: testAccessToken,
},
},
],
});
TestBed.compileComponents();
}
| Extend jasmine timeout to 25s | Extend jasmine timeout to 25s
| TypeScript | mit | Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript | ---
+++
@@ -12,7 +12,7 @@
export const testCustomerAlias = '{CustomerAlias}';
export function configureTest() {
- jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
+ jasmine.DEFAULT_TIMEOUT_INTERVAL = 25000;
TestBed.configureTestingModule({
imports: [HttpClientModule],
providers: [ |
eb41396452c5f81cf08e99b18a1a59109fc2cdc9 | core/test/datastore/helpers.spec.ts | core/test/datastore/helpers.spec.ts | import { isProjectDocument } from "../../src/datastore/helpers";
describe('helpers', () => {
it('isProjectDocument', () => {
const result = isProjectDocument({ resource: { id: 'project' }} as any);
expect(true).toBeTruthy();
});
});
| import { isProjectDocument } from '../../src/datastore/helpers';
describe('helpers', () => {
it('isProjectDocument', () => {
const result = isProjectDocument({ resource: { id: 'project' }} as any);
expect(result).toBeTruthy();
});
});
| Make datastore helpers test meaningful | Make datastore helpers test meaningful
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -1,4 +1,4 @@
-import { isProjectDocument } from "../../src/datastore/helpers";
+import { isProjectDocument } from '../../src/datastore/helpers';
describe('helpers', () => {
@@ -6,6 +6,6 @@
it('isProjectDocument', () => {
const result = isProjectDocument({ resource: { id: 'project' }} as any);
- expect(true).toBeTruthy();
+ expect(result).toBeTruthy();
});
}); |
34157af8a56df0b268a6b1d6e6db624f9866cdf5 | ui/src/api/image.ts | ui/src/api/image.ts | export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const imageUrl = getImageUrl(project, `${id}.jp2`, maxWidth, maxHeight, token);
const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
export const getImageUrl = (project: string, path: string, maxWidth: number,
maxHeight: number, token: string, format = 'jpg'): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${encodeURIComponent(path)}`
+ `/${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
};
export const makeUrl = (project: string, id: string, token?: string): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${id}.jp2/${token_}/info.json`;
}; | export const fetchImage = async (project: string,
id: string,
maxWidth: number,
maxHeight: number,
token: string): Promise<string> => {
const imageUrl = getImageUrl(project, `${id}.jp2`, maxWidth, maxHeight, token);
const response = await fetch(imageUrl);
if (response.ok) return URL.createObjectURL(await response.blob());
else throw (await response.json());
};
export const getImageUrl = (project: string, path: string, maxWidth: number,
maxHeight: number, token: string, format = 'jpg'): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${encodeURIComponent(path)}/`
+ `${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
};
export const makeUrl = (project: string, id: string, token?: string): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
return `/api/images/${project}/${id}.jp2/${token_}/info.json`;
}; | Move slash to first part of splitted string | Move slash to first part of splitted string
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -15,8 +15,8 @@
maxHeight: number, token: string, format = 'jpg'): string => {
const token_ = token === undefined || token === '' ? 'anonymous' : token;
- return `/api/images/${project}/${encodeURIComponent(path)}`
- + `/${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
+ return `/api/images/${project}/${encodeURIComponent(path)}/`
+ + `${token_}/full/!${maxWidth},${maxHeight}/0/default.${format}`;
};
|
9edf863887e7674e430b1d9fb0995abf1ed16ec1 | src/js/components/Search.tsx | src/js/components/Search.tsx | import React, { MutableRefObject } from 'react'
import { observer } from 'mobx-react'
import Input from '@material-ui/core/Input'
import { useStore } from './StoreContext'
export type InputRefProps = { inputRef: MutableRefObject<HTMLInputElement> }
export default observer(({ inputRef }: InputRefProps) => {
const { userStore, searchStore } = useStore()
return (
<Input
fullWidth
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
placeholder='Search your tab title...'
onChange={e => searchStore.search(e.target.value)}
onFocus={() => {
const { search, query, startType } = searchStore
search(query)
startType()
}}
onBlur={() => searchStore.stopType()}
value={searchStore.query}
/>
)
})
| import React, { MutableRefObject } from 'react'
import { observer } from 'mobx-react'
import { useStore } from './StoreContext'
import { TextField } from '@material-ui/core'
export type InputRefProps = { inputRef: MutableRefObject<HTMLInputElement> }
export default observer(({ inputRef }: InputRefProps) => {
const { userStore, searchStore } = useStore()
return (
<TextField
fullWidth
type='search'
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
placeholder='Search your tab title...'
onChange={e => searchStore.search(e.target.value)}
onFocus={() => {
const { search, query, startType } = searchStore
search(query)
startType()
}}
onBlur={() => searchStore.stopType()}
value={searchStore.query}
/>
)
})
| Add a clear button for search box | feat: Add a clear button for search box
| TypeScript | mit | xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2 | ---
+++
@@ -1,15 +1,16 @@
import React, { MutableRefObject } from 'react'
import { observer } from 'mobx-react'
-import Input from '@material-ui/core/Input'
import { useStore } from './StoreContext'
+import { TextField } from '@material-ui/core'
export type InputRefProps = { inputRef: MutableRefObject<HTMLInputElement> }
export default observer(({ inputRef }: InputRefProps) => {
const { userStore, searchStore } = useStore()
return (
- <Input
+ <TextField
fullWidth
+ type='search'
autoFocus={userStore.autoFocusSearch}
inputProps={{ ref: inputRef }}
placeholder='Search your tab title...' |
09a649b3f28351bb59d083bba2bffb90f8ea5b49 | src/Components/Publishing/Layouts/NewsLayout.tsx | src/Components/Publishing/Layouts/NewsLayout.tsx | import React, { Component } from "react"
import styled from "styled-components"
import { NewsHeadline } from "../News/NewsHeadline"
import { NewsSections } from "../News/NewsSections"
interface Props {
article: any
isTruncated?: boolean
}
interface State {
isTruncated: boolean
}
interface NewsContainerProps {
isTruncated: boolean
}
export class NewsLayout extends Component<Props, State> {
state = {
isTruncated: this.props.isTruncated || true,
}
render() {
const { article } = this.props
const { isTruncated } = this.state
return (
<NewsContainer
onClick={() =>
this.setState({
isTruncated: false,
})}
isTruncated={isTruncated}
>
<NewsHeadline article={article} />
<NewsSections article={article} isTruncated={isTruncated} />
</NewsContainer>
)
}
}
const NewsContainer = styled.div`
max-width: 780px;
margin: 40px auto;
${(props: NewsContainerProps) =>
props.isTruncated &&
`
&:hover {
outline: 1px solid gray;
outline-offset: 30px;
}
`};
`
| import React, { Component } from "react"
import styled from "styled-components"
import { NewsHeadline } from "../News/NewsHeadline"
import { NewsSections } from "../News/NewsSections"
interface Props {
article: any
isTruncated?: boolean
}
interface State {
isTruncated: boolean
}
interface NewsContainerProps {
isTruncated: boolean
}
export class NewsLayout extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
isTruncated: this.props.isTruncated || true,
}
}
render() {
const { article } = this.props
const { isTruncated } = this.state
return (
<NewsContainer
onClick={() =>
this.setState({
isTruncated: false,
})}
isTruncated={isTruncated}
>
<NewsHeadline article={article} />
<NewsSections article={article} isTruncated={isTruncated} />
</NewsContainer>
)
}
}
const NewsContainer = styled.div`
max-width: 780px;
margin: 40px auto;
${(props: NewsContainerProps) =>
props.isTruncated &&
`
&:hover {
outline: 1px solid gray;
outline-offset: 30px;
}
`};
`
| Use constructor to set state | Use constructor to set state
| TypeScript | mit | artsy/reaction-force,artsy/reaction,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction-force,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction | ---
+++
@@ -17,8 +17,12 @@
}
export class NewsLayout extends Component<Props, State> {
- state = {
- isTruncated: this.props.isTruncated || true,
+ constructor(props: Props) {
+ super(props)
+
+ this.state = {
+ isTruncated: this.props.isTruncated || true,
+ }
}
render() { |
abfd38a0f59113b07bb08f78b8ff57648afad131 | client/environments/environment.prod.ts | client/environments/environment.prod.ts | export const environment = {
production: true,
backend: {
url: 'https://ng2-training.herokuapp.com/api'
}
};
| export const environment = {
production: true,
backend: {
url: '/api'
}
};
| Set backend url as relative | Set backend url as relative
| TypeScript | mit | fvilers/angular2-training,fvilers/angular2-training,fvilers/angular2-training | ---
+++
@@ -1,6 +1,6 @@
export const environment = {
production: true,
backend: {
- url: 'https://ng2-training.herokuapp.com/api'
+ url: '/api'
}
}; |
130247f2823acb7d18d88eb3d6b1291ecc2b8e94 | app/src/lib/feature-flag.ts | app/src/lib/feature-flag.ts | const Disable = false
/**
* Enables the application to opt-in for preview features based on runtime
* checks. This is backed by the GITHUB_DESKTOP_PREVIEW_FEATURES environment
* variable, which is checked for non-development environments.
*/
function enableDevelopmentFeatures(): boolean {
if (Disable) {
return false
}
if (__DEV__) {
return true
}
if (process.env.GITHUB_DESKTOP_PREVIEW_FEATURES === '1') {
return true
}
return false
}
/** Should the app enable beta features? */
function enableBetaFeatures(): boolean {
return enableDevelopmentFeatures() || __RELEASE_CHANNEL__ === 'beta'
}
/** Should the new Compare view be enabled? */
export function enableCompareBranch(): boolean {
return enableBetaFeatures()
}
/** Should merge tool integration be enabled? */
export function enableMergeTool(): boolean {
return enableDevelopmentFeatures()
}
export function enableCompareSidebar(): boolean {
return true
}
| const Disable = false
/**
* Enables the application to opt-in for preview features based on runtime
* checks. This is backed by the GITHUB_DESKTOP_PREVIEW_FEATURES environment
* variable, which is checked for non-development environments.
*/
function enableDevelopmentFeatures(): boolean {
if (Disable) {
return false
}
if (__DEV__) {
return true
}
if (process.env.GITHUB_DESKTOP_PREVIEW_FEATURES === '1') {
return true
}
return false
}
/** Should the app enable beta features? */
function enableBetaFeatures(): boolean {
return enableDevelopmentFeatures() || __RELEASE_CHANNEL__ === 'beta'
}
/** Should the new Compare view be enabled? */
export function enableCompareBranch(): boolean {
return enableBetaFeatures()
}
/** Should merge tool integration be enabled? */
export function enableMergeTool(): boolean {
return enableDevelopmentFeatures()
}
export function enableCompareSidebar(): boolean {
return true
}
/** Should the Notification of Diverging From Default Branch (NDDB) feature be enabled? */
export function enableNotificationOfBranchUpdates(): boolean {
return enableDevelopmentFeatures()
}
| Add feature behind dev features | Add feature behind dev features
| TypeScript | mit | desktop/desktop,shiftkey/desktop,shiftkey/desktop,shiftkey/desktop,artivilla/desktop,artivilla/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,say25/desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,say25/desktop,kactus-io/kactus,kactus-io/kactus | ---
+++
@@ -39,3 +39,8 @@
export function enableCompareSidebar(): boolean {
return true
}
+
+/** Should the Notification of Diverging From Default Branch (NDDB) feature be enabled? */
+export function enableNotificationOfBranchUpdates(): boolean {
+ return enableDevelopmentFeatures()
+} |
f0c922bf19c018d14026a7a767fcfa69af7f7f94 | src/client/src/rt-components/tear-off/ExternalWindow.tsx | src/client/src/rt-components/tear-off/ExternalWindow.tsx | import { FC, useEffect } from 'react'
import { usePlatform, WindowConfig } from 'rt-components'
import { WindowCenterStatus } from './types'
const defaultConfig: WindowConfig = {
name: '',
url: '',
width: 600,
height: 640,
center: WindowCenterStatus.Parent,
}
export interface ExternalWindowProps {
title?: string
onBlock?: () => void
onUnload: () => void
config?: WindowConfig
}
const ExternalWindow: FC<ExternalWindowProps> = ({
title = '',
onBlock = null as () => void,
onUnload = null as () => void,
config = defaultConfig,
}) => {
const platform = usePlatform()
useEffect(() => {
let externalWindow: Window
const release = () => {
if (externalWindow) {
window.removeEventListener('beforeunload', release)
}
onUnload.call(null)
}
const getWindow = async () => {
externalWindow = await platform.window.open(config, release)
if (externalWindow) {
window.addEventListener('beforeunload', release)
}
}
getWindow()
return () => {
if (externalWindow) {
externalWindow.close()
}
}
}, [])
return null
}
export default ExternalWindow | import { FC, useEffect } from 'react'
import { usePlatform, WindowConfig } from 'rt-components'
import { WindowCenterStatus } from './types'
const defaultConfig: WindowConfig = {
name: '',
url: '',
width: 600,
height: 640,
center: WindowCenterStatus.Parent,
}
export interface ExternalWindowProps {
title?: string
onBlock?: () => void
onUnload: () => void
config?: WindowConfig
}
const ExternalWindow: FC<ExternalWindowProps> = ({
title = '',
onBlock = null as () => void,
onUnload = null as () => void,
config = defaultConfig,
}) => {
const platform = usePlatform()
useEffect(() => {
let externalWindow: Window
const release = () => {
if (externalWindow) {
window.removeEventListener('beforeunload', release)
}
if (typeof onUnload === 'function') {
onUnload.call(null)
}
}
const getWindow = async () => {
externalWindow = await platform.window.open(config, release)
if (externalWindow) {
window.addEventListener('beforeunload', release)
}
}
getWindow()
return () => {
if (externalWindow) {
externalWindow.close()
}
}
}, [])
return null
}
export default ExternalWindow
| Add type check for onUnload callback | Add type check for onUnload callback | TypeScript | apache-2.0 | AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud | ---
+++
@@ -33,7 +33,9 @@
window.removeEventListener('beforeunload', release)
}
- onUnload.call(null)
+ if (typeof onUnload === 'function') {
+ onUnload.call(null)
+ }
}
const getWindow = async () => { |
cc90653c0a115bdfa843dc8c1c4d5dc9ad8aeda1 | src/api/server/giphy.ts | src/api/server/giphy.ts | import 'whatwg-fetch';
export const BASE_URL = 'http://api.giphy.com/v1/gifs';
export function get(path): any {
return fetch(BASE_URL + path, {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json());
}
| import 'whatwg-fetch';
export const BASE_URL = 'https://api.giphy.com/v1/gifs';
export function get(path): any {
return fetch(BASE_URL + path, {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json());
}
| Use HTTPS for API requests | Use HTTPS for API requests
| TypeScript | mit | andrewlo/giphy-react-redux,andrewlo/giphy-react-redux,andrewlo/giphy-react-redux | ---
+++
@@ -1,6 +1,6 @@
import 'whatwg-fetch';
-export const BASE_URL = 'http://api.giphy.com/v1/gifs';
+export const BASE_URL = 'https://api.giphy.com/v1/gifs';
export function get(path): any {
return fetch(BASE_URL + path, { |
fcceaab2167a186d4982cf1beb4bd2f9e025dffe | webapp/src/db.ts | webapp/src/db.ts | declare var require:any;
var PouchDB = require("pouchdb")
import * as Promise from "bluebird";
(window as any).Promise = Promise;
export let db = new PouchDB("mbit", { revs_limit: 2 })
export class Table {
constructor(public name:string)
{
}
getAsync(id:string):Promise<any> {
return db.get(this.name + "--" + id).then((v:any) => {
v.id = id
return v
})
}
getAllAsync():Promise<any[]> {
return db.allDocs({
include_docs: true,
startkey: this.name + "--",
endkey: this.name + "--\uffff"
}).then((resp:any) => resp.rows.map((e:any) => e.doc))
}
deleteAsync(obj:any):Promise<void> {
return db.remove(obj)
}
setAsync(obj:any):Promise<string> {
if (obj.id && !obj._id)
obj._id = this.name + "--" + obj.id
return db.put(obj).then((resp:any) => resp.rev)
}
}
| declare var require:any;
var PouchDB = require("pouchdb")
import * as Promise from "bluebird";
(window as any).Promise = Promise;
(Promise as any).config({
// Enables all warnings except forgotten return statements.
warnings: {
wForgottenReturn: false
}
});
export let db = new PouchDB("mbit", { revs_limit: 2 })
export class Table {
constructor(public name:string)
{
}
getAsync(id:string):Promise<any> {
return db.get(this.name + "--" + id).then((v:any) => {
v.id = id
return v
})
}
getAllAsync():Promise<any[]> {
return db.allDocs({
include_docs: true,
startkey: this.name + "--",
endkey: this.name + "--\uffff"
}).then((resp:any) => resp.rows.map((e:any) => e.doc))
}
deleteAsync(obj:any):Promise<void> {
return db.remove(obj)
}
setAsync(obj:any):Promise<string> {
if (obj.id && !obj._id)
obj._id = this.name + "--" + obj.id
return db.put(obj).then((resp:any) => resp.rev)
}
}
| Disable forgotten promise return warning | Disable forgotten promise return warning
| TypeScript | mit | playi/pxt,playi/pxt,Microsoft/pxt,playi/pxt,Microsoft/pxt,switchinnovations/pxt,switch-education/pxt,Microsoft/pxt,switch-education/pxt,Microsoft/pxt,switchinnovations/pxt,switch-education/pxt,Microsoft/pxt,switchinnovations/pxt,switch-education/pxt,switch-education/pxt,playi/pxt,switchinnovations/pxt | ---
+++
@@ -3,6 +3,13 @@
import * as Promise from "bluebird";
(window as any).Promise = Promise;
+(Promise as any).config({
+ // Enables all warnings except forgotten return statements.
+ warnings: {
+ wForgottenReturn: false
+ }
+});
+
export let db = new PouchDB("mbit", { revs_limit: 2 })
export class Table { |
364b90133f5c7b9b66a590b9770800bcc155fea0 | src/Test/Html/Escaping/Content.ts | src/Test/Html/Escaping/Content.ts | import { expect } from 'chai'
import Up from '../../../index'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
describe('Inside plain text nodes, all instances of < and &', () => {
it('are replaced with "<" and "&", respectively', () => {
const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
})
})
describe('Inside a plain text node, >, \', and "', () => {
it('are preserved', () => {
const text = 'John said, "1 and 2 > 0. I can\'t believe it."'
const node = new PlainTextNode(text)
expect(Up.toHtml(node)).to.be.eql(text)
})
})
| import { expect } from 'chai'
import Up from '../../../index'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
describe('Inside plain text nodes, all instances of < and &', () => {
it('are escaped by replacing them with "<" and "&", respectively', () => {
const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
})
})
describe('Inside a plain text node, >, \', and "', () => {
it('are preserved', () => {
const text = 'John said, "1 and 2 > 0. I can\'t believe it."'
const node = new PlainTextNode(text)
expect(Up.toHtml(node)).to.be.eql(text)
})
})
describe("Inside a spoiler's label, all instances of < and &", () => {
it("are escaped", () => {
const up = new Up({
i18n: {
terms: { toggleSpoiler: '<_< & show & hide' }
}
})
const node = new SpoilerNode([])
const html =
'<span class="up-spoiler up-revealable">'
+ '<label for="up-spoiler-1"><_< & show & hide</label>'
+ '<input id="up-spoiler-1" type="checkbox">'
+ '<span></span>'
+ '</span>'
expect(up.toHtml(node)).to.be.eql(html)
})
})
| Add failing html escaping test | Add failing html escaping test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,10 +1,11 @@
import { expect } from 'chai'
import Up from '../../../index'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
describe('Inside plain text nodes, all instances of < and &', () => {
- it('are replaced with "<" and "&", respectively', () => {
+ it('are escaped by replacing them with "<" and "&", respectively', () => {
const node = new PlainTextNode('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
expect(Up.toHtml(node)).to.be.eql('4 & 5 < 10, and 6 & 7 < 10. Coincidence?')
})
@@ -19,3 +20,24 @@
})
})
+
+describe("Inside a spoiler's label, all instances of < and &", () => {
+ it("are escaped", () => {
+ const up = new Up({
+ i18n: {
+ terms: { toggleSpoiler: '<_< & show & hide' }
+ }
+ })
+
+ const node = new SpoilerNode([])
+
+ const html =
+ '<span class="up-spoiler up-revealable">'
+ + '<label for="up-spoiler-1"><_< & show & hide</label>'
+ + '<input id="up-spoiler-1" type="checkbox">'
+ + '<span></span>'
+ + '</span>'
+
+ expect(up.toHtml(node)).to.be.eql(html)
+ })
+}) |
f346650c733d1f4775dc5dfb280565c207e3211e | src/utils/validators.ts | src/utils/validators.ts | import * as _ from 'lodash';
import * as moment from 'moment';
import { badRequest } from 'boom';
import * as Joi from 'joi';
namespace schemas {
export const username = Joi.string().token().empty().min(2).max(20).label('Username');
export const password = Joi.string().empty().min(1).label('Password');
export const user = Joi.object().keys({ username, password }).options({ stripUnknown: true }).label('User');
export const transactionAmount = Joi.number().precision(2).label('Transaction amount');
export const groupName = Joi.string().min(4).max(255).label('Group name');
export const alternativeLoginKey = Joi.string().empty().label('Alternative login key');
export const timestamp = Joi.date().label('Timestamp');
}
function validateSchema<T>(schema: Joi.Schema, value: T): T {
const result = schema.validate(value);
if (result.error) {
throw badRequest(result.error.message, result.error.details);
}
return result.value;
}
export default {
user: _.partial(validateSchema, schemas.user),
username: _.partial(validateSchema, schemas.username),
password: _.partial(validateSchema, schemas.password),
transactionAmount: _.partial(validateSchema, schemas.transactionAmount),
groupName: _.partial(validateSchema, schemas.groupName),
alternativeLoginKey: _.partial(validateSchema, schemas.alternativeLoginKey),
timestamp: (time: any): moment.Moment => moment(validateSchema(schemas.timestamp, time)).utc(),
};
| import * as _ from 'lodash';
import * as moment from 'moment';
import { badRequest } from 'boom';
import * as Joi from 'joi';
namespace schemas {
export const username = Joi.string().token().empty().min(2).max(20).label('Username');
export const password = Joi.string().empty().min(1).label('Password');
export const user = Joi.object().keys({ username, password }).options({ stripUnknown: true }).label('User');
export const transactionAmount = Joi.number().precision(2).min(-1e+6).max(1e+6).label('Transaction amount');
export const groupName = Joi.string().min(4).max(255).label('Group name');
export const alternativeLoginKey = Joi.string().empty().label('Alternative login key');
export const timestamp = Joi.date().label('Timestamp');
}
function validateSchema<T>(schema: Joi.Schema, value: T): T {
const result = schema.validate(value);
if (result.error) {
throw badRequest(result.error.message, result.error.details);
}
return result.value;
}
export default {
user: _.partial(validateSchema, schemas.user),
username: _.partial(validateSchema, schemas.username),
password: _.partial(validateSchema, schemas.password),
transactionAmount: _.partial(validateSchema, schemas.transactionAmount),
groupName: _.partial(validateSchema, schemas.groupName),
alternativeLoginKey: _.partial(validateSchema, schemas.alternativeLoginKey),
timestamp: (time: any): moment.Moment => moment(validateSchema(schemas.timestamp, time)).utc(),
};
| Set minimum and maximum to transaction amount | Set minimum and maximum to transaction amount
| TypeScript | mit | majori/piikki | ---
+++
@@ -7,7 +7,7 @@
export const username = Joi.string().token().empty().min(2).max(20).label('Username');
export const password = Joi.string().empty().min(1).label('Password');
export const user = Joi.object().keys({ username, password }).options({ stripUnknown: true }).label('User');
- export const transactionAmount = Joi.number().precision(2).label('Transaction amount');
+ export const transactionAmount = Joi.number().precision(2).min(-1e+6).max(1e+6).label('Transaction amount');
export const groupName = Joi.string().min(4).max(255).label('Group name');
export const alternativeLoginKey = Joi.string().empty().label('Alternative login key');
export const timestamp = Joi.date().label('Timestamp'); |
8f3305024d5ae3f132b5735de5509c9a579c0474 | src/util/statusBarTextUtils.ts | src/util/statusBarTextUtils.ts | import { ModeName } from '../mode/mode';
import { StatusBar } from '../statusBar';
import { VimState } from '../state/vimState';
import { configuration } from '../configuration/configuration';
export function ReportClear(vimState: VimState) {
StatusBar.Set('', vimState.currentMode, vimState.isRecordingMacro, true);
}
export function ReportLinesChanged(numLinesChanged: number, vimState: VimState) {
if (numLinesChanged > configuration.report) {
StatusBar.Set(
numLinesChanged + ' more lines',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else if (-numLinesChanged > configuration.report) {
StatusBar.Set(
numLinesChanged + ' fewer lines',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
}
}
export function ReportLinesYanked(numLinesYanked: number, vimState: VimState) {
if (numLinesYanked > configuration.report) {
if (vimState.currentMode === ModeName.VisualBlock) {
StatusBar.Set(
'block of ' + numLinesYanked + ' lines yanked',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else {
StatusBar.Set(
numLinesYanked + ' lines yanked',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
}
}
}
| import { ModeName } from '../mode/mode';
import { StatusBar } from '../statusBar';
import { VimState } from '../state/vimState';
import { configuration } from '../configuration/configuration';
export function ReportClear(vimState: VimState) {
StatusBar.Set('', vimState.currentMode, vimState.isRecordingMacro, true);
}
export function ReportLinesChanged(numLinesChanged: number, vimState: VimState) {
if (numLinesChanged > configuration.report) {
StatusBar.Set(
numLinesChanged + ' more lines',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else if (-numLinesChanged > configuration.report) {
StatusBar.Set(
numLinesChanged + ' fewer lines',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else {
ReportClear(vimState);
}
}
export function ReportLinesYanked(numLinesYanked: number, vimState: VimState) {
if (numLinesYanked > configuration.report) {
if (vimState.currentMode === ModeName.VisualBlock) {
StatusBar.Set(
'block of ' + numLinesYanked + ' lines yanked',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else {
StatusBar.Set(
numLinesYanked + ' lines yanked',
vimState.currentMode,
vimState.isRecordingMacro,
true
);
} else{
ReportClear(vimState);
}
}
}
| Clear reported lines if new report is received and it is less than report threshold | Clear reported lines if new report is received and it is less than report threshold
| TypeScript | mit | VSCodeVim/Vim,VSCodeVim/Vim | ---
+++
@@ -22,6 +22,8 @@
vimState.isRecordingMacro,
true
);
+ } else {
+ ReportClear(vimState);
}
}
@@ -41,6 +43,8 @@
vimState.isRecordingMacro,
true
);
+ } else{
+ ReportClear(vimState);
}
}
} |
af6f355f086102c7119eb52d51275160fb33c487 | src/app/duels/game.component.ts | src/app/duels/game.component.ts | import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Game } from './game';
@Component({
selector: 'duel-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css'],
})
export class GameComponent {
@Input() game: Game;
@Output() onPicked = new EventEmitter<string>();
pick(team: string): void {
this.game.selectedTeam = team;
}
isSelected(team: string): boolean {
return this.game.selectedTeam === team;
}
}
| import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Game } from './game';
@Component({
selector: 'duel-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css'],
})
export class GameComponent {
@Input() game: Game;
@Output() onPicked = new EventEmitter<string>();
pick(team: string): void {
if (this.game.selectedTeam === team) {
this.game.selectedTeam = undefined;
} else {
this.game.selectedTeam = team;
}
}
isSelected(team: string): boolean {
return this.game.selectedTeam === team;
}
}
| Add ability to unselect a team after picking | Add ability to unselect a team after picking
| TypeScript | mit | lentz/buddyduel,lentz/buddyduel,lentz/buddyduel | ---
+++
@@ -12,7 +12,11 @@
@Output() onPicked = new EventEmitter<string>();
pick(team: string): void {
- this.game.selectedTeam = team;
+ if (this.game.selectedTeam === team) {
+ this.game.selectedTeam = undefined;
+ } else {
+ this.game.selectedTeam = team;
+ }
}
isSelected(team: string): boolean { |
97a23155ca9eba4008fe108db4ea1de266e7cc67 | src/game/game-form.component.ts | src/game/game-form.component.ts | import {Component, Input, Output, OnInit, EventEmitter} from 'angular2/core';
import {FormBuilder, ControlGroup, Validators} from 'angular2/common';
import {Game} from '../shared/models/game.model';
@Component({
selector: 'agot-game-form',
moduleId: module.id,
templateUrl: './game-form.html',
styleUrls: ['./game-form.css']
})
export class GameFormComponent implements OnInit {
@Input()
game:Game;
@Output()
submit = new EventEmitter<any>(); // TODO check type?
gameForm:ControlGroup;
constructor(private _FormBuilder:FormBuilder) {
}
ngOnInit() {
this.serialiseGameToForm();
}
onSubmit() {
console.log(this.gameForm.value, this.game);
this.deserialiseFormToGame();
// TODO
//this.submit.emit(this.game);
}
private deserialiseFormToGame() {
// set date to string
// set deck from deckId?
// set other?
};
private serialiseGameToForm() {
this.gameForm = this._FormBuilder.group({
date: [this.convertDateString(), Validators.required],
coreSetCount: [this.game.coreSetCount, Validators.required],
deckType: [this.game.deckType.deckTypeId, Validators.required],
gamePlayers: [this.game.gamePlayers, Validators.required],
});
};
private convertDateString() {
// TODO what is the right bastard string format here?
return this.game.date;
};
}
| import {Component, Input, Output, OnInit, EventEmitter} from 'angular2/core';
import {FormBuilder, ControlGroup, Validators} from 'angular2/common';
import {Game} from '../shared/models/game.model';
@Component({
selector: 'agot-game-form',
moduleId: module.id,
templateUrl: './game-form.html',
styleUrls: ['./game-form.css'],
})
export class GameFormComponent implements OnInit {
@Input()
game:Game;
@Output()
submit = new EventEmitter<any>(); // TODO check type?
gameForm:ControlGroup;
constructor(private _FormBuilder:FormBuilder) {
}
ngOnInit() {
this.serialiseGameToForm();
}
onSubmit() {
console.log(this.gameForm.value, this.game);
this.deserialiseFormToGame();
// TODO
//this.submit.emit(this.game);
}
private deserialiseFormToGame() {
// set date to string
// set deck from deckId?
// set other?
};
private serialiseGameToForm() {
this.gameForm = this._FormBuilder.group({
date: [this.convertDateString(), Validators.required],
coreSetCount: [this.game.coreSetCount, Validators.required],
deckType: [this.game.deckType.deckTypeId, Validators.required],
gamePlayers: [this.game.gamePlayers, Validators.required],
});
};
private convertDateString() {
// have to remove the time and timezone to populate the control correctly
return this.game.date.slice(0, 10);
};
}
| Convert date to usable string to populate input | Convert date to usable string to populate input
| TypeScript | mit | davewragg/agot-spa,davewragg/agot-spa,davewragg/agot-spa | ---
+++
@@ -6,7 +6,7 @@
selector: 'agot-game-form',
moduleId: module.id,
templateUrl: './game-form.html',
- styleUrls: ['./game-form.css']
+ styleUrls: ['./game-form.css'],
})
export class GameFormComponent implements OnInit {
@Input()
@@ -46,7 +46,7 @@
};
private convertDateString() {
- // TODO what is the right bastard string format here?
- return this.game.date;
+ // have to remove the time and timezone to populate the control correctly
+ return this.game.date.slice(0, 10);
};
} |
7ed6389c41311791117f08e4178d156ffd90c1eb | app/+models/application-error.ts | app/+models/application-error.ts | const ERRORS = {
"404-001": {
message: "Unable to fetch the list of projects",
debug: "Please check your internet connection"
},
"422-001": {
message: "Login failed due to a badly formatted token. %{token} is not a valid token",
redirection: [
{ name: "Back to login page.", route: '/login' }
]
}
};
export class ApplicationError {
id: string;
userMessage: string;
debug: string;
errorId: number;
errorType: number;
metadata: any;
hasDebug: boolean;
redirections: any[];
constructor(id: string, metadata: any) {
this.id = id;
this.errorType = parseInt(id.split('-')[0]);
this.errorId = parseInt(id.split('-')[1]);
this.metadata = metadata;
if (ERRORS.hasOwnProperty(id) === true) {
this.userMessage = ERRORS[id].message;
this.debug = (ERRORS[id].hasOwnProperty('debug') === true)
? ERRORS[id].debug
: ERRORS[id].message;
this.hasDebug = (ERRORS[id].hasOwnProperty('debug') === true);
this.redirections = (ERRORS[id].hasOwnProperty('redirections') === true) ? ERRORS[id].redirections : [];
} else {
this.userMessage = "Undefined error.";
this.debug = "Undefined error.";
this.hasDebug = false;
this.redirections = [];
}
}
} | const ERRORS = {
"404-001": {
message: "Unable to fetch the list of projects",
debug: "Please check your internet connection",
redirections: [
{ name: "Retry", route: '/projects' }
]
},
"422-001": {
message: "Login failed due to a badly formatted token. %{token} is not a valid token",
redirections: [
{ name: "Back to login page.", route: '/login' }
]
}
};
export class ApplicationError {
id: string;
userMessage: string;
debug: string;
errorId: number;
errorType: number;
metadata: any;
hasDebug: boolean;
redirections: any[];
constructor(id: string, metadata: any) {
this.id = id;
this.errorType = parseInt(id.split('-')[0]);
this.errorId = parseInt(id.split('-')[1]);
this.metadata = metadata;
if (ERRORS.hasOwnProperty(id) === true) {
this.userMessage = ERRORS[id].message;
this.debug = (ERRORS[id].hasOwnProperty('debug') === true)
? ERRORS[id].debug
: ERRORS[id].message;
this.hasDebug = (ERRORS[id].hasOwnProperty('debug') === true);
this.redirections = (ERRORS[id].hasOwnProperty('redirections') === true) ? ERRORS[id].redirections : [];
} else {
this.userMessage = "Undefined error.";
this.debug = "Undefined error.";
this.hasDebug = false;
this.redirections = [];
}
}
} | Add some links on defined errors | [Error] Add some links on defined errors
| TypeScript | mit | yllieth/localehub,yllieth/localehub,yllieth/localehub,yllieth/localehub | ---
+++
@@ -1,11 +1,14 @@
const ERRORS = {
"404-001": {
message: "Unable to fetch the list of projects",
- debug: "Please check your internet connection"
+ debug: "Please check your internet connection",
+ redirections: [
+ { name: "Retry", route: '/projects' }
+ ]
},
"422-001": {
message: "Login failed due to a badly formatted token. %{token} is not a valid token",
- redirection: [
+ redirections: [
{ name: "Back to login page.", route: '/login' }
]
} |
10d0c9c6c31c28afadbc4384e3fb1369042c8f8c | index.ts | index.ts | export { AuthAPIClient } from "./src/v1/AuthAPIClient";
export { DataAPIClient } from "./src/v1/DataAPIClient";
export { Constants } from "./src/v1/Constants";
export { IAccount } from "./src/v1/interfaces/data/IAccount";
export { IBalance } from "./src/v1/interfaces/data/IBalance";
export { IInfo } from "./src/v1/interfaces/data/IInfo";
export { IMe } from "./src/v1/interfaces/data/IMe";
export { IOptions } from "./src/v1/interfaces/auth/IOptions";
export { IResult, IError } from "./src/v1/interfaces/data/IResponse";
export { ITokenResponse } from "./src/v1/interfaces/auth/ITokenResponse";
export { ITransaction } from "./src/v1/interfaces/data/ITransaction";
export { ICard } from "./src/v1/interfaces/data/ICard";
export { ICardBalance } from "./src/v1/interfaces/data/ICardBalance";
export { ICardTransaction } from "./src/v1/interfaces/data/ICardTransaction";
| export { AuthAPIClient } from "./src/v1/AuthAPIClient";
export { DataAPIClient } from "./src/v1/DataAPIClient";
export { Constants } from "./src/v1/Constants";
export { IAccount } from "./src/v1/interfaces/data/IAccount";
export { IBalance } from "./src/v1/interfaces/data/IBalance";
export { IInfo } from "./src/v1/interfaces/data/IInfo";
export { IMe } from "./src/v1/interfaces/data/IMe";
export { IOptions } from "./src/v1/interfaces/auth/IOptions";
export { IResult, IError } from "./src/v1/interfaces/data/IResponse";
export { ITokenResponse } from "./src/v1/interfaces/auth/ITokenResponse";
export { ITransaction } from "./src/v1/interfaces/data/ITransaction";
export { ICard } from "./src/v1/interfaces/data/ICard";
export { ICardBalance } from "./src/v1/interfaces/data/ICardBalance";
export { ICardTransaction } from "./src/v1/interfaces/data/ICardTransaction";
export { IProviderInfo } from "./src/v1/interfaces/auth/IProviderInfo";
| Add missing export for IProviderInfo | Add missing export for IProviderInfo
| TypeScript | mit | TrueLayer/truelayer-client-javascript | ---
+++
@@ -13,3 +13,4 @@
export { ICard } from "./src/v1/interfaces/data/ICard";
export { ICardBalance } from "./src/v1/interfaces/data/ICardBalance";
export { ICardTransaction } from "./src/v1/interfaces/data/ICardTransaction";
+export { IProviderInfo } from "./src/v1/interfaces/auth/IProviderInfo"; |
739e1b861f4ad3d1b5ae6ae93bcf51e929f6558a | addons/docs/src/frameworks/vue/extractArgTypes.ts | addons/docs/src/frameworks/vue/extractArgTypes.ts | import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor, hasDocgen, extractComponentProps } from '../../lib/docgen';
import { trimQuotes } from '../../lib/sbtypes/utils';
const SECTIONS = ['props', 'events', 'slots'];
const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (!hasDocgen(component)) {
return null;
}
const results: ArgTypes = {};
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, jsDocTags }) => {
const { name, type, description, defaultValue } = propDef;
results[name] = {
name,
defaultValue: defaultValue && trim(defaultValue.detail || defaultValue.summary),
table: {
type,
jsDocTags,
defaultValue,
category: section,
},
};
});
});
return results;
};
| import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor, hasDocgen, extractComponentProps } from '../../lib/docgen';
import { trimQuotes } from '../../lib/sbtypes/utils';
const SECTIONS = ['props', 'events', 'slots'];
const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (!hasDocgen(component)) {
return null;
}
const results: ArgTypes = {};
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, jsDocTags }) => {
const { name, sbType, type, description, defaultValue } = propDef;
results[name] = {
name,
description,
type: sbType,
defaultValue: defaultValue && trim(defaultValue.detail || defaultValue.summary),
table: {
type,
jsDocTags,
defaultValue,
category: section,
},
};
});
});
return results;
};
| Fix missing description and type | Fix missing description and type
| TypeScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook | ---
+++
@@ -14,9 +14,11 @@
SECTIONS.forEach((section) => {
const props = extractComponentProps(component, section);
props.forEach(({ propDef, jsDocTags }) => {
- const { name, type, description, defaultValue } = propDef;
+ const { name, sbType, type, description, defaultValue } = propDef;
results[name] = {
name,
+ description,
+ type: sbType,
defaultValue: defaultValue && trim(defaultValue.detail || defaultValue.summary),
table: {
type, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.