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
|
---|---|---|---|---|---|---|---|---|---|---|
d2b571178a4d25948877e4dbd253db7c4c333db4 | projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts | projects/angular2-cookie-law/src/lib/angular2-cookie-law.service.ts | /**
* angular2-cookie-law
*
* Copyright 2016-2018, @andreasonny83, All rights reserved.
*
* @author: @andreasonny83 <[email protected]>
*/
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
constructor(
@Inject(DOCUMENT) private doc: Document,
@Inject(PLATFORM_ID) private platform: Object
) { }
public seen(cookieName: string = 'cookieLawSeen'): boolean {
let cookies: Array<string> = [];
if (isPlatformBrowser(this.platform)) {
cookies = this.doc.cookie.split(';');
}
return this.cookieExisits(cookieName, cookies);
}
public storeCookie(cookieName: string, expiration?: number): void {
return this.setCookie(cookieName, expiration);
}
private cookieExisits(name: string, cookies: Array<string>): boolean {
const cookieName = `${name}=`;
return cookies.reduce((prev, curr) =>
prev || curr.trim().search(cookieName) > -1, false);
}
private setCookie(name: string, expiration?: number): void {
const now: Date = new Date();
const exp: Date = new Date(now.getTime() + expiration * 86400000);
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
if (isPlatformBrowser(this.platform)) {
this.doc.cookie = cookieString;
}
}
}
| /**
* angular2-cookie-law
*
* Copyright 2016-2018, @andreasonny83, All rights reserved.
*
* @author: @andreasonny83 <[email protected]>
*/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
public seen(cookieName: string = 'cookieLawSeen'): boolean {
const cookies: Array<string> = document.cookie.split(';');
return this.cookieExisits(cookieName, cookies);
}
public storeCookie(cookieName: string, expiration?: number): void {
return this.setCookie(cookieName, expiration);
}
private cookieExisits(name: string, cookies: Array<string>): boolean {
const cookieName = `${name}=`;
return cookies.reduce((prev, curr) =>
prev || curr.trim().search(cookieName) > -1, false);
}
private setCookie(name: string, expiration?: number): void {
const now: Date = new Date();
const exp: Date = new Date(now.getTime() + expiration * 86400000);
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
document.cookie = cookieString;
}
}
| Revert "Angular2CookieLawService compatibility with Angular Universal" | Revert "Angular2CookieLawService compatibility with Angular Universal"
| TypeScript | mit | andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law,andreasonny83/angular2-cookie-law | ---
+++
@@ -6,25 +6,14 @@
* @author: @andreasonny83 <[email protected]>
*/
-import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
-import { DOCUMENT, isPlatformBrowser } from '@angular/common';
+import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Angular2CookieLawService {
-
- constructor(
- @Inject(DOCUMENT) private doc: Document,
- @Inject(PLATFORM_ID) private platform: Object
- ) { }
-
public seen(cookieName: string = 'cookieLawSeen'): boolean {
- let cookies: Array<string> = [];
-
- if (isPlatformBrowser(this.platform)) {
- cookies = this.doc.cookie.split(';');
- }
+ const cookies: Array<string> = document.cookie.split(';');
return this.cookieExisits(cookieName, cookies);
}
@@ -47,8 +36,6 @@
const cookieString = encodeURIComponent(name) +
`=true;path=/;expires=${exp.toUTCString()};`;
- if (isPlatformBrowser(this.platform)) {
- this.doc.cookie = cookieString;
- }
+ document.cookie = cookieString;
}
} |
65799f46a000e7bca7ee4c2d3d70e58ddad241e4 | example/image.component.ts | example/image.component.ts | import { Component, Input } from '@angular/core';
import { LazyLoadImageDirective } from '../src/lazyload-image.directive';
@Component({
selector: 'image',
styles: [`
img {
width: 100%;
min-height: 1000px;
transition: opacity 1s;
opacity: 0;
}
img.ng2-lazyloaded {
opacity: 1;
}
`],
template: `
<img src="https://www.placecage.com/1000/1000" [lazyLoad]="image" offset="0">
`,
directives: [ LazyLoadImageDirective ]
})
class ImageComponent {
@Input('src') image;
}
export { ImageComponent };
| import { Component, Input } from '@angular/core';
import { LazyLoadImageDirective } from '../src/lazyload-image.directive';
@Component({
selector: 'image',
styles: [`
img {
min-width: 1497px;
width: 100%;
min-height: 1127px;
transition: opacity 1s;
opacity: 0;
}
img.ng2-lazyloaded {
opacity: 1;
}
`],
template: `
<img src="https://www.placecage.com/1000/1000" [lazyLoad]="image" offset="0">
`,
directives: [ LazyLoadImageDirective ]
})
class ImageComponent {
@Input('src') image;
}
export { ImageComponent };
| Set a fix with and width on the image | :sparkles: Set a fix with and width on the image
| TypeScript | mit | tjoskar/ng-lazyload-image,tjoskar/ng2-lazyload-image,tjoskar/ng-lazyload-image,tjoskar/ng2-lazyload-image,tjoskar/ng2-lazyload-image | ---
+++
@@ -5,8 +5,9 @@
selector: 'image',
styles: [`
img {
+ min-width: 1497px;
width: 100%;
- min-height: 1000px;
+ min-height: 1127px;
transition: opacity 1s;
opacity: 0;
} |
3f90e5412969b13563cd013becf951cd5b7c9773 | packages/utils/src/loader/loaders.ts | packages/utils/src/loader/loaders.ts | import type { Awaitable } from '@antfu/utils';
import { existsSync, promises as fs } from 'fs';
import type { CustomIconLoader } from './types';
import { camelize, pascalize } from '../misc/strings';
export function FileSystemIconLoader(
dir: string,
transform?: (svg: string) => Awaitable<string>
): CustomIconLoader {
return async (name) => {
const paths = [
`${dir}/${name}.svg`,
`${dir}/${camelize(name)}.svg`,
`${dir}/${pascalize(name)}.svg`,
];
for (const path of paths) {
if (existsSync(path)) {
const svg = await fs.readFile(path, 'utf-8');
return typeof transform === 'function'
? await transform(svg)
: svg;
}
}
};
}
| import type { Awaitable } from '@antfu/utils';
import { promises as fs, Stats } from 'fs';
import type { CustomIconLoader } from './types';
import { camelize, pascalize } from '../misc/strings';
/**
* Returns CustomIconLoader for loading icons from a directory
*/
export function FileSystemIconLoader(
dir: string,
transform?: (svg: string) => Awaitable<string>
): CustomIconLoader {
return async (name) => {
const paths = [
`${dir}/${name}.svg`,
`${dir}/${camelize(name)}.svg`,
`${dir}/${pascalize(name)}.svg`,
];
for (const path of paths) {
let stat: Stats;
try {
stat = await fs.lstat(path);
} catch (err) {
continue;
}
if (stat.isFile()) {
const svg = await fs.readFile(path, 'utf-8');
return typeof transform === 'function'
? await transform(svg)
: svg;
}
}
};
}
| Check if file exists asynchronously in FileSystemIconLoader | Check if file exists asynchronously in FileSystemIconLoader
| TypeScript | mit | simplesvg/simple-svg,simplesvg/simple-svg,simplesvg/simple-svg | ---
+++
@@ -1,8 +1,11 @@
import type { Awaitable } from '@antfu/utils';
-import { existsSync, promises as fs } from 'fs';
+import { promises as fs, Stats } from 'fs';
import type { CustomIconLoader } from './types';
import { camelize, pascalize } from '../misc/strings';
+/**
+ * Returns CustomIconLoader for loading icons from a directory
+ */
export function FileSystemIconLoader(
dir: string,
transform?: (svg: string) => Awaitable<string>
@@ -14,7 +17,13 @@
`${dir}/${pascalize(name)}.svg`,
];
for (const path of paths) {
- if (existsSync(path)) {
+ let stat: Stats;
+ try {
+ stat = await fs.lstat(path);
+ } catch (err) {
+ continue;
+ }
+ if (stat.isFile()) {
const svg = await fs.readFile(path, 'utf-8');
return typeof transform === 'function'
? await transform(svg) |
ae7c485ab6c600adc5626ccb69c95f785d7f0f94 | components/form-vue/control-errors/control-error.ts | components/form-vue/control-errors/control-error.ts | import Vue from 'vue';
import { Component, Prop } from 'vue-property-decorator';
import { findVueParent } from '../../../utils/vue';
import { AppFormControlErrors } from './control-errors';
@Component({})
export class AppFormControlError extends Vue
{
@Prop( String ) when: string;
mounted()
{
const defaultSlot = this.$slots.default[0];
const errors = findVueParent( this, AppFormControlErrors ) as AppFormControlErrors;
if ( defaultSlot.text ) {
errors.setMessageOverride( this.when, defaultSlot.text );
}
}
render( h: Vue.CreateElement )
{
return h( 'span' );
}
}
| import Vue from 'vue';
import { Component, Prop, Watch } from 'vue-property-decorator';
import { findVueParent } from '../../../utils/vue';
import { AppFormControlErrors } from './control-errors';
@Component({})
export class AppFormControlError extends Vue
{
@Prop( String ) when: string;
@Prop( String ) message: string;
mounted()
{
this.setOverride();
}
@Watch( 'message' )
onMessageChange()
{
this.setOverride();
}
private setOverride()
{
const errors = findVueParent( this, AppFormControlErrors ) as AppFormControlErrors;
errors.setMessageOverride( this.when, this.message );
}
render( h: Vue.CreateElement )
{
return h( 'span' );
}
}
| Fix form control error overrides not being translatable | Fix form control error overrides not being translatable
| TypeScript | mit | gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib,gamejolt/frontend-lib | ---
+++
@@ -1,5 +1,5 @@
import Vue from 'vue';
-import { Component, Prop } from 'vue-property-decorator';
+import { Component, Prop, Watch } from 'vue-property-decorator';
import { findVueParent } from '../../../utils/vue';
import { AppFormControlErrors } from './control-errors';
@@ -8,15 +8,23 @@
export class AppFormControlError extends Vue
{
@Prop( String ) when: string;
+ @Prop( String ) message: string;
mounted()
{
- const defaultSlot = this.$slots.default[0];
+ this.setOverride();
+ }
+
+ @Watch( 'message' )
+ onMessageChange()
+ {
+ this.setOverride();
+ }
+
+ private setOverride()
+ {
const errors = findVueParent( this, AppFormControlErrors ) as AppFormControlErrors;
-
- if ( defaultSlot.text ) {
- errors.setMessageOverride( this.when, defaultSlot.text );
- }
+ errors.setMessageOverride( this.when, this.message );
}
render( h: Vue.CreateElement ) |
cf8ce3751e8e42e601e312ea1129f8ab50a1ea10 | packages/custom-elements/ts_src/AlreadyConstructedMarker.ts | packages/custom-elements/ts_src/AlreadyConstructedMarker.ts | /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* Represents the 'already constructed marker' used in custom
* element construction stacks.
*
* https://html.spec.whatwg.org/#concept-already-constructed-marker
*/
const alreadyConstructedMarker: unique symbol =
Symbol('AlreadyConstructedMarker');
export default alreadyConstructedMarker;
export type AlreadyConstructedMarkerType = typeof alreadyConstructedMarker;
| /**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt The complete set of authors may be found
* at http://polymer.github.io/AUTHORS.txt The complete set of contributors may
* be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by
* Google as part of the polymer project is also subject to an additional IP
* rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* Represents the 'already constructed marker' used in custom
* element construction stacks.
*
* https://html.spec.whatwg.org/#concept-already-constructed-marker
*/
const alreadyConstructedMarker = {} as {_alreadyConstructedMarker: never};
export default alreadyConstructedMarker;
export type AlreadyConstructedMarkerType = typeof alreadyConstructedMarker;
| Use a branded unconstructable type rather than unique symbol to save bytes. | Use a branded unconstructable type rather than unique symbol to save bytes.
| TypeScript | bsd-3-clause | webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills | ---
+++
@@ -15,8 +15,7 @@
*
* https://html.spec.whatwg.org/#concept-already-constructed-marker
*/
-const alreadyConstructedMarker: unique symbol =
- Symbol('AlreadyConstructedMarker');
+const alreadyConstructedMarker = {} as {_alreadyConstructedMarker: never};
export default alreadyConstructedMarker;
export type AlreadyConstructedMarkerType = typeof alreadyConstructedMarker; |
725a89f9e8ab1f0d969b3c1592f0912281cbaa7a | src/components/Layout/Link/index.tsx | src/components/Layout/Link/index.tsx | import React, { PropsWithChildren, ReactElement } from 'react'
import { Link as HyperLink, LinkProps } from 'react-router-dom'
export default function Link({
to,
children,
...rest
}: PropsWithChildren<LinkProps>): ReactElement {
return (
<HyperLink to={to} {...rest}>
{children}
</HyperLink>
)
}
| import React, { PropsWithChildren, ReactElement } from 'react'
import { Link as HyperLink, LinkProps } from 'react-router-dom'
export default function Link({
to,
children,
...rest
}: PropsWithChildren<LinkProps>): ReactElement {
return (
<HyperLink to={to} {...rest} replace>
{children}
</HyperLink>
)
}
| Fix 'cannot PUSH the same path' warning from Router on Link component by the replace prop | Fix 'cannot PUSH the same path' warning from Router on Link component by the replace prop
| TypeScript | mit | daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io,daltonmenezes/daltonmenezes.github.io | ---
+++
@@ -7,7 +7,7 @@
...rest
}: PropsWithChildren<LinkProps>): ReactElement {
return (
- <HyperLink to={to} {...rest}>
+ <HyperLink to={to} {...rest} replace>
{children}
</HyperLink>
) |
beab55946eb7570474729711e9245b8a2e31d317 | addons/docs/src/frameworks/react/extractArgTypes.ts | addons/docs/src/frameworks/react/extractArgTypes.ts | import { PropDef, PropsTableRowsProps } from '@storybook/components';
import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor } from '../../lib/docgen';
import { trimQuotes } from '../../lib/sbtypes/utils';
import { extractProps } from './extractProps';
const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (component) {
const props = extractProps(component);
const { rows } = props as PropsTableRowsProps;
if (rows) {
return rows.reduce((acc: ArgTypes, row: PropDef) => {
const { type, sbType, defaultValue: defaultSummary, jsDocTags, required } = row;
let defaultValue = defaultSummary && trim(defaultSummary.detail || defaultSummary.summary);
try {
// eslint-disable-next-line no-eval
defaultValue = eval(defaultValue);
// eslint-disable-next-line no-empty
} catch {}
acc[row.name] = {
...row,
defaultValue,
type: { required, ...sbType },
table: {
type,
jsDocTags,
defaultValue,
},
};
return acc;
}, {});
}
}
return null;
};
| import { PropDef, PropsTableRowsProps } from '@storybook/components';
import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor } from '../../lib/docgen';
import { extractProps } from './extractProps';
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (component) {
const props = extractProps(component);
const { rows } = props as PropsTableRowsProps;
if (rows) {
return rows.reduce((acc: ArgTypes, row: PropDef) => {
const { type, sbType, defaultValue: defaultSummary, jsDocTags, required } = row;
let defaultValue = defaultSummary && (defaultSummary.detail || defaultSummary.summary);
try {
// eslint-disable-next-line no-eval
defaultValue = eval(defaultValue);
// eslint-disable-next-line no-empty
} catch {}
acc[row.name] = {
...row,
defaultValue,
type: { required, ...sbType },
table: {
type,
jsDocTags,
defaultValue,
},
};
return acc;
}, {});
}
}
return null;
};
| Clean up redundant quote removal | ArgTypes: Clean up redundant quote removal
| TypeScript | mit | kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook | ---
+++
@@ -1,10 +1,7 @@
import { PropDef, PropsTableRowsProps } from '@storybook/components';
import { ArgTypes } from '@storybook/api';
import { ArgTypesExtractor } from '../../lib/docgen';
-import { trimQuotes } from '../../lib/sbtypes/utils';
import { extractProps } from './extractProps';
-
-const trim = (val: any) => (val && typeof val === 'string' ? trimQuotes(val) : val);
export const extractArgTypes: ArgTypesExtractor = (component) => {
if (component) {
@@ -13,7 +10,7 @@
if (rows) {
return rows.reduce((acc: ArgTypes, row: PropDef) => {
const { type, sbType, defaultValue: defaultSummary, jsDocTags, required } = row;
- let defaultValue = defaultSummary && trim(defaultSummary.detail || defaultSummary.summary);
+ let defaultValue = defaultSummary && (defaultSummary.detail || defaultSummary.summary);
try {
// eslint-disable-next-line no-eval
defaultValue = eval(defaultValue); |
976d27f59a87e3a5e7f860a6900fcf11d1fe80d5 | src/environments/environment.prod.ts | src/environments/environment.prod.ts | export const environment = {
production: true
};
| export const environment = {
production: true,
firebase: {
projectId: "releaseer-a6183",
apiKey: "AIzaSyA_tWprch4_iJKKcEg3CCAO9VwCjvKxY5I",
authDomain: "releaseer-a6183.firebaseapp.com",
databaseURL: "https://releaseer-a6183.firebaseio.com",
storageBucket: "releaseer-a6183.appspot.com",
messagingSenderId: "454541533417"
}
};
| Upgrade Releaser to Angular 4 | Upgrade Releaser to Angular 4
| TypeScript | mit | Richard87/releaser,Richard87/releaser,Richard87/releaser,Richard87/releaser | ---
+++
@@ -1,3 +1,11 @@
export const environment = {
- production: true
+ production: true,
+ firebase: {
+ projectId: "releaseer-a6183",
+ apiKey: "AIzaSyA_tWprch4_iJKKcEg3CCAO9VwCjvKxY5I",
+ authDomain: "releaseer-a6183.firebaseapp.com",
+ databaseURL: "https://releaseer-a6183.firebaseio.com",
+ storageBucket: "releaseer-a6183.appspot.com",
+ messagingSenderId: "454541533417"
+ }
}; |
acd4008b08d0b61c9491cbc2ead2985c53cc72fe | lib/api/index.ts | lib/api/index.ts | import { CountryRecord, SubdivisionsRecord } from '@maxmind/geoip2-node';
import { findCityByIp } from '../db/maxmind/city';
import { ipToNumber, numberToIp } from '../ip-utils';
export {
ipToNumber,
numberToIp,
};
type IpCountry = {
ip: number;
country_name: string;
subdivision_1_name: string;
}
/**
* Given a collection of IP addresses returns the country associated with each one.
* @param ips - numeric IP addresses
*/
export const getCityLocationsByIp = async (ips: number[]): Promise<IpCountry[]> => {
const promises = ips.map(async (ip) => {
const ipAddress = numberToIp(ip);
const city = await findCityByIp(ipAddress);
const country_name = (city.country as CountryRecord).names?.en ?? 'unknown';
const subdivisions = (city.subdivisions || []) as SubdivisionsRecord[];
const subdivision_1_name = subdivisions.length > 0 ? subdivisions[0].names?.en ?? 'unknown' : 'unknown';
const ipCountry: IpCountry = {
country_name,
ip,
subdivision_1_name,
};
return ipCountry;
});
const ipCountries = await Promise.all(promises);
return ipCountries;
};
| import { findCityByIp } from '../db/maxmind/city';
import { ipToNumber, numberToIp } from '../ip-utils';
export {
ipToNumber,
numberToIp,
};
type IpCountry = {
ip: number;
country_name: string;
subdivision_1_name: string;
}
/**
* Given a collection of IP addresses returns the country associated with each one.
* @param ips - numeric IP addresses
*/
export const getCityLocationsByIp = async (ips: number[]): Promise<IpCountry[]> => {
const promises = ips.map(async (ip) => {
const ipAddress = numberToIp(ip);
const city = await findCityByIp(ipAddress);
const country_name = city.country?.names?.en ?? 'unknown';
const subdivisions = city.subdivisions || [];
const subdivision_1_name = subdivisions.length > 0 ? subdivisions[0].names?.en ?? 'unknown' : 'unknown';
const ipCountry: IpCountry = {
country_name,
ip,
subdivision_1_name,
};
return ipCountry;
});
const ipCountries = await Promise.all(promises);
return ipCountries;
};
| Remove two more TS casts | Remove two more TS casts
| TypeScript | mit | guyellis/ipapi,guyellis/ipapi,guyellis/ipapi | ---
+++
@@ -1,4 +1,3 @@
-import { CountryRecord, SubdivisionsRecord } from '@maxmind/geoip2-node';
import { findCityByIp } from '../db/maxmind/city';
import { ipToNumber, numberToIp } from '../ip-utils';
@@ -22,8 +21,8 @@
const promises = ips.map(async (ip) => {
const ipAddress = numberToIp(ip);
const city = await findCityByIp(ipAddress);
- const country_name = (city.country as CountryRecord).names?.en ?? 'unknown';
- const subdivisions = (city.subdivisions || []) as SubdivisionsRecord[];
+ const country_name = city.country?.names?.en ?? 'unknown';
+ const subdivisions = city.subdivisions || [];
const subdivision_1_name = subdivisions.length > 0 ? subdivisions[0].names?.en ?? 'unknown' : 'unknown';
const ipCountry: IpCountry = {
country_name, |
ab46b17b2e5986ebeb350c6d97b1846999a1cde0 | src/styles/elements/Button.theme.ts | src/styles/elements/Button.theme.ts | import { stripUnit } from 'polished';
import {
defaultBorderRadius,
inputVerticalPadding,
pageFont
} from '../globals';
// Begin extract
const borderColor = '';
// End extract
export const verticalMargin = '0em';
export const horizontalMargin = '0.25em';
export const backgroundColor = '#e0e1e2';
export const backgroundImage = 'none';
export const background = `${backgroundColor} ${backgroundImage}`;
export const lineHeight = '1em';
export const verticalPadding = inputVerticalPadding;
export const horizontalPadding = '1.5em';
// Text
export const textTransform = 'none';
export const tapColor = 'transparent';
export const fontFamily = pageFont;
export const fontWeight = 'bold';
export const textColor = 'rgba(0,0,0,.6)';
export const textShadow = 'none';
export const invertedTextShadow = textShadow;
export const borderRadius = defaultBorderRadius;
export const verticalAlign = 'baseline';
// Internal Shadow
export const shadowDistance = '0em';
const calculateShadowOffset = (shadowDistance: string) => {
const strippedShadowDistance = stripUnit(shadowDistance);
if (typeof strippedShadowDistance === 'number') {
return `${strippedShadowDistance / 2}em`;
}
return strippedShadowDistance;
};
export const shadowOffset = calculateShadowOffset(shadowDistance);
export const shadowBoxShadow = `0px -${shadowDistance} 0px 0px ${borderColor} inset`;
| import { stripUnit } from 'polished';
import {
borderColor,
defaultBorderRadius,
inputVerticalPadding,
pageFont
} from '../globals';
export const verticalMargin = '0em';
export const horizontalMargin = '0.25em';
export const backgroundColor = '#e0e1e2';
export const backgroundImage = 'none';
export const background = `${backgroundColor} ${backgroundImage}`;
export const lineHeight = '1em';
export const verticalPadding = inputVerticalPadding;
export const horizontalPadding = '1.5em';
// Text
export const textTransform = 'none';
export const tapColor = 'transparent';
export const fontFamily = pageFont;
export const fontWeight = 'bold';
export const textColor = 'rgba(0,0,0,.6)';
export const textShadow = 'none';
export const invertedTextShadow = textShadow;
export const borderRadius = defaultBorderRadius;
export const verticalAlign = 'baseline';
// Internal Shadow
export const shadowDistance = '0em';
const calculateShadowOffset = (shadowDistance: string) => {
const strippedShadowDistance = stripUnit(shadowDistance);
if (typeof strippedShadowDistance === 'number') {
return `${strippedShadowDistance / 2}em`;
}
return strippedShadowDistance;
};
export const shadowOffset = calculateShadowOffset(shadowDistance);
export const shadowBoxShadow = `0px -${shadowDistance} 0px 0px ${borderColor} inset`;
| Use border color from globals | Use border color from globals
| TypeScript | mit | maxdeviant/semantic-ui-css-in-js,maxdeviant/semantic-ui-css-in-js | ---
+++
@@ -1,13 +1,10 @@
import { stripUnit } from 'polished';
import {
+ borderColor,
defaultBorderRadius,
inputVerticalPadding,
pageFont
} from '../globals';
-
-// Begin extract
-const borderColor = '';
-// End extract
export const verticalMargin = '0em';
export const horizontalMargin = '0.25em'; |
945505839f9c446854fadbeef57c277205d3699c | ui/src/members/components/SelectUsers.tsx | ui/src/members/components/SelectUsers.tsx | // Libraries
import React, {PureComponent} from 'react'
//Components
import {MultiSelectDropdown, Dropdown} from 'src/clockface'
// Types
import {User} from '@influxdata/influx'
interface Props {
users: User[]
onSelect: (selectedIDs: string[]) => void
selectedUserIDs: string[]
}
export default class SelectUsers extends PureComponent<Props> {
public render() {
const {users} = this.props
return (
<>
<MultiSelectDropdown
selectedIDs={this.props.selectedUserIDs}
onChange={this.props.onSelect}
emptyText="Select user"
>
{users.map(u => (
<Dropdown.Item id={u.id} key={u.id} value={u}>
{u.name}
</Dropdown.Item>
))}
</MultiSelectDropdown>
</>
)
}
}
| // Libraries
import React, {PureComponent} from 'react'
//Components
import {MultiSelectDropdown, Dropdown} from 'src/clockface'
// Types
import {User} from '@influxdata/influx'
import {ComponentStatus} from '@influxdata/clockface'
interface Props {
users: User[]
onSelect: (selectedIDs: string[]) => void
selectedUserIDs: string[]
}
export default class SelectUsers extends PureComponent<Props> {
public render() {
const {users, selectedUserIDs, onSelect} = this.props
return (
<MultiSelectDropdown
selectedIDs={selectedUserIDs}
onChange={onSelect}
emptyText={this.emptyText}
status={this.dropdownStatus}
>
{users.map(u => (
<Dropdown.Item id={u.id} key={u.id} value={u}>
{u.name}
</Dropdown.Item>
))}
</MultiSelectDropdown>
)
}
private get emptyText(): string {
const {users} = this.props
if (!users || !users.length) {
return 'No users exist'
}
return 'Select user'
}
private get dropdownStatus(): ComponentStatus {
const {users} = this.props
if (!users || !users.length) {
return ComponentStatus.Disabled
}
return ComponentStatus.Default
}
}
| Update add users dropdown with an empty state | Update add users dropdown with an empty state
| TypeScript | mit | mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb | ---
+++
@@ -6,6 +6,7 @@
// Types
import {User} from '@influxdata/influx'
+import {ComponentStatus} from '@influxdata/clockface'
interface Props {
users: User[]
@@ -15,22 +16,37 @@
export default class SelectUsers extends PureComponent<Props> {
public render() {
- const {users} = this.props
+ const {users, selectedUserIDs, onSelect} = this.props
return (
- <>
- <MultiSelectDropdown
- selectedIDs={this.props.selectedUserIDs}
- onChange={this.props.onSelect}
- emptyText="Select user"
- >
- {users.map(u => (
- <Dropdown.Item id={u.id} key={u.id} value={u}>
- {u.name}
- </Dropdown.Item>
- ))}
- </MultiSelectDropdown>
- </>
+ <MultiSelectDropdown
+ selectedIDs={selectedUserIDs}
+ onChange={onSelect}
+ emptyText={this.emptyText}
+ status={this.dropdownStatus}
+ >
+ {users.map(u => (
+ <Dropdown.Item id={u.id} key={u.id} value={u}>
+ {u.name}
+ </Dropdown.Item>
+ ))}
+ </MultiSelectDropdown>
)
}
+
+ private get emptyText(): string {
+ const {users} = this.props
+ if (!users || !users.length) {
+ return 'No users exist'
+ }
+ return 'Select user'
+ }
+
+ private get dropdownStatus(): ComponentStatus {
+ const {users} = this.props
+ if (!users || !users.length) {
+ return ComponentStatus.Disabled
+ }
+ return ComponentStatus.Default
+ }
} |
eeed5e50da724789e9a25168353fc9e7c6b2db1a | src/components/Header.tsx | src/components/Header.tsx | import React from "react";
import { ToggleThemeButton } from "./ToggleThemeButton";
export function Header() {
return (
<nav className="navbar">
<a className="navbar-brand" href="images/avatar.jpg" title="Click to see my face :)">
<img src="images/avatar.jpg" className="border rounded-circle" />
Victor Nogueira
</a>
<div className="navbar-content ml-auto">
<ToggleThemeButton />
</div>
</nav>
);
}
| import React from "react";
import { ToggleThemeButton } from "./ToggleThemeButton";
export function Header() {
return (
<nav className="navbar">
<div className="navbar-brand">
<a
className="navbar-brand"
href="images/avatar.jpg"
data-toggle="tooltip"
data-placement="right"
data-title="Willing to see my face? :)"
>
<img src="images/avatar.jpg" className="border rounded-circle" />
</a>
Victor Nogueira
</div>
<div className="navbar-content ml-auto">
<ToggleThemeButton />
</div>
</nav>
);
}
| Remove link from the name, in the top bar | Remove link from the name, in the top bar
| TypeScript | mit | felladrin/felladrin.github.io,felladrin/felladrin.github.io | ---
+++
@@ -4,10 +4,18 @@
export function Header() {
return (
<nav className="navbar">
- <a className="navbar-brand" href="images/avatar.jpg" title="Click to see my face :)">
- <img src="images/avatar.jpg" className="border rounded-circle" />
+ <div className="navbar-brand">
+ <a
+ className="navbar-brand"
+ href="images/avatar.jpg"
+ data-toggle="tooltip"
+ data-placement="right"
+ data-title="Willing to see my face? :)"
+ >
+ <img src="images/avatar.jpg" className="border rounded-circle" />
+ </a>
Victor Nogueira
- </a>
+ </div>
<div className="navbar-content ml-auto">
<ToggleThemeButton />
</div> |
475cffc40a7a95eb59be212c46dfc7387ea583d5 | packages/graphql-codegen-cli/src/utils/document-finder.ts | packages/graphql-codegen-cli/src/utils/document-finder.ts | import { parse } from 'graphql-codegen-core';
import { Source } from 'graphql';
import gqlPluck from 'graphql-tag-pluck';
export function extractDocumentStringFromCodeFile(source: Source): string | void {
try {
const parsed = parse(source.body);
if (parsed) {
return source.body;
}
} catch (e) {
return gqlPluck.fromFile.sync(source.name) || null;
}
}
| import { parse } from 'graphql-codegen-core';
import { Source } from 'graphql';
import gqlPluck from 'graphql-tag-pluck';
export function extractDocumentStringFromCodeFile(source: Source): string | void {
try {
const parsed = parse(source.body);
if (parsed) {
return source.body;
}
} catch (e) {
try {
return gqlPluck.fromFile.sync(source.name) || null;
} catch (e) {
throw new e.constructor(`${e.message} at ${source.name}`);
}
}
}
| Add borken document to error report | Add borken document to error report
| TypeScript | mit | dotansimha/graphql-code-generator,dotansimha/graphql-code-generator,dotansimha/graphql-code-generator | ---
+++
@@ -10,6 +10,10 @@
return source.body;
}
} catch (e) {
- return gqlPluck.fromFile.sync(source.name) || null;
+ try {
+ return gqlPluck.fromFile.sync(source.name) || null;
+ } catch (e) {
+ throw new e.constructor(`${e.message} at ${source.name}`);
+ }
}
} |
ddd33055eeeb3dab10663d26c9eb812cdb22ef31 | demo/containers/App.tsx | demo/containers/App.tsx | // import all the examples
import BasicInteractiveMap from "../examples/BasicInteractiveMap";
import HighResolutionMap from "../examples/HighResolutionMap";
import Example from "../components/Example";
import Header from "../components/Header";
import HEREMap from "../../src/HEREMap";
import * as React from "react";
export default class App extends React.Component<any, any> {
public render(): JSX.Element {
const examples = this.getExamples();
const center = {
lat: 55.17307,
lng: 15.17594,
};
return (
<div className="content">
<Header
examplesLength={examples.length}
/>
<section id="title-block">
<div className="container">
<div className="offset">
<h1>React HERE Maps</h1>
<h2>React wrapper for the HERE Maps API for JavaScript</h2>
</div>
</div>
<HEREMap
zoom={7}
center={center}
hidpi={true}
appId="NoiW7CS2CC05ppu95hyL"
appCode="28L997fKdiJiY7TVVEsEGQ"
/>
</section>
{ examples.map((example, index) => (
<Example
key={index}
example={example}
/>
))}
</div>
);
}
private getExamples(): Array<any> {
const examples: Array<any> = [
BasicInteractiveMap,
HighResolutionMap,
];
return examples;
}
}
| // import all the examples
import BasicInteractiveMap from "../examples/BasicInteractiveMap";
import HighResolutionMap from "../examples/HighResolutionMap";
import Example from "../components/Example";
import Header from "../components/Header";
import HEREMap from "../../src/HEREMap";
import * as React from "react";
export default class App extends React.Component<any, any> {
public render(): JSX.Element {
const examples = this.getExamples();
const center = {
lat: 55.17307,
lng: 15.17594,
};
return (
<div className="content">
<Header
examplesLength={examples.length}
/>
<section id="title-block">
<div className="container">
<div className="offset">
<h1>React HERE Maps</h1>
<h2>React wrapper for the HERE Maps API for JavaScript</h2>
</div>
</div>
<HEREMap
zoom={7}
center={center}
hidpi={true}
interactive={false}
appId="NoiW7CS2CC05ppu95hyL"
appCode="28L997fKdiJiY7TVVEsEGQ"
/>
</section>
{ examples.map((example, index) => (
<Example
key={index}
example={example}
/>
))}
</div>
);
}
private getExamples(): Array<any> {
const examples: Array<any> = [
BasicInteractiveMap,
HighResolutionMap,
];
return examples;
}
}
| Set interactive to false in title block HERE Map on demo site. | Set interactive to false in title block HERE Map on demo site.
| TypeScript | mit | Josh-ES/react-here-maps,Josh-ES/react-here-maps | ---
+++
@@ -34,6 +34,7 @@
zoom={7}
center={center}
hidpi={true}
+ interactive={false}
appId="NoiW7CS2CC05ppu95hyL"
appCode="28L997fKdiJiY7TVVEsEGQ"
/> |
f91974faf59fbde1002e42b59ed893b13c3da549 | WebUtils/src/ts/WebUtils/LabKey.ts | WebUtils/src/ts/WebUtils/LabKey.ts | declare const LABKEY: {
CSRF: string,
ActionURL: any,
getModuleContext(moduleName: string): any;
};
export function getCSRF(): string {
return LABKEY.CSRF || "";
}
export function getCurrentController(): string {
return LABKEY.ActionURL.getController();
}
export function getCurrentContainer(): string {
return LABKEY.ActionURL.getContainer();
}
export function getBaseURL(): string {
return LABKEY.ActionURL.getBaseURL();
}
export function buildURL(controller: string, action: string, container?: string): string {
return LABKEY.ActionURL.buildURL(controller, action, container);
}
declare const __WebUtilsPageLoadData: any;
export function getPageLoadData(): any {
return __WebUtilsPageLoadData;
}
export function getModuleContext(moduleName: string): any {
return LABKEY.getModuleContext(moduleName) || {};
} | declare const LABKEY: {
CSRF: string,
ActionURL: any,
getModuleContext(moduleName: string): any;
};
export function getCSRF(): string {
return LABKEY.CSRF || "";
}
export function getCurrentController(): string {
return LABKEY.ActionURL.getController();
}
export function getCurrentContainer(): string {
return LABKEY.ActionURL.getContainer();
}
export function getBaseURL(): string {
return LABKEY.ActionURL.getBaseURL();
}
export function buildURL(controller: string, action: string, container: string): string {
return LABKEY.ActionURL.buildURL(controller, action, container);
}
export function buildURLWithParams(controller: string, action: string, container: string, queryParams: {[name: string]: string}): string {
return LABKEY.ActionURL.buildURL(controller, action, container, queryParams);
}
declare const __WebUtilsPageLoadData: any;
export function getPageLoadData(): any {
return __WebUtilsPageLoadData;
}
export function getModuleContext(moduleName: string): any {
return LABKEY.getModuleContext(moduleName) || {};
} | Add a method to get URLs with params. | Add a method to get URLs with params.
| TypeScript | apache-2.0 | WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules | ---
+++
@@ -20,8 +20,12 @@
return LABKEY.ActionURL.getBaseURL();
}
-export function buildURL(controller: string, action: string, container?: string): string {
+export function buildURL(controller: string, action: string, container: string): string {
return LABKEY.ActionURL.buildURL(controller, action, container);
+}
+
+export function buildURLWithParams(controller: string, action: string, container: string, queryParams: {[name: string]: string}): string {
+ return LABKEY.ActionURL.buildURL(controller, action, container, queryParams);
}
declare const __WebUtilsPageLoadData: any; |
e051f572bd24c60848cac4a27c9b7ecc42cee1d9 | pages/_error.tsx | pages/_error.tsx | import React from 'react';
import { NextPageContext } from 'next';
import Link from 'next/link';
import BasePage from '../components/BasePage';
import Header from '../components/Header';
import Noise from '../components/Noise';
import styles from './_error.module.css';
export interface ErrorProps {
statusCode?: number;
}
export function ErrorPage({statusCode}: ErrorProps) {
return (
<BasePage>
<Header/>
<div className={styles.errorWrapper}>
<Noise className={styles.errorImage} />
<div>
<h1>oops</h1>
<h2>error {statusCode ? statusCode : 'on client'}</h2>
<p className={styles.errorLinks}>
<Link href='/'>
<a>Home</a>
</Link>
//
<a href='#' onClick={() => history.back()}>Back</a>
</p>
</div>
</div>
</BasePage>
);
}
ErrorPage.getInitialProps = ({ res, err }: NextPageContext): ErrorProps => {
const statusCode = res ? res.statusCode : err ? (err as any).statusCode : null;
return { statusCode };
};
export default ErrorPage;
| import React from 'react';
import { NextPageContext } from 'next';
import Link from 'next/link';
import BasePage from '../components/BasePage';
import Header from '../components/Header';
import Noise from '../components/Noise';
import styles from './_error.module.css';
export interface ErrorProps {
statusCode?: number;
}
export function ErrorPage({statusCode}: ErrorProps) {
return (
<BasePage>
<Header/>
<div className={styles.errorWrapper}>
<Noise className={styles.errorImage} />
<div>
<h1>oops</h1>
<h2>error {statusCode ? statusCode : 'on client'}</h2>
<p className={styles.errorLinks}>
<Link href='/'>
<a>Home</a>
</Link>
//
<a href='#' onClick={() => history.back()}>Back</a>
</p>
</div>
</div>
</BasePage>
);
}
ErrorPage.getInitialProps = ({ res, err }: NextPageContext): ErrorProps => {
const statusCode = res ? res.statusCode : err ? (err as any).statusCode : 404;
return { statusCode };
};
export default ErrorPage;
| Fix error to 404 on client by default | Fix error to 404 on client by default
| TypeScript | mit | AsherFoster/asherfoster.github.com,AsherFoster/asherfoster.github.com | ---
+++
@@ -33,7 +33,7 @@
}
ErrorPage.getInitialProps = ({ res, err }: NextPageContext): ErrorProps => {
- const statusCode = res ? res.statusCode : err ? (err as any).statusCode : null;
+ const statusCode = res ? res.statusCode : err ? (err as any).statusCode : 404;
return { statusCode };
};
|
f27556523f400c068a8cc845119734454fdd7df1 | packages/@sanity/desk-tool/src/panes/documentPane/changesPanel/helpers.ts | packages/@sanity/desk-tool/src/panes/documentPane/changesPanel/helpers.ts | import {Diff, AnnotationDetails, visitDiff} from '@sanity/field/diff'
export function collectLatestAuthorAnnotations(diff: Diff): AnnotationDetails[] {
const authorMap = new Map<string, AnnotationDetails>()
visitDiff(diff, child => {
if (child.action === 'unchanged' || !('annotation' in child) || !child.annotation) {
return true
}
const {author, timestamp} = child.annotation
const previous = authorMap.get(author)
if (!previous || previous.timestamp < timestamp) {
authorMap.set(author, child.annotation)
}
return true
})
return Array.from(authorMap.values())
}
| import {Diff, AnnotationDetails, visitDiff} from '@sanity/field/diff'
export function collectLatestAuthorAnnotations(diff: Diff): AnnotationDetails[] {
const authorMap = new Map<string, AnnotationDetails>()
visitDiff(diff, child => {
if (child.action === 'unchanged' || !('annotation' in child) || !child.annotation) {
return true
}
const {author, timestamp} = child.annotation
const previous = authorMap.get(author)
if (!previous || previous.timestamp < timestamp) {
authorMap.set(author, child.annotation)
}
return true
})
return Array.from(authorMap.values()).sort(
(a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp)
)
}
| Sort latest author annotations by timestamp | [desk-tool] Sort latest author annotations by timestamp
| TypeScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -16,5 +16,7 @@
return true
})
- return Array.from(authorMap.values())
+ return Array.from(authorMap.values()).sort(
+ (a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp)
+ )
} |
db97eb66138da46b051bd243adf5c5b2db6167a4 | examples/with-typescript/src/index.ts | examples/with-typescript/src/index.ts | import express from 'express';
let app = require('./server').default;
if (module.hot) {
module.hot.accept('./server', () => {
console.log('🔁 HMR Reloading `./server`...');
try {
app = require('./server').default;
} catch (error) {
console.error(error);
}
});
console.info('✅ Server-side HMR Enabled!');
}
const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
export default express()
.use((req, res) => app.handle(req, res))
.listen(port, (err: Error) => {
if (err) {
console.error(err);
return;
}
console.log(`> App started http://localhost:${port}`)
});
| import express from 'express';
let app = require('./server').default;
if (module.hot) {
module.hot.accept('./server', () => {
console.log('🔁 HMR Reloading `./server`...');
try {
app = require('./server').default;
} catch (error) {
console.error(error);
}
});
console.info('✅ Server-side HMR Enabled!');
}
const port = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
export default express()
.use((req, res) => app.handle(req, res))
.listen(port, () => {
console.log(`> App started http://localhost:${port}`)
});
| Fix error running with-typescript example | Fix error running with-typescript example
Fixes the following error -
```
src/index.ts:22:17 - error TS2769: No overload matches this call.
The last overload gave the following error.
Argument of type '(err: Error) => void' is not assignable to parameter of type '() => void'.
22 .listen(port, (err: Error) => {
~~~~~~~~~~~~~~~~~
```
Closes #1478 | TypeScript | mit | jaredpalmer/razzle,jaredpalmer/razzle | ---
+++
@@ -18,10 +18,6 @@
export default express()
.use((req, res) => app.handle(req, res))
- .listen(port, (err: Error) => {
- if (err) {
- console.error(err);
- return;
- }
+ .listen(port, () => {
console.log(`> App started http://localhost:${port}`)
}); |
68f4ddf1fb2ef0181992cf38e1d649953de2b903 | src/core/model/document.ts | src/core/model/document.ts | import {Resource} from './resource';
import {copy} from 'tsfun';
import {subtract} from 'tsfun/objects';
import {NewDocument} from "./new-document";
import {Action} from './action';
export interface Document extends NewDocument {
resource : Resource;
modified: Action[];
created: Action;
}
/**
* Companion object
*/
export module Document {
export function isValid(document: Document, missingIdLegal = false): boolean {
if (!document.resource) return false;
if (!document.resource.id && !missingIdLegal) return false;
if (!document.resource.relations) return false;
if (!document.created) return false;
return true;
}
export function removeFields<D extends Document>(fields: Array<string>) {
return (document: D): D => {
const result = copy(document);
result.resource = subtract(fields)(document.resource) as Resource;
return result as D;
};
}
export function removeRelations<D extends Document>(relations: Array<string>) {
return (document: D): D => {
const result = copy(document);
result.resource.relations = subtract(relations)(result.resource.relations);
return result as D;
};
}
} | import {Resource} from './resource';
import {copy} from 'tsfun';
import {subtract} from 'tsfun/objects';
import {NewDocument} from "./new-document";
import {Action} from './action';
export interface Document extends NewDocument {
resource : Resource;
modified: Action[];
created: Action;
}
/**
* Companion object
*/
export module Document {
export function isValid(document: Document, missingIdLegal = false): boolean {
if (!document.resource) return false;
if (!document.resource.id && !missingIdLegal) return false;
if (!document.resource.relations) return false;
if (!document.created) return false;
if (!document.modified || document.modified.length === 0) return false;
return true;
}
export function removeFields<D extends Document>(fields: Array<string>) {
return (document: D): D => {
const result = copy(document);
result.resource = subtract(fields)(document.resource) as Resource;
return result as D;
};
}
export function removeRelations<D extends Document>(relations: Array<string>) {
return (document: D): D => {
const result = copy(document);
result.resource.relations = subtract(relations)(result.resource.relations);
return result as D;
};
}
} | Add check for modified in isValid | Add check for modified in isValid
| TypeScript | apache-2.0 | dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2 | ---
+++
@@ -24,6 +24,7 @@
if (!document.resource.id && !missingIdLegal) return false;
if (!document.resource.relations) return false;
if (!document.created) return false;
+ if (!document.modified || document.modified.length === 0) return false;
return true;
} |
22e842f179f68945b834a1cbe25c1df002113c10 | src/app/states/devices/ble/device-og-kit.ts | src/app/states/devices/ble/device-og-kit.ts | import { _ } from '@biesbjerg/ngx-translate-extract/dist/utils/utils';
import { DeviceType } from '../abstract-device';
import { DeviceParams, DeviceParamsModel, DeviceParamType } from '../device-params';
import { AbstractBLEDevice, RawBLEDevice } from './abstract-ble-device';
export class DeviceOGKit extends AbstractBLEDevice {
readonly deviceType = DeviceType.OGKit;
hitsPeriod = 1000;
params: DeviceParams = {
audioHits: true,
visualHits: true
};
paramsModel: DeviceParamsModel = {
audioHits: {
label: <string>_('SENSORS.PARAM.AUDIO_HITS'),
type: DeviceParamType.Boolean
},
visualHits: {
label: <string>_('SENSORS.PARAM.VISUAL_HITS'),
type: DeviceParamType.Boolean
}
};
constructor(rawDevice: RawBLEDevice) {
super(rawDevice);
this.apparatusVersion = rawDevice.name;
const manufacturerData =
rawDevice.advertising instanceof ArrayBuffer
? new Uint8Array(rawDevice.advertising).slice(23, 29)
: new Uint8Array(rawDevice.advertising.kCBAdvDataManufacturerData);
this.apparatusId = new TextDecoder('utf8').decode(manufacturerData).replace(/\0/g, '');
}
}
| import { _ } from '@biesbjerg/ngx-translate-extract/dist/utils/utils';
import { DeviceType } from '../abstract-device';
import { DeviceParams, DeviceParamsModel, DeviceParamType } from '../device-params';
import { AbstractBLEDevice, RawBLEDevice } from './abstract-ble-device';
export class DeviceOGKit extends AbstractBLEDevice {
readonly deviceType = DeviceType.OGKit;
hitsPeriod = 1000;
params: DeviceParams = {
audioHits: true,
visualHits: true
};
paramsModel: DeviceParamsModel = {
audioHits: {
label: <string>_('SENSORS.PARAM.AUDIO_HITS'),
type: DeviceParamType.Boolean
},
visualHits: {
label: <string>_('SENSORS.PARAM.VISUAL_HITS'),
type: DeviceParamType.Boolean
}
};
constructor(rawDevice: RawBLEDevice) {
super(rawDevice);
this.apparatusVersion = rawDevice.name;
let advertising: Uint8Array;
if (rawDevice.advertising instanceof ArrayBuffer) {
const manufacturerData = new Uint8Array(rawDevice.advertising);
const index = manufacturerData.indexOf(0xff);
advertising = manufacturerData.slice(index + 3, index + manufacturerData[index - 1]);
} else {
advertising = new Uint8Array(rawDevice.advertising.kCBAdvDataManufacturerData);
}
this.apparatusId = new TextDecoder('utf8').decode(advertising).replace(/\0/g, '');
}
}
| Fix OG-Kit name detection from advertising data | Fix OG-Kit name detection from advertising data
| TypeScript | apache-2.0 | openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile,openradiation/openradiation-mobile | ---
+++
@@ -25,10 +25,15 @@
constructor(rawDevice: RawBLEDevice) {
super(rawDevice);
this.apparatusVersion = rawDevice.name;
- const manufacturerData =
- rawDevice.advertising instanceof ArrayBuffer
- ? new Uint8Array(rawDevice.advertising).slice(23, 29)
- : new Uint8Array(rawDevice.advertising.kCBAdvDataManufacturerData);
- this.apparatusId = new TextDecoder('utf8').decode(manufacturerData).replace(/\0/g, '');
+ let advertising: Uint8Array;
+ if (rawDevice.advertising instanceof ArrayBuffer) {
+ const manufacturerData = new Uint8Array(rawDevice.advertising);
+ const index = manufacturerData.indexOf(0xff);
+ advertising = manufacturerData.slice(index + 3, index + manufacturerData[index - 1]);
+ } else {
+ advertising = new Uint8Array(rawDevice.advertising.kCBAdvDataManufacturerData);
+ }
+
+ this.apparatusId = new TextDecoder('utf8').decode(advertising).replace(/\0/g, '');
}
} |
c621aa9c43537074f894be0701642324424f9130 | src/components/utilities/input.tsx | src/components/utilities/input.tsx | import * as React from "react";
export interface InputProps{
onChange: (value: any) => void,
label?: string
id?: string,
class?: string,
value?: string
}
export function Input(props: InputProps) {
return <div className={props.class +" float-label"}>
<input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value)} />
<label> {props.label} </label>
</div>
} | import * as React from "react";
export interface InputProps{
onChange: (value: any) => void,
label?: string
id?: string,
class?: string,
value?: string
}
export function Input(props: InputProps) {
return <div className={props.class +" float-label"}>
<input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value === ""?undefined:e.target.value)} />
<label> {props.label} </label>
</div>
} | Return Undefined on Empty Input | Return Undefined on Empty Input
| TypeScript | mit | goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End,goodbye-island/S-Store-Front-End | ---
+++
@@ -10,7 +10,7 @@
export function Input(props: InputProps) {
return <div className={props.class +" float-label"}>
- <input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value)} />
+ <input required value={props.value} id={props.id} onChange={(e: any) => props.onChange(e.target.value === ""?undefined:e.target.value)} />
<label> {props.label} </label>
</div>
} |
67c024578f5c55a5880a4407592b9365eccc915f | src/main.ts | src/main.ts | /// <reference path="func.ts" />
declare var module;
declare var require;
if (module && module.exports && typeof require === 'function') {
module.exports = fun;
} | /// <reference path="type.ts" />
/// <reference path="func.ts" />
declare var module;
declare var require;
if (module && module.exports && typeof require === 'function') {
module.exports = fun;
} | Add mssing reference to type.ts | Add mssing reference to type.ts
| TypeScript | mit | federico-lox/fun.ts | ---
+++
@@ -1,3 +1,4 @@
+/// <reference path="type.ts" />
/// <reference path="func.ts" />
declare var module; |
d0dba1fce6dcc0b91c0561eda8707c5c5bb6e626 | client/src/app/videos/+video-edit/video-update.resolver.ts | client/src/app/videos/+video-edit/video-update.resolver.ts | import { Injectable } from '@angular/core'
import { VideoService } from '@app/shared/video/video.service'
import { ActivatedRouteSnapshot, Resolve } from '@angular/router'
import { map, switchMap } from 'rxjs/operators'
import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
import { VideoCaptionService } from '@app/shared/video-caption'
@Injectable()
export class VideoUpdateResolver implements Resolve<any> {
constructor (
private videoService: VideoService,
private videoChannelService: VideoChannelService,
private videoCaptionService: VideoCaptionService
) {}
resolve (route: ActivatedRouteSnapshot) {
const uuid: string = route.params[ 'uuid' ]
return this.videoService.getVideo(uuid)
.pipe(
switchMap(video => {
return this.videoService
.loadCompleteDescription(video.descriptionPath)
.pipe(map(description => Object.assign(video, { description })))
}),
switchMap(video => {
return this.videoChannelService
.listAccountVideoChannels(video.account)
.pipe(
map(result => result.data),
map(videoChannels => videoChannels.map(c => ({ id: c.id, label: c.displayName, support: c.support }))),
map(videoChannels => ({ video, videoChannels }))
)
}),
switchMap(({ video, videoChannels }) => {
return this.videoCaptionService
.listCaptions(video.id)
.pipe(
map(result => result.data),
map(videoCaptions => ({ video, videoChannels, videoCaptions }))
)
})
)
}
}
| import { Injectable } from '@angular/core'
import { VideoService } from '@app/shared/video/video.service'
import { ActivatedRouteSnapshot, Resolve } from '@angular/router'
import { map, switchMap } from 'rxjs/operators'
import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
import { VideoCaptionService } from '@app/shared/video-caption'
import { forkJoin } from 'rxjs'
@Injectable()
export class VideoUpdateResolver implements Resolve<any> {
constructor (
private videoService: VideoService,
private videoChannelService: VideoChannelService,
private videoCaptionService: VideoCaptionService
) {
}
resolve (route: ActivatedRouteSnapshot) {
const uuid: string = route.params[ 'uuid' ]
return this.videoService.getVideo(uuid)
.pipe(
switchMap(video => {
return forkJoin([
this.videoService
.loadCompleteDescription(video.descriptionPath)
.pipe(map(description => Object.assign(video, { description }))),
this.videoChannelService
.listAccountVideoChannels(video.account)
.pipe(
map(result => result.data),
map(videoChannels => videoChannels.map(c => ({ id: c.id, label: c.displayName, support: c.support })))
),
this.videoCaptionService
.listCaptions(video.id)
.pipe(
map(result => result.data)
)
])
}),
map(([ video, videoChannels, videoCaptions ]) => ({ video, videoChannels, videoCaptions }))
)
}
}
| Optimize video update page load | Optimize video update page load
| TypeScript | agpl-3.0 | Chocobozzz/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube | ---
+++
@@ -4,6 +4,7 @@
import { map, switchMap } from 'rxjs/operators'
import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
import { VideoCaptionService } from '@app/shared/video-caption'
+import { forkJoin } from 'rxjs'
@Injectable()
export class VideoUpdateResolver implements Resolve<any> {
@@ -11,35 +12,35 @@
private videoService: VideoService,
private videoChannelService: VideoChannelService,
private videoCaptionService: VideoCaptionService
- ) {}
+ ) {
+ }
resolve (route: ActivatedRouteSnapshot) {
const uuid: string = route.params[ 'uuid' ]
return this.videoService.getVideo(uuid)
- .pipe(
- switchMap(video => {
- return this.videoService
- .loadCompleteDescription(video.descriptionPath)
- .pipe(map(description => Object.assign(video, { description })))
- }),
- switchMap(video => {
- return this.videoChannelService
- .listAccountVideoChannels(video.account)
- .pipe(
- map(result => result.data),
- map(videoChannels => videoChannels.map(c => ({ id: c.id, label: c.displayName, support: c.support }))),
- map(videoChannels => ({ video, videoChannels }))
- )
- }),
- switchMap(({ video, videoChannels }) => {
- return this.videoCaptionService
- .listCaptions(video.id)
- .pipe(
- map(result => result.data),
- map(videoCaptions => ({ video, videoChannels, videoCaptions }))
- )
- })
- )
+ .pipe(
+ switchMap(video => {
+ return forkJoin([
+ this.videoService
+ .loadCompleteDescription(video.descriptionPath)
+ .pipe(map(description => Object.assign(video, { description }))),
+
+ this.videoChannelService
+ .listAccountVideoChannels(video.account)
+ .pipe(
+ map(result => result.data),
+ map(videoChannels => videoChannels.map(c => ({ id: c.id, label: c.displayName, support: c.support })))
+ ),
+
+ this.videoCaptionService
+ .listCaptions(video.id)
+ .pipe(
+ map(result => result.data)
+ )
+ ])
+ }),
+ map(([ video, videoChannels, videoCaptions ]) => ({ video, videoChannels, videoCaptions }))
+ )
}
} |
350ca39633924b9bd5c39feb846338633d73f9d2 | packages/hooks/src/useApolloClient.ts | packages/hooks/src/useApolloClient.ts | import React from 'react';
import { invariant } from 'ts-invariant';
import { getApolloContext } from '@apollo/react-common';
export function useApolloClient() {
const { client } = React.useContext(getApolloContext());
invariant(
client,
'No Apollo Client instance can be found. Please ensure that you ' +
'have called `ApolloProvider` higher up in your tree.'
);
return client;
}
| import React from 'react';
import { invariant } from 'ts-invariant';
import { getApolloContext } from '@apollo/react-common';
import ApolloClient from 'apollo-client';
export function useApolloClient(): ApolloClient<object> {
const { client } = React.useContext(getApolloContext());
invariant(
client,
'No Apollo Client instance can be found. Please ensure that you ' +
'have called `ApolloProvider` higher up in your tree.'
);
return client!;
}
| Make sure a returned `ApolloClient<object>` is enforced | Make sure a returned `ApolloClient<object>` is enforced
| TypeScript | mit | apollostack/react-apollo,apollographql/react-apollo,apollostack/react-apollo,apollographql/react-apollo | ---
+++
@@ -1,13 +1,14 @@
import React from 'react';
import { invariant } from 'ts-invariant';
import { getApolloContext } from '@apollo/react-common';
+import ApolloClient from 'apollo-client';
-export function useApolloClient() {
+export function useApolloClient(): ApolloClient<object> {
const { client } = React.useContext(getApolloContext());
invariant(
client,
'No Apollo Client instance can be found. Please ensure that you ' +
'have called `ApolloProvider` higher up in your tree.'
);
- return client;
+ return client!;
} |
595f002a2bde6ccdd4647ba9f55071662ab26c0d | src/simpleExample/index.ts | src/simpleExample/index.ts | // All in one file example
import { Component, getStyle, Actions, StyleGroup, run, Inputs, logFns } from '../core'
import { h, View, viewHandler } from '../interfaces/view'
import { styleHandler } from '../groups/style'
// Component
const state = {
count: 0,
}
type S = typeof state
const inputs: Inputs<S> = (s, F) => ({
inc: async () => {
await F.toAct('Inc')
setImmediate(() => {
F.toIn('inc')
})
},
})
const actions: Actions<S> = {
Inc: () => s => {
s.count++
},
}
const view: View<S> = async (s, F) => {
const style = getStyle(F)
return h('div', {
class: style('base'),
on: { click: F.in('inc') },
}, 'Count ' + s.count)
}
const style: StyleGroup = {
base: {
color: 'green',
fontSize: '40px',
},
}
const Root: Component<any> = {
state,
inputs,
actions,
interfaces: { view },
groups: { style },
}
const DEV = true
run({
Root,
record: DEV,
log: DEV,
groups: {
style: styleHandler('', DEV),
},
interfaces: {
view: viewHandler('#app'),
},
})
| // All in one file example
import { Component, getStyle, Actions, StyleGroup, run, Inputs } from '../core'
import { h, View, viewHandler } from '../interfaces/view'
import { styleHandler } from '../groups/style'
// Component
const state = {
count: 0,
}
type S = typeof state
const inputs: Inputs<S> = (s, F) => ({
inc: async () => {
await F.toAct('Inc')
setImmediate(() => {
F.toIn('inc')
})
},
})
const actions: Actions<S> = {
Inc: () => s => {
s.count++
},
}
const view: View<S> = async (s, F) => {
const style = getStyle(F)
return h('div', {
class: style('base'),
on: { click: F.in('inc') },
}, 'Count ' + s.count)
}
const style: StyleGroup = {
base: {
color: 'green',
fontSize: '40px',
},
}
const Root: Component<any> = {
state,
inputs,
actions,
interfaces: { view },
groups: { style },
}
const DEV = true
run({
Root,
record: DEV,
log: DEV,
groups: {
style: styleHandler('', DEV),
},
interfaces: {
view: viewHandler('#app'),
},
})
| Remove unused import from simpleExample | Remove unused import from simpleExample
| TypeScript | mit | FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal | ---
+++
@@ -1,5 +1,5 @@
// All in one file example
-import { Component, getStyle, Actions, StyleGroup, run, Inputs, logFns } from '../core'
+import { Component, getStyle, Actions, StyleGroup, run, Inputs } from '../core'
import { h, View, viewHandler } from '../interfaces/view'
import { styleHandler } from '../groups/style'
|
9afdb529c53498c5f9362ce70fcbe8255f575a06 | reactjs/src/stores/storeIdentifier.ts | reactjs/src/stores/storeIdentifier.ts | import RoleStore from './roleStore';
import TenantStore from './tenantStore';
import UserStore from './userStore';
import SessionStore from './sessionStore';
import AuthenticationStore from './authenticationStore';
import AccountStore from './accountStore';
export default class Stores {
static AuthenticationStore: string = getName(AuthenticationStore);
static RoleStore: string = getName(RoleStore);
static TenantStore: string = getName(TenantStore);
static UserStore: string = getName(UserStore);
static SessionStore: string = getName(SessionStore);
static AccountStore: string = getName(AccountStore);
}
function getName(store: any): string {
return abp.utils.toCamelCase(store.name);
}
| export default class Stores {
static AuthenticationStore: string = 'authenticationStore';
static RoleStore: string = 'roleStore';
static TenantStore: string = 'tenantStore';
static UserStore: string = 'userStore';
static SessionStore: string = 'sessionStore';
static AccountStore: string = 'accountStore';
}
| Store 'e' is not available error fixed for production build | Store 'e' is not available error fixed for production build
| TypeScript | mit | aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template | ---
+++
@@ -1,19 +1,8 @@
-import RoleStore from './roleStore';
-import TenantStore from './tenantStore';
-import UserStore from './userStore';
-import SessionStore from './sessionStore';
-import AuthenticationStore from './authenticationStore';
-import AccountStore from './accountStore';
-
export default class Stores {
- static AuthenticationStore: string = getName(AuthenticationStore);
- static RoleStore: string = getName(RoleStore);
- static TenantStore: string = getName(TenantStore);
- static UserStore: string = getName(UserStore);
- static SessionStore: string = getName(SessionStore);
- static AccountStore: string = getName(AccountStore);
+ static AuthenticationStore: string = 'authenticationStore';
+ static RoleStore: string = 'roleStore';
+ static TenantStore: string = 'tenantStore';
+ static UserStore: string = 'userStore';
+ static SessionStore: string = 'sessionStore';
+ static AccountStore: string = 'accountStore';
}
-
-function getName(store: any): string {
- return abp.utils.toCamelCase(store.name);
-} |
513c475e3d9a0661b72364121c67d22a44c9d7d6 | desktop/app/src/deeplinkTracking.tsx | desktop/app/src/deeplinkTracking.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Logger} from 'flipper-common';
export type OpenPluginParams = {
pluginId: string;
client: string | undefined;
devices: string[];
payload: string | undefined;
};
export type DeeplinkInteractionState =
| 'INIT'
| 'ERROR'
| 'PLUGIN_LIGHTHOUSE_BAIL'
| 'PLUGIN_STATUS_BAIL'
| 'PLUGIN_DEVICE_BAIL'
| 'PLUGIN_CLIENT_BAIL'
| 'PLUGIN_DEVICE_SELECTION_BAIL'
| 'PLUGIN_CLIENT_SELECTION_BAIL'
| 'PLUGIN_DEVICE_UNSUPPORTED'
| 'PLUGIN_CLIENT_UNSUPPORTED'
| 'PLUGIN_OPEN_SUCCESS';
export type DeeplinkInteraction = {
state: DeeplinkInteractionState;
errorMessage?: string;
plugin?: OpenPluginParams;
extra?: object;
};
export function track(
logger: Logger,
query: string,
interaction: DeeplinkInteraction,
) {
logger.track(
'usage',
'deeplink',
{
...interaction,
query,
},
interaction.plugin?.pluginId,
);
}
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Logger} from 'flipper-common';
export type OpenPluginParams = {
pluginId: string;
client: string | undefined;
devices: string[];
payload: string | undefined;
};
export type DeeplinkInteractionState =
| 'INIT'
| 'ERROR'
| 'PLUGIN_LIGHTHOUSE_BAIL' // User did not connect to VPN/Lighthouse when asked
| 'PLUGIN_STATUS_BAIL' // User did not install the plugin (has `extra` attribute with more information)
| 'PLUGIN_DEVICE_BAIL' // User did not launch a new device
| 'PLUGIN_CLIENT_BAIL' // User did not launch a supported app
| 'PLUGIN_DEVICE_SELECTION_BAIL' // User closed dialogue asking to select one of many devices
| 'PLUGIN_CLIENT_SELECTION_BAIL' // User closed dialogue asking to select one of many apps
| 'PLUGIN_DEVICE_UNSUPPORTED' // The device did not match the requirements specified in the deeplink URL
| 'PLUGIN_CLIENT_UNSUPPORTED' // The already opened app did not match the requirements specified in the deeplink URL
| 'PLUGIN_OPEN_SUCCESS'; // Everything is awesome
export type DeeplinkInteraction = {
state: DeeplinkInteractionState;
errorMessage?: string;
plugin?: OpenPluginParams;
extra?: object;
};
export function track(
logger: Logger,
query: string,
interaction: DeeplinkInteraction,
) {
logger.track(
'usage',
'deeplink',
{
...interaction,
query,
},
interaction.plugin?.pluginId,
);
}
| Add comments for interaction events | Add comments for interaction events
Summary: Per title
Reviewed By: mweststrate
Differential Revision: D32171224
fbshipit-source-id: b7610e8c10674d56e75468f46a3fd0664d70b4aa
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -19,15 +19,15 @@
export type DeeplinkInteractionState =
| 'INIT'
| 'ERROR'
- | 'PLUGIN_LIGHTHOUSE_BAIL'
- | 'PLUGIN_STATUS_BAIL'
- | 'PLUGIN_DEVICE_BAIL'
- | 'PLUGIN_CLIENT_BAIL'
- | 'PLUGIN_DEVICE_SELECTION_BAIL'
- | 'PLUGIN_CLIENT_SELECTION_BAIL'
- | 'PLUGIN_DEVICE_UNSUPPORTED'
- | 'PLUGIN_CLIENT_UNSUPPORTED'
- | 'PLUGIN_OPEN_SUCCESS';
+ | 'PLUGIN_LIGHTHOUSE_BAIL' // User did not connect to VPN/Lighthouse when asked
+ | 'PLUGIN_STATUS_BAIL' // User did not install the plugin (has `extra` attribute with more information)
+ | 'PLUGIN_DEVICE_BAIL' // User did not launch a new device
+ | 'PLUGIN_CLIENT_BAIL' // User did not launch a supported app
+ | 'PLUGIN_DEVICE_SELECTION_BAIL' // User closed dialogue asking to select one of many devices
+ | 'PLUGIN_CLIENT_SELECTION_BAIL' // User closed dialogue asking to select one of many apps
+ | 'PLUGIN_DEVICE_UNSUPPORTED' // The device did not match the requirements specified in the deeplink URL
+ | 'PLUGIN_CLIENT_UNSUPPORTED' // The already opened app did not match the requirements specified in the deeplink URL
+ | 'PLUGIN_OPEN_SUCCESS'; // Everything is awesome
export type DeeplinkInteraction = {
state: DeeplinkInteractionState; |
458b35d82cbe72a1f8d22070c9c032ef186ee4c6 | src/navigation/replace.tsx | src/navigation/replace.tsx | import React from "react";
import { domToReact } from "html-react-parser";
import attributesToProps from "html-react-parser/lib/attributes-to-props";
import { HashLink as Link } from "react-router-hash-link";
export function replace(domNode: any) {
if (domNode.name && domNode.name === "a") {
const { href, ...rest } = domNode.attribs;
const props = attributesToProps(rest);
if(href && !href.startsWith("http:") && !href.startsWith("https:") && !href.startsWith("mailto:")){
// Local (relative) links pimped with react router navigation
return (
<Link to={href} {...props}>
{domToReact(domNode.children, { replace })}
</Link>
);
}else{
// Default behaviour for links to fully qualified URLs
}
}
// !whitelist.includes(domNode.name) &&
// domNode.type !== "text" &&
// console.dir(domNode, { depth: null });
}
export const whitelist = [
"a",
"span",
"li",
"ul",
"div",
"i",
"br",
"img",
"input",
"form",
"nav",
"small",
];
| import React from "react";
import { domToReact } from "html-react-parser";
import attributesToProps from "html-react-parser/lib/attributes-to-props";
import { HashLink as Link } from "react-router-hash-link";
export function replace(domNode: any) {
if (domNode.name && domNode.name === "a") {
const { href, ...rest } = domNode.attribs;
const props = attributesToProps(rest);
if (
href &&
!href.startsWith("http:") &&
!href.startsWith("https:") &&
!href.startsWith("mailto:") &&
!href.startsWith("//assets.ctfassets.net")
) {
// Local (relative) links pimped with react router navigation
return (
<Link to={href} {...props}>
{domToReact(domNode.children, { replace })}
</Link>
);
} else {
// Default behaviour for links to fully qualified URLs
}
}
// !whitelist.includes(domNode.name) &&
// domNode.type !== "text" &&
// console.dir(domNode, { depth: null });
}
export const whitelist = [
"a",
"span",
"li",
"ul",
"div",
"i",
"br",
"img",
"input",
"form",
"nav",
"small",
];
| Fix external links for example reports breaking | DS: Fix external links for example reports breaking
| TypeScript | apache-2.0 | saasquatch/saasquatch-docs,saasquatch/saasquatch-docs,saasquatch/saasquatch-docs | ---
+++
@@ -7,14 +7,20 @@
if (domNode.name && domNode.name === "a") {
const { href, ...rest } = domNode.attribs;
const props = attributesToProps(rest);
- if(href && !href.startsWith("http:") && !href.startsWith("https:") && !href.startsWith("mailto:")){
+ if (
+ href &&
+ !href.startsWith("http:") &&
+ !href.startsWith("https:") &&
+ !href.startsWith("mailto:") &&
+ !href.startsWith("//assets.ctfassets.net")
+ ) {
// Local (relative) links pimped with react router navigation
return (
<Link to={href} {...props}>
{domToReact(domNode.children, { replace })}
</Link>
- );
- }else{
+ );
+ } else {
// Default behaviour for links to fully qualified URLs
}
} |
00dc902fee69f3c388bd63e2704c4c3bef1ab3cc | src/workerExample/index.ts | src/workerExample/index.ts | import { runWorker, run } from '../core'
import { moduleDef } from './module'
// TODO: make this variable dynamic, implement a toggle button for that
const runInWorker = true
if (runInWorker) {
// Running Fractal in a worker thread
runWorker({
Root: 'in-worker', // no matter what you put here ;) because Root component is imported inside the worker
worker: new Worker('worker.js'),
...moduleDef,
})
} else {
// Running Fractal in the main thread
run(moduleDef)
}
| import { runWorker, run } from '../core'
import { moduleDef } from './module'
// TODO: make this variable dynamic, implement a toggle button for that
const runInWorker = true
if (runInWorker) {
// Running Fractal in a worker thread
runWorker({
worker: new Worker('worker.js'),
...moduleDef,
})
} else {
// Running Fractal in the main thread
run(moduleDef)
}
| Remove unused stuff in worker and playground example | Remove unused stuff in worker and playground example
| TypeScript | mit | FractalBlocks/Fractal,FractalBlocks/Fractal,FractalBlocks/Fractal | ---
+++
@@ -7,7 +7,6 @@
if (runInWorker) {
// Running Fractal in a worker thread
runWorker({
- Root: 'in-worker', // no matter what you put here ;) because Root component is imported inside the worker
worker: new Worker('worker.js'),
...moduleDef,
}) |
05798c2f4610a7c82fc0e1a7b7b75da93f60233e | src/vs/workbench/parts/extensions/electron-browser/extensionsFileTemplate.ts | src/vs/workbench/parts/extensions/electron-browser/extensionsFileTemplate.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
export const SchemaId = 'vscode://schemas/extensions';
export const Schema: IJSONSchema = {
id: SchemaId,
type: 'object',
title: localize('app.extensions.json.title', "Extensions"),
properties: {
recommendations: {
type: 'array',
description: localize('app.extensions.json.recommendations', "List of extension recommendations."),
items: {
'type': 'string',
}
}
}
};
export const Content: string = [
'{',
'\t// See http://go.microsoft.com/fwlink/?LinkId=827846',
'\t// for the documentation about the extensions.json format',
'\t"recommendations": [',
'\t\t',
'\t]',
'}'
].join('\n'); | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
export const SchemaId = 'vscode://schemas/extensions';
export const Schema: IJSONSchema = {
id: SchemaId,
type: 'object',
title: localize('app.extensions.json.title', "Extensions"),
properties: {
recommendations: {
type: 'array',
description: localize('app.extensions.json.recommendations', "List of extensions recommendations. The identifier of an extension is always ${publisher}.${name}. For example: vscode.csharp."),
items: {
'type': 'string',
}
}
}
};
export const Content: string = [
'{',
'\t// See http://go.microsoft.com/fwlink/?LinkId=827846',
'\t// for the documentation about the extensions.json format',
'\t"recommendations": [',
'\t\t',
'\t]',
'}'
].join('\n'); | Update description of recommendations prop | Update description of recommendations prop
| TypeScript | mit | zyml/vscode,zyml/vscode,Microsoft/vscode,rishii7/vscode,charlespierce/vscode,hashhar/vscode,stringham/vscode,0xmohit/vscode,matthewshirley/vscode,zyml/vscode,veeramarni/vscode,radshit/vscode,microsoft/vscode,hashhar/vscode,microlv/vscode,charlespierce/vscode,cleidigh/vscode,landonepps/vscode,zyml/vscode,veeramarni/vscode,joaomoreno/vscode,DustinCampbell/vscode,DustinCampbell/vscode,cleidigh/vscode,eamodio/vscode,mjbvz/vscode,microlv/vscode,hungys/vscode,matthewshirley/vscode,Microsoft/vscode,hoovercj/vscode,gagangupt16/vscode,mjbvz/vscode,cleidigh/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,jchadwick/vscode,the-ress/vscode,landonepps/vscode,zyml/vscode,cleidigh/vscode,Microsoft/vscode,DustinCampbell/vscode,microlv/vscode,landonepps/vscode,mjbvz/vscode,microlv/vscode,radshit/vscode,joaomoreno/vscode,KattMingMing/vscode,charlespierce/vscode,0xmohit/vscode,jchadwick/vscode,microsoft/vscode,cleidigh/vscode,radshit/vscode,veeramarni/vscode,hungys/vscode,joaomoreno/vscode,Zalastax/vscode,joaomoreno/vscode,joaomoreno/vscode,Zalastax/vscode,charlespierce/vscode,stringham/vscode,gagangupt16/vscode,DustinCampbell/vscode,joaomoreno/vscode,eamodio/vscode,charlespierce/vscode,gagangupt16/vscode,hashhar/vscode,mjbvz/vscode,rishii7/vscode,KattMingMing/vscode,gagangupt16/vscode,eamodio/vscode,joaomoreno/vscode,zyml/vscode,cleidigh/vscode,eamodio/vscode,Zalastax/vscode,landonepps/vscode,KattMingMing/vscode,hoovercj/vscode,landonepps/vscode,jchadwick/vscode,hungys/vscode,joaomoreno/vscode,the-ress/vscode,joaomoreno/vscode,the-ress/vscode,radshit/vscode,cleidigh/vscode,jchadwick/vscode,Microsoft/vscode,hoovercj/vscode,KattMingMing/vscode,veeramarni/vscode,radshit/vscode,zyml/vscode,mjbvz/vscode,mjbvz/vscode,jchadwick/vscode,hoovercj/vscode,0xmohit/vscode,Microsoft/vscode,rishii7/vscode,stringham/vscode,stringham/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,rishii7/vscode,gagangupt16/vscode,hungys/vscode,rishii7/vscode,veeramarni/vscode,the-ress/vscode,landonepps/vscode,jchadwick/vscode,hoovercj/vscode,microsoft/vscode,jchadwick/vscode,charlespierce/vscode,stringham/vscode,Microsoft/vscode,stringham/vscode,radshit/vscode,gagangupt16/vscode,mjbvz/vscode,mjbvz/vscode,eamodio/vscode,gagangupt16/vscode,0xmohit/vscode,microsoft/vscode,jchadwick/vscode,veeramarni/vscode,microlv/vscode,charlespierce/vscode,hashhar/vscode,gagangupt16/vscode,mjbvz/vscode,joaomoreno/vscode,radshit/vscode,hungys/vscode,charlespierce/vscode,hoovercj/vscode,the-ress/vscode,zyml/vscode,hoovercj/vscode,KattMingMing/vscode,eamodio/vscode,hungys/vscode,mjbvz/vscode,radshit/vscode,stringham/vscode,gagangupt16/vscode,hoovercj/vscode,jchadwick/vscode,DustinCampbell/vscode,0xmohit/vscode,joaomoreno/vscode,landonepps/vscode,cleidigh/vscode,joaomoreno/vscode,landonepps/vscode,landonepps/vscode,jchadwick/vscode,rishii7/vscode,charlespierce/vscode,cleidigh/vscode,matthewshirley/vscode,veeramarni/vscode,landonepps/vscode,0xmohit/vscode,KattMingMing/vscode,jchadwick/vscode,zyml/vscode,Zalastax/vscode,DustinCampbell/vscode,hashhar/vscode,matthewshirley/vscode,the-ress/vscode,stringham/vscode,the-ress/vscode,0xmohit/vscode,charlespierce/vscode,0xmohit/vscode,0xmohit/vscode,Zalastax/vscode,Zalastax/vscode,hashhar/vscode,matthewshirley/vscode,eamodio/vscode,DustinCampbell/vscode,matthewshirley/vscode,DustinCampbell/vscode,veeramarni/vscode,the-ress/vscode,microlv/vscode,microlv/vscode,hashhar/vscode,Microsoft/vscode,cleidigh/vscode,hoovercj/vscode,cleidigh/vscode,DustinCampbell/vscode,veeramarni/vscode,Zalastax/vscode,hungys/vscode,hashhar/vscode,Krzysztof-Cieslak/vscode,KattMingMing/vscode,hashhar/vscode,jchadwick/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,rishii7/vscode,the-ress/vscode,jchadwick/vscode,gagangupt16/vscode,the-ress/vscode,radshit/vscode,veeramarni/vscode,hashhar/vscode,matthewshirley/vscode,Krzysztof-Cieslak/vscode,charlespierce/vscode,Microsoft/vscode,veeramarni/vscode,joaomoreno/vscode,hoovercj/vscode,Zalastax/vscode,KattMingMing/vscode,gagangupt16/vscode,microlv/vscode,DustinCampbell/vscode,landonepps/vscode,microlv/vscode,cleidigh/vscode,charlespierce/vscode,microsoft/vscode,mjbvz/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,0xmohit/vscode,rishii7/vscode,matthewshirley/vscode,hungys/vscode,hashhar/vscode,hoovercj/vscode,microsoft/vscode,microlv/vscode,zyml/vscode,microlv/vscode,rishii7/vscode,landonepps/vscode,microsoft/vscode,hungys/vscode,0xmohit/vscode,eamodio/vscode,DustinCampbell/vscode,microlv/vscode,mjbvz/vscode,stringham/vscode,eamodio/vscode,KattMingMing/vscode,Microsoft/vscode,eamodio/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,KattMingMing/vscode,KattMingMing/vscode,veeramarni/vscode,zyml/vscode,zyml/vscode,landonepps/vscode,joaomoreno/vscode,stringham/vscode,mjbvz/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,KattMingMing/vscode,the-ress/vscode,microlv/vscode,hoovercj/vscode,hashhar/vscode,veeramarni/vscode,Krzysztof-Cieslak/vscode,radshit/vscode,hashhar/vscode,hoovercj/vscode,joaomoreno/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,Microsoft/vscode,Microsoft/vscode,hoovercj/vscode,0xmohit/vscode,veeramarni/vscode,DustinCampbell/vscode,rishii7/vscode,the-ress/vscode,hungys/vscode,stringham/vscode,hungys/vscode,microsoft/vscode,hoovercj/vscode,DustinCampbell/vscode,charlespierce/vscode,gagangupt16/vscode,KattMingMing/vscode,matthewshirley/vscode,microsoft/vscode,gagangupt16/vscode,radshit/vscode,cleidigh/vscode,cra0zy/VSCode,Microsoft/vscode,DustinCampbell/vscode,0xmohit/vscode,DustinCampbell/vscode,Microsoft/vscode,microlv/vscode,matthewshirley/vscode,matthewshirley/vscode,Krzysztof-Cieslak/vscode,stringham/vscode,radshit/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,cleidigh/vscode,eamodio/vscode,cleidigh/vscode,Krzysztof-Cieslak/vscode,rishii7/vscode,0xmohit/vscode,landonepps/vscode,radshit/vscode,rkeithhill/VSCode,charlespierce/vscode,Microsoft/vscode,gagangupt16/vscode,landonepps/vscode,Zalastax/vscode,0xmohit/vscode,KattMingMing/vscode,radshit/vscode,the-ress/vscode,eamodio/vscode,eamodio/vscode,eamodio/vscode,Zalastax/vscode,zyml/vscode,cleidigh/vscode,rishii7/vscode,stringham/vscode,Microsoft/vscode,veeramarni/vscode,Zalastax/vscode,microsoft/vscode,jchadwick/vscode,Zalastax/vscode,microsoft/vscode,gagangupt16/vscode,cleidigh/vscode,microlv/vscode,landonepps/vscode,jchadwick/vscode,zyml/vscode,hashhar/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,radshit/vscode,joaomoreno/vscode,Zalastax/vscode,matthewshirley/vscode,matthewshirley/vscode,microlv/vscode,veeramarni/vscode,veeramarni/vscode,0xmohit/vscode,hungys/vscode,Microsoft/vscode,KattMingMing/vscode,hungys/vscode,Zalastax/vscode,stringham/vscode,matthewshirley/vscode,landonepps/vscode,mjbvz/vscode,rishii7/vscode,zyml/vscode,stringham/vscode,hungys/vscode,hungys/vscode,gagangupt16/vscode,DustinCampbell/vscode,mjbvz/vscode,charlespierce/vscode,Krzysztof-Cieslak/vscode,hashhar/vscode,Zalastax/vscode,Zalastax/vscode,microsoft/vscode,microsoft/vscode,jchadwick/vscode,zyml/vscode,hashhar/vscode,KattMingMing/vscode,microsoft/vscode,microsoft/vscode,matthewshirley/vscode,KattMingMing/vscode,eamodio/vscode,mjbvz/vscode,matthewshirley/vscode,matthewshirley/vscode,jchadwick/vscode,gagangupt16/vscode,radshit/vscode,radshit/vscode,DustinCampbell/vscode,charlespierce/vscode,stringham/vscode,Krzysztof-Cieslak/vscode,Zalastax/vscode,rishii7/vscode,joaomoreno/vscode,hashhar/vscode,charlespierce/vscode,hungys/vscode,hoovercj/vscode,Microsoft/vscode,rishii7/vscode,hungys/vscode,zyml/vscode | ---
+++
@@ -14,7 +14,7 @@
properties: {
recommendations: {
type: 'array',
- description: localize('app.extensions.json.recommendations', "List of extension recommendations."),
+ description: localize('app.extensions.json.recommendations', "List of extensions recommendations. The identifier of an extension is always ${publisher}.${name}. For example: vscode.csharp."),
items: {
'type': 'string',
} |
a35d30eaf018b09fdd5b93fc1920c80c43192bb6 | frontend/maybe_load_app_signal.ts | frontend/maybe_load_app_signal.ts | export async function maybeLoadAppSignal() {
const token = globalConfig["APPSIGNAL_TOKEN"];
if (window.appSignal) {
console.log("Already have appSignal loaded.");
return;
}
if (token) {
console.log("Load appsignal");
const AppSignal = (await import("@appsignal/javascript")).default;
console.log("Load window events plugin");
const { plugin } = await import("@appsignal/plugin-window-events");
console.log("instantiate appsignal");
const as = new AppSignal({
key: "YOUR FRONTEND API KEY"
});
console.log("Use plugins");
as.use(plugin);
console.log("Make it global");
window.appSignal = as;
console.log("done");
} else {
console.log("No appsignal token detected.");
}
}
| export async function maybeLoadAppSignal() {
const token = globalConfig["APPSIGNAL_TOKEN"];
if (window.appSignal) {
console.log("Already have appSignal loaded.");
return;
}
if (token) {
const AppSignal = (await import("@appsignal/javascript")).default;
const { plugin } = await import("@appsignal/plugin-window-events");
const as = new AppSignal({
key: token,
revision: globalConfig["LONG_REVISION"]
});
as.use(plugin);
window.appSignal = as;
console.log("AppSignal loaded.");
} else {
console.log("No appsignal token detected.");
}
}
| Remove loggers, use real FE token | Remove loggers, use real FE token
| TypeScript | mit | gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App | ---
+++
@@ -7,19 +7,15 @@
}
if (token) {
- console.log("Load appsignal");
const AppSignal = (await import("@appsignal/javascript")).default;
- console.log("Load window events plugin");
const { plugin } = await import("@appsignal/plugin-window-events");
- console.log("instantiate appsignal");
const as = new AppSignal({
- key: "YOUR FRONTEND API KEY"
+ key: token,
+ revision: globalConfig["LONG_REVISION"]
});
- console.log("Use plugins");
as.use(plugin);
- console.log("Make it global");
window.appSignal = as;
- console.log("done");
+ console.log("AppSignal loaded.");
} else {
console.log("No appsignal token detected.");
} |
897a5ec79194507bbfb3343a93ae711123f1dc84 | lib/typescript/contact_property.ts | lib/typescript/contact_property.ts | import { RequestPromise } from 'request-promise'
declare class Properties {
get(): RequestPromise
getByName(name: string): RequestPromise
create(data: {}): RequestPromise
update(name: string, data: {}): RequestPromise
upsert(data: {}): RequestPromise
getGroups(): RequestPromise
createGroup(data: {}): void
updateGroup(name: string, data: {}): void
deleteGroup(name: string): void
delete(name: string): void
}
export { Properties }
| import { RequestPromise } from 'request-promise'
declare class Properties {
get(): RequestPromise
getByName(name: string): RequestPromise
create(data: {}): RequestPromise
update(name: string, data: {}): RequestPromise
upsert(data: {}): RequestPromise
getGroups(): RequestPromise
createGroup(data: {}): void
updateGroup(name: string, data: {}): void
deleteGroup(name: string): void
delete(name: string): RequestPromise
}
export { Properties }
| Change the delete response from void to RequestPromise | Change the delete response from void to RequestPromise
| TypeScript | mit | brainflake/node-hubspot,brainflake/node-hubspot | ---
+++
@@ -19,7 +19,7 @@
deleteGroup(name: string): void
- delete(name: string): void
+ delete(name: string): RequestPromise
}
export { Properties } |
46ab7d7c7852b43f64b1bacf04a99056c127e253 | src/promised.tsx | src/promised.tsx | import * as React from 'react';
import LinearProgress from 'material-ui/LinearProgress';
import Snackbar from 'material-ui/Snackbar';
interface PromisedState {
error?: Error;
loading: boolean;
value?: any;
}
// tslint:disable-next-line:only-arrow-functions
const Promised = function<T, ChildProps = {}>(propName: string, Wrapped: React.ComponentType<ChildProps>) {
interface WrapperProp {
promise: Promise<T>;
}
type PromisedProps = ChildProps & WrapperProp;
return class PromisedWrapper extends React.Component<PromisedProps, PromisedState> {
constructor(props: PromisedProps) {
super(props);
this.state = { loading: true };
}
componentWillMount() {
this.props.promise
.then(this.handleSuccess)
.catch(this.handleRejection);
}
render() {
const { error, loading, value } = this.state;
if (error) {
return <Snackbar message={ error.message } open={ !!error } />;
} else if (loading) {
return <LinearProgress />;
} else {
const childProps = { [propName]: value };
return <Wrapped { ...childProps } />;
}
}
private handleRejection = (error: Error) => {
this.setState({ error, loading: false });
}
private handleSuccess = (value: T) => {
this.setState({ loading: false, value });
}
};
};
export default Promised;
| import * as React from 'react';
import LinearProgress from 'material-ui/LinearProgress';
import Snackbar from 'material-ui/Snackbar';
interface PromisedState {
error?: Error;
loading: boolean;
value?: any;
}
// Inspired by http://natpryce.com/articles/000814.html
// tslint:disable-next-line:only-arrow-functions
const Promised = function<T, ChildProps = {}>(propName: string, Wrapped: React.ComponentType<ChildProps>) {
interface WrapperProp {
promise: Promise<T>;
}
type PromisedProps = ChildProps & WrapperProp;
return class PromisedWrapper extends React.Component<PromisedProps, PromisedState> {
constructor(props: PromisedProps) {
super(props);
this.state = { loading: true };
}
componentWillMount() {
this.props.promise
.then(this.handleSuccess)
.catch(this.handleRejection);
}
render() {
const { error, loading, value } = this.state;
if (error) {
return <Snackbar message={ error.message } open={ !!error } />;
} else if (loading) {
return <LinearProgress />;
} else {
const childProps = { [propName]: value };
return <Wrapped { ...childProps } />;
}
}
private handleRejection = (error: Error) => {
this.setState({ error, loading: false });
}
private handleSuccess = (value: T) => {
this.setState({ loading: false, value });
}
};
};
export default Promised;
| Add reference to inspiring blog post | Add reference to inspiring blog post
| TypeScript | mit | mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web | ---
+++
@@ -8,6 +8,8 @@
loading: boolean;
value?: any;
}
+
+// Inspired by http://natpryce.com/articles/000814.html
// tslint:disable-next-line:only-arrow-functions
const Promised = function<T, ChildProps = {}>(propName: string, Wrapped: React.ComponentType<ChildProps>) { |
b351af4e1c28c8e7021f107c5dca1c96be55331b | src/index.ts | src/index.ts | import { SandboxParameter } from './interfaces';
import nativeAddon from './nativeAddon';
import { SandboxProcess } from './sandboxProcess';
import { existsSync } from 'fs';
import * as randomString from 'randomstring';
import * as path from 'path';
export * from './interfaces';
if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) {
throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme.");
}
export function startSandbox(parameter: SandboxParameter): SandboxProcess {
const actualParameter = Object.assign({}, parameter);
actualParameter.cgroup = path.join(actualParameter.cgroup, randomString.generate(9));
const startResult: { pid: number; execParam: ArrayBuffer } = nativeAddon.startSandbox(actualParameter);
return new SandboxProcess(parameter, startResult.pid, startResult.execParam);
};
| import { SandboxParameter } from './interfaces';
import nativeAddon from './nativeAddon';
import { SandboxProcess } from './sandboxProcess';
import { existsSync } from 'fs';
import * as randomString from 'randomstring';
import * as path from 'path';
export * from './interfaces';
if (!existsSync('/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes')) {
throw new Error("Your linux kernel doesn't support memory-swap account. Please turn it on following the readme.");
}
export function startSandbox(parameter: SandboxParameter): SandboxProcess {
const actualParameter = Object.assign({}, parameter);
actualParameter.cgroup = path.join(actualParameter.cgroup, randomString.generate(9));
const startResult: { pid: number; execParam: ArrayBuffer } = nativeAddon.startSandbox(actualParameter);
return new SandboxProcess(actualParameter, startResult.pid, startResult.execParam);
};
| Fix cgroup not deleted after sandbox finished | Fix cgroup not deleted after sandbox finished
| TypeScript | mit | t123yh/simple-sandbox,t123yh/simple-sandbox | ---
+++
@@ -15,6 +15,6 @@
const actualParameter = Object.assign({}, parameter);
actualParameter.cgroup = path.join(actualParameter.cgroup, randomString.generate(9));
const startResult: { pid: number; execParam: ArrayBuffer } = nativeAddon.startSandbox(actualParameter);
- return new SandboxProcess(parameter, startResult.pid, startResult.execParam);
+ return new SandboxProcess(actualParameter, startResult.pid, startResult.execParam);
};
|
523336f8b190b11416fab41c54607348c9491770 | src/index.ts | src/index.ts | import {
middleware,
Middleware as GenericMiddleware
} from '@pawelgalazka/middleware'
import { useMiddlewares } from './middlewares'
export { useMiddlewares } from './middlewares'
export { help, withHelp } from './middlewares/helper'
export { rawArgs } from './middlewares/rawArgsParser'
export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any
export type CLIParams = string[]
export type CommandsModule = ICommandsDictionary | CommandFunction
export type Middleware = GenericMiddleware<IMiddlewareArguments>
export interface ICLIOptions {
[key: string]: number | string | boolean
}
export interface ICommandsDictionary {
[namespace: string]: CommandsModule
}
export interface IMiddlewareArguments {
options: ICLIOptions
params: CLIParams
definition: CommandsModule
namespace: string
command: CommandFunction
reject: (error: Error) => void
}
export class CLIError extends Error {}
export function cli(
definition: CommandsModule,
middlewares: Middleware[] = useMiddlewares()
) {
middleware<IMiddlewareArguments>(middlewares)({
command: () => null,
definition,
namespace: '',
options: {},
params: [],
reject: error => {
throw error
}
})
}
| import {
middleware,
Middleware as GenericMiddleware
} from '@pawelgalazka/middleware'
import { useMiddlewares } from './middlewares'
export { useMiddlewares } from './middlewares'
export { help, withHelp } from './middlewares/helper'
export { rawArgs } from './middlewares/rawArgsParser'
export type CommandFunction = (options: ICLIOptions, ...args: any[]) => any
export type CLIParams = string[]
export type CommandsModule = ICommandsDictionary | CommandFunction
export type Middleware = GenericMiddleware<IMiddlewareArguments>
export interface ICLIOptions {
[key: string]: number | string | boolean
}
export interface ICommandsDictionary {
[namespace: string]: CommandsModule
}
export interface IMiddlewareArguments {
options: ICLIOptions
params: CLIParams
definition: CommandsModule
namespace: string
command?: CommandFunction
reject: (error: Error) => void
}
export class CLIError extends Error {}
export function cli(
definition: CommandsModule,
middlewares: Middleware[] = useMiddlewares()
) {
middleware<IMiddlewareArguments>(middlewares)({
definition,
namespace: '',
options: {},
params: [],
reject: error => {
throw error
}
})
}
| Make command optional for IMiddlewareArguments | Make command optional for IMiddlewareArguments
| TypeScript | mit | pawelgalazka/microcli,pawelgalazka/microcli | ---
+++
@@ -26,7 +26,7 @@
params: CLIParams
definition: CommandsModule
namespace: string
- command: CommandFunction
+ command?: CommandFunction
reject: (error: Error) => void
}
@@ -37,7 +37,6 @@
middlewares: Middleware[] = useMiddlewares()
) {
middleware<IMiddlewareArguments>(middlewares)({
- command: () => null,
definition,
namespace: '',
options: {}, |
74f1191e4e3f5e1a55e011f703c13a287ce9fa74 | src/index.ts | src/index.ts |
import {PropertyType} from "./model/property-type";
import {ModelOptions, ProcessMode} from "./model/options";
import {ValidateResult} from "./manager/validate";
import {model} from "./model/model";
import {type} from "./decorator/type";
import {length} from "./decorator/length";
import {range} from "./decorator/range";
import {manager} from "./manager/manager";
function options(options: ModelOptions) {
manager.setGlobalOptions(options);
}
function validate(model: Object): boolean;
function validate(model: Object, result: ValidateResult);
function validate(model: Object, result?: ValidateResult) {
let error = manager.validate(model);
if (!result) {
return error == null;
} else {
result(error);
}
}
export {
PropertyType, ProcessMode,
model, options, validate,
type, length, range
} |
import {PropertyType} from "./model/property-type";
import {ModelOptions, ProcessMode} from "./model/options";
import {ValidateResult} from "./manager/validate";
import {model} from "./model/model";
import {type} from "./decorator/type";
import {length} from "./decorator/length";
import {range} from "./decorator/range";
import {manager} from "./manager/manager";
function options(options: ModelOptions) {
manager.setGlobalOptions(options);
}
function validate(model: Object): boolean;
function validate(model: Object, result: ValidateResult);
function validate(models: Object[]): boolean;
function validate(models: Object[], result: ValidateResult);
function validate(modelOrArray: Object[], resultOrNull?: ValidateResult) {
let models: Object[];
if (Array.isArray(modelOrArray)) {
models = modelOrArray;
} else {
models = [modelOrArray];
}
for (let model of models) {
let error = manager.validate(model);
if (error != null) {
if (!resultOrNull) {
return false;
} else {
resultOrNull(error);
return;
}
}
}
if (!resultOrNull) {
return true;
} else {
resultOrNull(null);
}
}
export {
PropertyType, ProcessMode,
model, options, validate,
type, length, range
} | Validate accepts an array of models | Validate accepts an array of models
| TypeScript | mit | Cytren/DecorativeModels,Cytren/DecorativeModels | ---
+++
@@ -15,14 +15,35 @@
function validate(model: Object): boolean;
function validate(model: Object, result: ValidateResult);
+function validate(models: Object[]): boolean;
+function validate(models: Object[], result: ValidateResult);
-function validate(model: Object, result?: ValidateResult) {
- let error = manager.validate(model);
+function validate(modelOrArray: Object[], resultOrNull?: ValidateResult) {
+ let models: Object[];
- if (!result) {
- return error == null;
+ if (Array.isArray(modelOrArray)) {
+ models = modelOrArray;
} else {
- result(error);
+ models = [modelOrArray];
+ }
+
+ for (let model of models) {
+ let error = manager.validate(model);
+
+ if (error != null) {
+ if (!resultOrNull) {
+ return false;
+ } else {
+ resultOrNull(error);
+ return;
+ }
+ }
+ }
+
+ if (!resultOrNull) {
+ return true;
+ } else {
+ resultOrNull(null);
}
}
|
eb623dfb1c3432b4cc543b7dbfb66839d0b620cf | src/utils.ts | src/utils.ts | "use strict";
import * as path from "path";
import * as fs from "fs";
import { workspace } from "vscode";
export const dartVMPath = "bin/dart";
export const analyzerPath = "bin/snapshots/analysis_server.dart.snapshot";
const configExtensionName = "dart";
const configSdkPathName = "sdkPath";
const configSetIndentName = "setIndentSettings";
let config = workspace.getConfiguration(configExtensionName);
export function findDartSdk(): string {
let paths = (<string>process.env.PATH).split(";");
// We don't expect the user to add .\bin in config, but it would be in the PATHs
if (config.has(configSdkPathName))
paths.unshift(path.join(config.get<string>(configSdkPathName), 'bin'));
let sdkPath = paths.find(isValidDartSdk);
if (sdkPath)
return path.join(sdkPath, ".."); // Take .\bin back off.
return null;
}
function isValidDartSdk(pathToTest: string): boolean {
// Apparently this is the "correct" way to check files exist synchronously in Node :'(
try {
fs.accessSync(path.join(pathToTest, "..", analyzerPath), fs.R_OK);
return true; // If no error, we found a match!
}
catch (e) { }
return false; // Didn't find it, so must be an invalid path.
}
| "use strict";
import * as path from "path";
import * as fs from "fs";
import { workspace } from "vscode";
export const dartVMPath = "bin/dart";
export const analyzerPath = "bin/snapshots/analysis_server.dart.snapshot";
const configExtensionName = "dart";
const configSdkPathName = "sdkPath";
const configSetIndentName = "setIndentSettings";
let config = workspace.getConfiguration(configExtensionName);
export function findDartSdk(): string {
let paths = (<string>process.env.PATH).split(path.delimiter);
// We don't expect the user to add .\bin in config, but it would be in the PATHs
if (config.has(configSdkPathName))
paths.unshift(path.join(config.get<string>(configSdkPathName), 'bin'));
let sdkPath = paths.find(isValidDartSdk);
if (sdkPath)
return path.join(sdkPath, ".."); // Take .\bin back off.
return null;
}
function isValidDartSdk(pathToTest: string): boolean {
// Apparently this is the "correct" way to check files exist synchronously in Node :'(
try {
fs.accessSync(path.join(pathToTest, "..", analyzerPath), fs.R_OK);
return true; // If no error, we found a match!
}
catch (e) { }
return false; // Didn't find it, so must be an invalid path.
}
| Use platform-specific path delimiter when parsing PATH. | Use platform-specific path delimiter when parsing PATH.
#17
| TypeScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -13,7 +13,7 @@
let config = workspace.getConfiguration(configExtensionName);
export function findDartSdk(): string {
- let paths = (<string>process.env.PATH).split(";");
+ let paths = (<string>process.env.PATH).split(path.delimiter);
// We don't expect the user to add .\bin in config, but it would be in the PATHs
if (config.has(configSdkPathName)) |
899161a67c6a57d4cf13fd9d7a1e754566d51ec0 | src/index.ts | src/index.ts | export default {
isValid(bic: string): boolean {
const bicRegex = /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/;
return bicRegex.test(bic);
},
};
| const BIC_REGEX = /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/;
export default {
isValid(bic: string): boolean {
return BIC_REGEX.test(bic);
},
};
| Move the regex definition outside of the function | Move the regex definition outside of the function
| TypeScript | mit | nicolaspayot/bic,nicolaspayot/bic | ---
+++
@@ -1,7 +1,7 @@
+const BIC_REGEX = /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/;
+
export default {
isValid(bic: string): boolean {
- const bicRegex = /^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$/;
-
- return bicRegex.test(bic);
+ return BIC_REGEX.test(bic);
},
}; |
2e810944a7394cf3b9870ffe056be0d97b7c2157 | src/index.ts | src/index.ts | import { app, BrowserWindow, webContents, shell } from "electron";
import { ThemeCompiler } from "./theme-compiler";
let win;
function createWindow() {
ThemeCompiler.existsDefaultTheme()
.then(ThemeCompiler.loadThemes)
.then(ThemeCompiler.compileThemes)
.then(() => {
win = new BrowserWindow({ width: 800, height: 600, minWidth: 650, minHeight: 500, icon: `${__dirname}/app/img/icon.png` });
win.loadURL(`${__dirname}/app/view/index.html`);
win.on("closed", () => {
win = null;
});
webContents.getFocusedWebContents().on("will-navigate", handleRedirect);
})
.catch(err => {
console.error("Error while compiling themes.", err);
process.exit(1);
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church
});
app.on("activate", () => {
win === null && createWindow(); // Code like if you were in Satan's church
});
function handleRedirect(e, url) {
if (url != webContents.getFocusedWebContents().getURL()) {
e.preventDefault();
shell.openExternal(url);
}
}
| import { app, BrowserWindow, webContents, shell } from "electron";
import { ThemeCompiler } from "./theme-compiler";
let win;
function createWindow() {
ThemeCompiler.existsDefaultTheme()
.then(ThemeCompiler.loadThemes)
.then(ThemeCompiler.compileThemes)
.then(() => {
win = new BrowserWindow({ width: 800, height: 600, minWidth: 650, minHeight: 500, icon: `${__dirname}/app/img/icon.png` });
win.loadURL(`${__dirname}/app/view/index.html`);
win.on("closed", () => {
win = null;
});
webContents.getFocusedWebContents().on("will-navigate", handleRedirect);
})
.catch(err => {
console.error("Error while compiling themes.", err);
process.exit(1);
});
}
app.on("ready", createWindow);
app.on("window-all-closed", () => {
process.platform !== "darwin" && app.quit(); // Code like if you were in Satan's church
});
app.on("activate", () => {
win === null && createWindow(); // Code like if you were in Satan's church
});
function handleRedirect(event: Event, url: string) {
if (url === webContents.getFocusedWebContents().getURL()) return;
event.preventDefault();
shell.openExternal(url);
}
| Make a function more lisible | Make a function more lisible
| TypeScript | mit | Xstoudi/alduin,Xstoudi/alduin,Xstoudi/alduin | ---
+++
@@ -35,9 +35,9 @@
win === null && createWindow(); // Code like if you were in Satan's church
});
-function handleRedirect(e, url) {
- if (url != webContents.getFocusedWebContents().getURL()) {
- e.preventDefault();
- shell.openExternal(url);
- }
+function handleRedirect(event: Event, url: string) {
+ if (url === webContents.getFocusedWebContents().getURL()) return;
+
+ event.preventDefault();
+ shell.openExternal(url);
} |
020fca21c11d8424905b5b21f440d45a8d5dc08d | src/index.ts | src/index.ts | /**
* @file The primary entry for Innerface.
*
* @author Justin Toon
* @license MIT
*/
import * as _ from 'lodash';
import { selectors } from './if.const';
import * as controllers from './controllers';
/**
* A system of simple UI actions implemented with an HTML API.
*
* @since 0.1.0
*/
export default class Innerface {
/**
* Initialize the library.
*/
public static init() {
_.forEach(controllers, (controller, index) => {
controller().initialize();
});
}
}
| /**
* @file The primary entry for Innerface.
*
* @author Justin Toon
* @license MIT
*/
import * as _ from 'lodash';
import { selectors } from './if.const';
import * as controllers from './controllers';
/**
* A system of simple UI actions implemented with an HTML API.
*
* @since 0.1.0
*/
export default class Innerface {
/**
* Initialize the library.
*/
public static init() {
_.forEach(controllers, (controller: Innerface.Controller, key: string) => {
controller.initialize();
});
}
}
| Add typing; fix initialization call | Add typing; fix initialization call
| TypeScript | mit | overneath42/innerface,overneath42/innerface | ---
+++
@@ -20,8 +20,8 @@
* Initialize the library.
*/
public static init() {
- _.forEach(controllers, (controller, index) => {
- controller().initialize();
+ _.forEach(controllers, (controller: Innerface.Controller, key: string) => {
+ controller.initialize();
});
}
} |
b3f48d9811a8afab41e150a1eeebe9fdb95e20b1 | src/universal.ts | src/universal.ts | import { Request } from 'servie'
import {
HttpResponse,
request as nodeRequest,
RequestOptions as NodeRequestOptions,
transport as nodeTransport,
TransportOptions as NodeTransportOptions
} from './node'
import {
XhrResponse,
RequestOptions as BrowserRequestOptions,
TransportOptions as BrowserTransportOptions
} from './browser'
export type SendFn = (req: Request) => Promise<HttpResponse | XhrResponse>
export type TransportFn = (options?: NodeTransportOptions & BrowserTransportOptions) => SendFn
export type RequestFn = (url: string, options: NodeRequestOptions & BrowserRequestOptions) => Request
export const request: RequestFn = nodeRequest
export const transport: TransportFn = nodeTransport
| import { Request } from 'servie'
import {
HttpResponse,
request as nodeRequest,
RequestOptions as NodeRequestOptions,
transport as nodeTransport,
TransportOptions as NodeTransportOptions
} from './node'
import {
XhrResponse,
RequestOptions as BrowserRequestOptions,
TransportOptions as BrowserTransportOptions
} from './browser'
export type SendFn = (req: Request) => Promise<HttpResponse | XhrResponse>
export type TransportFn = (options?: NodeTransportOptions & BrowserTransportOptions) => SendFn
export type RequestFn = (url: string, options?: NodeRequestOptions & BrowserRequestOptions) => Request
export const request: RequestFn = nodeRequest
export const transport: TransportFn = nodeTransport
export const send = transport()
| Add default transport `send` and optional req opts | Add default transport `send` and optional req opts
| TypeScript | mit | blakeembrey/popsicle,blakeembrey/popsicle | ---
+++
@@ -15,7 +15,8 @@
export type SendFn = (req: Request) => Promise<HttpResponse | XhrResponse>
export type TransportFn = (options?: NodeTransportOptions & BrowserTransportOptions) => SendFn
-export type RequestFn = (url: string, options: NodeRequestOptions & BrowserRequestOptions) => Request
+export type RequestFn = (url: string, options?: NodeRequestOptions & BrowserRequestOptions) => Request
export const request: RequestFn = nodeRequest
export const transport: TransportFn = nodeTransport
+export const send = transport() |
11b38ef20f7f7841a6b2d348008b8fa073974d68 | src/cmds/dev/sync-watch.cmd.ts | src/cmds/dev/sync-watch.cmd.ts | import {
constants,
fs,
fsPath,
log,
printTitle,
deps,
} from '../../common';
import * as chokidar from 'chokidar';
import * as syncLibs from './sync-libs.cmd';
export const group = 'dev';
export const name = 'sync:watch';
export const alias = 'sw';
export const description = 'Auto syncs when module files change.';
const PATTERN = '/lib/**/*.js';
export async function cmd(
args?: {
params: string[],
options: {},
},
) {
printTitle('Sync on change');
const modules = constants
.MODULE_DIRS
.toPackageObjects()
.filter((pkg) => fs.existsSync(fsPath.join(pkg.path, 'tsconfig.json')));
modules.forEach((pkg) => {
log.info.blue(` - ${log.magenta(pkg.name)}${log.gray(PATTERN)}`);
watch(pkg);
});
log.info();
}
function watch(pkg: constants.IPackageObject) {
const sync = () => {
const pkgs = deps.dependsOn(pkg);
if (pkgs.length > 0) {
syncLibs.cmd({
params: pkgs.map((pkg) => pkg.name),
options: {},
});
}
};
chokidar
.watch(`${pkg.path}${PATTERN}`)
.on('change', (path) => sync());
}
| import {
constants,
fs,
fsPath,
log,
printTitle,
deps,
} from '../../common';
import * as chokidar from 'chokidar';
import * as syncLibs from './sync-libs.cmd';
export const group = 'dev';
export const name = 'sync:watch';
export const alias = 'sw';
export const description = 'Auto syncs when module files change.';
const PATTERN = '/lib/**/*.{js,ts}';
export async function cmd(
args?: {
params: string[],
options: {},
},
) {
printTitle('Sync on change');
const modules = constants
.MODULE_DIRS
.toPackageObjects()
.filter((pkg) => fs.existsSync(fsPath.join(pkg.path, 'tsconfig.json')));
modules.forEach((pkg) => {
log.info.blue(` - ${log.magenta(pkg.name)}${log.gray(PATTERN)}`);
watch(pkg);
});
log.info();
}
function watch(pkg: constants.IPackageObject) {
const sync = () => {
const pkgs = deps.dependsOn(pkg);
if (pkgs.length > 0) {
syncLibs.cmd({
params: pkgs.map((pkg) => pkg.name),
options: {},
});
}
};
chokidar
.watch(`${pkg.path}${PATTERN}`)
.on('change', (path) => sync());
}
| Make sync listen to typescript file changes | Make sync listen to typescript file changes
| TypeScript | mit | frederickfogerty/js-cli,frederickfogerty/js-cli,frederickfogerty/js-cli | ---
+++
@@ -16,7 +16,7 @@
export const description = 'Auto syncs when module files change.';
-const PATTERN = '/lib/**/*.js';
+const PATTERN = '/lib/**/*.{js,ts}';
export async function cmd(
args?: { |
e47a787082eb3d9911933d229a3ac7c3ced59edc | CeraonUI/src/Components/AppHost.tsx | CeraonUI/src/Components/AppHost.tsx | import * as React from 'react';
export default class AppHost extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
React.Children.only(this.props.children)
);
}
}
| import * as React from 'react';
export default class AppHost extends React.Component<any, any> {
constructor() {
super();
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
| Expand apphost to support multiple components | Expand apphost to support multiple components
| TypeScript | bsd-3-clause | Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound,Rdbaker/Mealbound | ---
+++
@@ -7,7 +7,9 @@
render() {
return (
- React.Children.only(this.props.children)
+ <div>
+ {this.props.children}
+ </div>
);
}
} |
07201fbb48dfecd35d2bca1bbf1befea177e15fb | src/octicon.tsx | src/octicon.tsx | import * as React from 'react'
interface OcticonProps {
width?: number,
height?: number,
symbol: string
}
export default class Octicon extends React.Component<OcticonProps, void> {
public static defaultProps: OcticonProps = { width: 16, height: 16, symbol: "" };
public constructor(props: OcticonProps) {
super(props)
}
public render() {
return (
<svg aria-hidden="true" class="octicon" width="12" height="16" role="img" version="1.1" viewBox="0 0 12 16">
<path d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"></path>
</svg>
)
}
}
| import * as React from 'react'
import {OcticonSymbol} from './octicons.generated'
export {OcticonSymbol as OcticonSymbol};
interface OcticonProps {
width?: number,
height?: number,
symbol: OcticonSymbol
}
export class Octicon extends React.Component<OcticonProps, void> {
public static defaultProps: OcticonProps = { width: 16, height: 16, symbol: OcticonSymbol.mark_github };
public constructor(props: OcticonProps) {
super(props)
}
public render() {
const symbol = this.props.symbol;
const viewBox = `0 0 ${symbol.w} ${symbol.h}`
return (
<svg aria-hidden="true" className="octicon" width={this.props.width} height={this.props.height} role="img" version="1.1" viewBox={viewBox}>
<path d={symbol.d}></path>
</svg>
)
}
}
| Use the new OcticonSymbol type for the component | Use the new OcticonSymbol type for the component
| TypeScript | mit | say25/desktop,kactus-io/kactus,desktop/desktop,say25/desktop,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,desktop/desktop,BugTesterTest/desktops,hjobrien/desktop,desktop/desktop,kactus-io/kactus,gengjiawen/desktop,kactus-io/kactus,artivilla/desktop,BugTesterTest/desktops,shiftkey/desktop,desktop/desktop,say25/desktop,gengjiawen/desktop,BugTesterTest/desktops,say25/desktop,artivilla/desktop,kactus-io/kactus,shiftkey/desktop,BugTesterTest/desktops,gengjiawen/desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,j-f1/forked-desktop,gengjiawen/desktop,hjobrien/desktop,hjobrien/desktop,hjobrien/desktop | ---
+++
@@ -1,23 +1,28 @@
import * as React from 'react'
+import {OcticonSymbol} from './octicons.generated'
+
+export {OcticonSymbol as OcticonSymbol};
interface OcticonProps {
width?: number,
height?: number,
- symbol: string
+ symbol: OcticonSymbol
}
-export default class Octicon extends React.Component<OcticonProps, void> {
+export class Octicon extends React.Component<OcticonProps, void> {
- public static defaultProps: OcticonProps = { width: 16, height: 16, symbol: "" };
+ public static defaultProps: OcticonProps = { width: 16, height: 16, symbol: OcticonSymbol.mark_github };
public constructor(props: OcticonProps) {
super(props)
}
public render() {
+ const symbol = this.props.symbol;
+ const viewBox = `0 0 ${symbol.w} ${symbol.h}`
return (
- <svg aria-hidden="true" class="octicon" width="12" height="16" role="img" version="1.1" viewBox="0 0 12 16">
- <path d="M12 9H7v5H5V9H0V7h5V2h2v5h5v2z"></path>
+ <svg aria-hidden="true" className="octicon" width={this.props.width} height={this.props.height} role="img" version="1.1" viewBox={viewBox}>
+ <path d={symbol.d}></path>
</svg>
)
} |
b5934738c711796667c0a7d9996e9174c6aea105 | applications/calendar/src/app/components/onboarding/CalendarOnboardingModal.tsx | applications/calendar/src/app/components/onboarding/CalendarOnboardingModal.tsx | import { c } from 'ttag';
import {
OnboardingContent,
OnboardingModal,
OnboardingStep,
OnboardingStepRenderCallback,
useSettingsLink,
} from '@proton/components';
import { APPS } from '@proton/shared/lib/constants';
import { CALENDAR_APP_NAME } from '@proton/shared/lib/calendar/constants';
import onboardingWelcome from '@proton/styles/assets/img/onboarding/calendar-welcome.svg';
const CalendarOnboardingModal = (props: any) => {
const goToSettings = useSettingsLink();
const appName = CALENDAR_APP_NAME;
return (
<OnboardingModal {...props}>
{({ onNext }: OnboardingStepRenderCallback) => {
return (
<OnboardingStep
submit={c(`Onboarding ProtonCalendar`).t`Import events`}
onSubmit={() => {
goToSettings('/calendars#import', APPS.PROTONCALENDAR, true);
onNext?.();
}}
close={c(`Onboarding ProtonCalendar`).t`Start using ${appName}`}
onClose={onNext}
>
<OnboardingContent
title={c(`Onboarding ProtonCalendar`).t`Meet your new encrypted calendar`}
description={c(`Onboarding ProtonCalendar`)
.t`A calendar is a record of your life. Keep your life secure and private with ${appName}.`}
img={<img src={onboardingWelcome} alt={appName} />}
/>
</OnboardingStep>
);
}}
</OnboardingModal>
);
};
export default CalendarOnboardingModal;
| import { c } from 'ttag';
import {
OnboardingContent,
OnboardingModal,
OnboardingStep,
OnboardingStepRenderCallback,
useSettingsLink,
} from '@proton/components';
import { APPS } from '@proton/shared/lib/constants';
import { CALENDAR_APP_NAME } from '@proton/shared/lib/calendar/constants';
import onboardingWelcome from '@proton/styles/assets/img/onboarding/calendar-welcome.svg';
const CalendarOnboardingModal = (props: any) => {
const goToSettings = useSettingsLink();
const appName = CALENDAR_APP_NAME;
return (
<OnboardingModal {...props}>
{({ onNext }: OnboardingStepRenderCallback) => {
return (
<OnboardingStep
submit={c('Onboarding ProtonCalendar').t`Import events`}
onSubmit={() => {
goToSettings('/calendars#import', APPS.PROTONCALENDAR, true);
onNext?.();
}}
close={c('Onboarding ProtonCalendar').t`Start using ${appName}`}
onClose={onNext}
>
<OnboardingContent
title={c('Onboarding ProtonCalendar').t`Meet your new encrypted calendar`}
description={c('Onboarding ProtonCalendar')
.t`A calendar is a record of your life. Keep your life secure and private with ${appName}.`}
img={<img src={onboardingWelcome} alt={appName} />}
/>
</OnboardingStep>
);
}}
</OnboardingModal>
);
};
export default CalendarOnboardingModal;
| Fix backticks inside context string | Fix backticks inside context string
ttag cli is unable to find these strings
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -19,17 +19,17 @@
{({ onNext }: OnboardingStepRenderCallback) => {
return (
<OnboardingStep
- submit={c(`Onboarding ProtonCalendar`).t`Import events`}
+ submit={c('Onboarding ProtonCalendar').t`Import events`}
onSubmit={() => {
goToSettings('/calendars#import', APPS.PROTONCALENDAR, true);
onNext?.();
}}
- close={c(`Onboarding ProtonCalendar`).t`Start using ${appName}`}
+ close={c('Onboarding ProtonCalendar').t`Start using ${appName}`}
onClose={onNext}
>
<OnboardingContent
- title={c(`Onboarding ProtonCalendar`).t`Meet your new encrypted calendar`}
- description={c(`Onboarding ProtonCalendar`)
+ title={c('Onboarding ProtonCalendar').t`Meet your new encrypted calendar`}
+ description={c('Onboarding ProtonCalendar')
.t`A calendar is a record of your life. Keep your life secure and private with ${appName}.`}
img={<img src={onboardingWelcome} alt={appName} />}
/> |
d75938d355d5f98a0c79140085fa1709a7fb18cb | angular-src/src/app/components/loggedin-wrapper/content/admin/admin.component.ts | angular-src/src/app/components/loggedin-wrapper/content/admin/admin.component.ts | import { Component, OnInit } from '@angular/core';
import { UserService } from '../../../../services/user.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
users: any;
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getAllUsers().subscribe(
data => {
localStorage.setItem('users', JSON.stringify(data));
});
this.users = JSON.parse(localStorage.getItem('users'));
}
}
| import { Component, OnInit } from '@angular/core';
import { UserService } from '../../../../services/user.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
users: any;
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getAllUsers().subscribe(
data => {
localStorage.setItem('users', JSON.stringify(data));
this.users = JSON.parse(localStorage.getItem('users'));
});
this.users = JSON.parse(localStorage.getItem('users'));
}
}
| Fix offline admin panel access issue | Fix offline admin panel access issue
| TypeScript | mit | karlveskus/moodlebox,karlveskus/moodlebox,karlveskus/moodlebox | ---
+++
@@ -15,6 +15,7 @@
this.userService.getAllUsers().subscribe(
data => {
localStorage.setItem('users', JSON.stringify(data));
+ this.users = JSON.parse(localStorage.getItem('users'));
});
this.users = JSON.parse(localStorage.getItem('users')); |
0443f10ecc21ad16d2a9fda34434e8203f5c58f5 | ui/src/index.tsx | ui/src/index.tsx | import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import Modal from 'react-modal';
import App from './App';
import './buttons.css';
import i18n from './i18n/i18n';
import Field from './idai_field/Field';
import Shapes from './idai_shapes/Shapes';
import './index.css';
Modal.setAppElement('#root');
const getSubdomain = (): string => {
const levels = window.location.host.split('.');
if (levels.length >= 3) return levels[0];
else return null;
};
// Run only shapes or field if subdomain is set, otherwise App wraps both
const subdomain = getSubdomain();
const app = (subdomain === 'shapes')
? <Shapes />
: (subdomain === 'field')
? <Field />
: <App />;
ReactDOM.render(
<I18nextProvider i18n={ i18n }>
{ app }
</I18nextProvider>,
document.getElementById('root')
);
| import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import Modal from 'react-modal';
import './buttons.css';
import i18n from './i18n/i18n';
import Field from './idai_field/Field';
import Shapes from './idai_shapes/Shapes';
import './index.css';
Modal.setAppElement('#root');
const getSubdomain = (): string => {
const levels = window.location.host.split('.');
if (levels.length >= 3) return levels[0];
else return null;
};
// Run only shapes or field if subdomain is set, otherwise App wraps both
const subdomain = getSubdomain();
const app = (subdomain === 'shapes' || process.env.REACT_APP_MAIN === 'shapes')
? <Shapes />
: <Field />;
ReactDOM.render(
<I18nextProvider i18n={ i18n }>
{ app }
</I18nextProvider>,
document.getElementById('root')
);
| Read main component from env for dev environment | Read main component from env for dev environment
| TypeScript | apache-2.0 | dainst/idai-field-web,dainst/idai-field-web,dainst/idai-field-web | ---
+++
@@ -3,7 +3,6 @@
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import Modal from 'react-modal';
-import App from './App';
import './buttons.css';
import i18n from './i18n/i18n';
import Field from './idai_field/Field';
@@ -24,11 +23,9 @@
// Run only shapes or field if subdomain is set, otherwise App wraps both
const subdomain = getSubdomain();
-const app = (subdomain === 'shapes')
+const app = (subdomain === 'shapes' || process.env.REACT_APP_MAIN === 'shapes')
? <Shapes />
- : (subdomain === 'field')
- ? <Field />
- : <App />;
+ : <Field />;
ReactDOM.render(
<I18nextProvider i18n={ i18n }> |
426e59d8ba35c6fb7cb4ae31aa3bcbd3cda6cec5 | src/picturepark-sdk-v1-angular/src/tests/config.template.ts | src/picturepark-sdk-v1-angular/src/tests/config.template.ts | import { HttpClientModule } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import {
PICTUREPARK_API_URL,
PICTUREPARK_CONFIGURATION,
PictureparkConfiguration,
AuthService,
AccessTokenAuthService
} from '@picturepark/sdk-v1-angular';
export const testUrl = '{Server}';
export const testAccessToken = '{AccessToken}';
export const testCustomerAlias = '{CustomerAlias}';
export function configureTest() {
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 {
PICTUREPARK_API_URL,
PICTUREPARK_CONFIGURATION,
PictureparkConfiguration,
AuthService,
AccessTokenAuthService
} from '@picturepark/sdk-v1-angular';
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();
}
| Extend timeout to 10 sec. | PP9-9267: Extend timeout to 10 sec.
| TypeScript | mit | Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript,Picturepark/Picturepark.SDK.TypeScript | ---
+++
@@ -14,6 +14,7 @@
export const testCustomerAlias = '{CustomerAlias}';
export function configureTest() {
+ jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
TestBed.configureTestingModule({
imports: [
HttpClientModule |
024f7bb87f57d7c15b675ce7257a0bffe42e3972 | packages/components/containers/feedback/RebrandingFeedbackModal.tsx | packages/components/containers/feedback/RebrandingFeedbackModal.tsx | import { c } from 'ttag';
import useFeature from '../../hooks/useFeature';
import { FeatureCode } from '../features/FeaturesContext';
import FeedbackModal, { FeedbackModalProps } from './FeedbackModal';
import { RebrandingFeatureValue } from './useRebrandingFeedback';
const RebrandingFeedbackModal = (props: Partial<FeedbackModalProps>) => {
const rebranding = useFeature<RebrandingFeatureValue>(FeatureCode.RebrandingFeedback);
const handleSuccess = () => {
/*
* The value of the rebranding feature is guaranteed to exist here
* because we're disabling the Feedback Modal until it's available.
*/
rebranding.update({
...rebranding.feature!.Value,
hasGivenRebrandingFeedback: true,
});
};
if (!rebranding.feature?.Value) {
return null;
}
return (
<FeedbackModal
size="medium"
onSuccess={handleSuccess}
feedbackType="rebrand_web"
scaleTitle={c('Label').t`How would you describe your experience with the new Proton?`}
scaleProps={{
from: 0,
to: 5,
fromLabel: c('Label').t`0 - Awful`,
toLabel: c('Label').t`5 - Wonderful`,
}}
{...props}
/>
);
};
export default RebrandingFeedbackModal;
| import { c } from 'ttag';
import useFeature from '../../hooks/useFeature';
import { FeatureCode } from '../features/FeaturesContext';
import FeedbackModal, { FeedbackModalProps } from './FeedbackModal';
import { RebrandingFeatureValue } from './useRebrandingFeedback';
const RebrandingFeedbackModal = (props: Partial<FeedbackModalProps>) => {
const rebranding = useFeature<RebrandingFeatureValue>(FeatureCode.RebrandingFeedback);
const handleSuccess = () => {
/*
* The value of the rebranding feature is guaranteed to exist here
* because we're disabling the Feedback Modal until it's available.
*/
rebranding.update({
...rebranding.feature!.Value,
hasGivenRebrandingFeedback: true,
});
};
if (!rebranding.feature?.Value) {
return null;
}
return (
<FeedbackModal
size="medium"
onSuccess={handleSuccess}
feedbackType="rebrand_web"
scaleTitle={c('Label').t`How would you describe your experience with the new Proton?`}
scaleProps={{
from: 1,
to: 5,
fromLabel: c('Label').t`1 - Awful`,
toLabel: c('Label').t`5 - Wonderful`,
}}
{...props}
/>
);
};
export default RebrandingFeedbackModal;
| Change rebranding feedback scale from 0-5 to 1-5 | Change rebranding feedback scale from 0-5 to 1-5
CP-4053
| TypeScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -30,9 +30,9 @@
feedbackType="rebrand_web"
scaleTitle={c('Label').t`How would you describe your experience with the new Proton?`}
scaleProps={{
- from: 0,
+ from: 1,
to: 5,
- fromLabel: c('Label').t`0 - Awful`,
+ fromLabel: c('Label').t`1 - Awful`,
toLabel: c('Label').t`5 - Wonderful`,
}}
{...props} |
891e63ff019bfcfa27b25cfd4485ab33b753d313 | src/elmReactor.ts | src/elmReactor.ts | import * as vscode from 'vscode';
import * as cp from 'child_process';
let reactor: cp.ChildProcess;
let oc: vscode.OutputChannel = vscode.window.createOutputChannel('Elm Reactor');
function startReactor() {
try {
if (reactor) {
reactor.kill();
oc.clear();
}
const config = vscode.workspace.getConfiguration('elm');
const host = config.get('reactorHost');
const port = config.get('reactorPort');
reactor = cp.spawn('elm', ['reactor', '-a=' + host, '-p=' + port], { cwd: vscode.workspace.rootPath });
reactor.stdout.on('data', (data: Buffer) => {
if (data && data.toString().startsWith('| ') === false) {
oc.append(data.toString());
}
});
reactor.stderr.on('data', (data: Buffer) => {
if (data) {
oc.append(data.toString());
}
});
oc.show(vscode.ViewColumn.Three);
}
catch (e) {
console.error("Starting Elm reactor failed", e);
vscode.window.showErrorMessage("Starting Elm reactor failed");
}
}
function stopReactor()
{
if (reactor)
{
reactor.kill();
reactor = null;
}
else
{
vscode.window.showInformationMessage('Elm Reactor not running')
}
}
export function activateReactor(): vscode.Disposable[] {
return [
vscode.commands.registerCommand('elm.reactorStart', startReactor),
vscode.commands.registerCommand('elm.reactorStop', stopReactor) ]
} | import * as vscode from 'vscode';
import * as cp from 'child_process';
let reactor: cp.ChildProcess;
let oc: vscode.OutputChannel = vscode.window.createOutputChannel('Elm Reactor');
function startReactor(): void {
try {
if (reactor) {
reactor.kill();
oc.clear();
}
const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('elm');
const host: string = <string>config.get('reactorHost');
const port: string = <string>config.get('reactorPort');
reactor = cp.spawn('elm', ['reactor', '-a=' + host, '-p=' + port], { cwd: vscode.workspace.rootPath });
reactor.stdout.on('data', (data: Buffer) => {
if (data && data.toString().startsWith('| ') === false) {
oc.append(data.toString());
}
});
reactor.stderr.on('data', (data: Buffer) => {
if (data) {
oc.append(data.toString());
}
});
oc.show(vscode.ViewColumn.Three);
} catch (e) {
console.error('Starting Elm reactor failed', e);
vscode.window.showErrorMessage('Starting Elm reactor failed');
}
}
function stopReactor(): void {
if (reactor) {
reactor.kill();
reactor = null;
} else {
vscode.window.showInformationMessage('Elm Reactor not running');
}
}
export function activateReactor(): vscode.Disposable[] {
return [
vscode.commands.registerCommand('elm.reactorStart', startReactor),
vscode.commands.registerCommand('elm.reactorStop', stopReactor)];
}
| Reformat code and add types | Reformat code and add types
| TypeScript | mit | sbrink/vscode-elm,Krzysztof-Cieslak/vscode-elm | ---
+++
@@ -4,16 +4,15 @@
let reactor: cp.ChildProcess;
let oc: vscode.OutputChannel = vscode.window.createOutputChannel('Elm Reactor');
-
-function startReactor() {
+function startReactor(): void {
try {
if (reactor) {
reactor.kill();
oc.clear();
}
- const config = vscode.workspace.getConfiguration('elm');
- const host = config.get('reactorHost');
- const port = config.get('reactorPort');
+ const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('elm');
+ const host: string = <string>config.get('reactorHost');
+ const port: string = <string>config.get('reactorPort');
reactor = cp.spawn('elm', ['reactor', '-a=' + host, '-p=' + port], { cwd: vscode.workspace.rootPath });
reactor.stdout.on('data', (data: Buffer) => {
if (data && data.toString().startsWith('| ') === false) {
@@ -26,29 +25,24 @@
}
});
oc.show(vscode.ViewColumn.Three);
- }
- catch (e) {
- console.error("Starting Elm reactor failed", e);
- vscode.window.showErrorMessage("Starting Elm reactor failed");
+ } catch (e) {
+ console.error('Starting Elm reactor failed', e);
+ vscode.window.showErrorMessage('Starting Elm reactor failed');
}
}
-function stopReactor()
-{
- if (reactor)
- {
+function stopReactor(): void {
+ if (reactor) {
reactor.kill();
reactor = null;
- }
- else
- {
- vscode.window.showInformationMessage('Elm Reactor not running')
+ } else {
+ vscode.window.showInformationMessage('Elm Reactor not running');
}
-
+
}
export function activateReactor(): vscode.Disposable[] {
return [
- vscode.commands.registerCommand('elm.reactorStart', startReactor),
- vscode.commands.registerCommand('elm.reactorStop', stopReactor) ]
+ vscode.commands.registerCommand('elm.reactorStart', startReactor),
+ vscode.commands.registerCommand('elm.reactorStop', stopReactor)];
} |
02e010d7e85345d26632897972bb735134bf225d | src/main/webapp/src/app/app.module.ts | src/main/webapp/src/app/app.module.ts | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {MaterialComponents} from './material-components';
import {TestPageComponent} from './test-page/test-page.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
declarations: [AppComponent, TestPageComponent],
imports: [
MaterialComponents,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {MaterialComponents} from './material-components';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
declarations: [AppComponent],
imports: [
MaterialComponents,
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| Remove traces of second page | Remove traces of second page
| TypeScript | apache-2.0 | googleinterns/step26-2020,googleinterns/step26-2020,googleinterns/step26-2020,googleinterns/step26-2020 | ---
+++
@@ -18,11 +18,10 @@
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {MaterialComponents} from './material-components';
-import {TestPageComponent} from './test-page/test-page.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
- declarations: [AppComponent, TestPageComponent],
+ declarations: [AppComponent],
imports: [
MaterialComponents,
BrowserModule, |
e7ee96689d5d83071232dea796ec362c327f8e51 | src/main/installDevTools.ts | src/main/installDevTools.ts | import installExtension, {
REACT_DEVELOPER_TOOLS,
REDUX_DEVTOOLS,
} from "electron-devtools-installer"
import electronIsDev from "electron-is-dev"
export const installDevTools = (): void => {
const devTools = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS, "devtron"]
if (electronIsDev) {
devTools.forEach(
async (tool): Promise<string> => {
const toolName = await installExtension(tool)
console.log(`Added Extension: ${toolName}`)
return toolName
},
)
}
}
| import installExtension, {
REACT_DEVELOPER_TOOLS,
REDUX_DEVTOOLS,
} from "electron-devtools-installer"
import electronIsDev from "electron-is-dev"
export const installDevTools = (): void => {
const devTools = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS]
if (electronIsDev) {
devTools.forEach(
async (tool): Promise<string> => {
const toolName = await installExtension(tool)
console.log(`Added Extension: ${toolName}`)
return toolName
},
)
}
}
| Stop trying to make devtron load on app start | Stop trying to make devtron load on app start
It's not working
| TypeScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -5,7 +5,7 @@
import electronIsDev from "electron-is-dev"
export const installDevTools = (): void => {
- const devTools = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS, "devtron"]
+ const devTools = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS]
if (electronIsDev) {
devTools.forEach(
async (tool): Promise<string> => { |
9545f2a55b87579826829fe708166d3b76f7e85f | src/app/feed.service.ts | src/app/feed.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import { Feed } from './model/feed';
@Injectable()
export class FeedService {
private rssToJsonServiceBaseUrl: string = 'http://rss2json.com/api.json?rss_url=';
constructor(
private http: Http
) { }
getFeedContent(url: string): Observable<Feed> {
return this.http.get(this.rssToJsonServiceBaseUrl + url)
.map(this.extractFeeds)
.catch(this.handleError);
}
private extractFeeds(res: Response): Feed {
let feed = res.json();
return feed || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
| import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import { Feed } from './model/feed';
@Injectable()
export class FeedService {
private rssToJsonServiceBaseUrl: string = 'https://rss2json.com/api.json?rss_url=';
constructor(
private http: Http
) { }
getFeedContent(url: string): Observable<Feed> {
return this.http.get(this.rssToJsonServiceBaseUrl + url)
.map(this.extractFeeds)
.catch(this.handleError);
}
private extractFeeds(res: Response): Feed {
let feed = res.json();
return feed || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
| Use https protocol for security. | Use https protocol for security. | TypeScript | mit | Chan4077/angular-rss-reader,Chan4077/angular-rss-reader,Chan4077/angular-rss-reader | ---
+++
@@ -6,7 +6,7 @@
@Injectable()
export class FeedService {
- private rssToJsonServiceBaseUrl: string = 'http://rss2json.com/api.json?rss_url=';
+ private rssToJsonServiceBaseUrl: string = 'https://rss2json.com/api.json?rss_url=';
constructor(
private http: Http |
2a0d46c4acc9430aff1504934a6ce872b0048b1f | ts/_declare/jquery.eventListener.d.ts | ts/_declare/jquery.eventListener.d.ts | interface JQuery
{
addEventListener(type:string, selector?:any, data?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
addEventListener(type:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
} | interface JQuery
{
addEventListener(type:string, selector?:any, data?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
addEventListener(type:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, selector?:any, data?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
}
| Allow removeEventListener to be more flexible | Allow removeEventListener to be more flexible | TypeScript | mit | codeBelt/StructureJS,codeBelt/StructureJS,codeBelt/StructureJS | ---
+++
@@ -3,6 +3,7 @@
addEventListener(type:string, selector?:any, data?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
addEventListener(type:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
+ removeEventListener(type?:string, selector?:any, data?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, selector?:any, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
removeEventListener(type?:string, handler?:(eventObject:JQueryEventObject) => any, scope?:any): JQuery;
} |
5f129c31c73f6d1255f4a84f71e0c3da69cd99f1 | src/frontend/redux/store.ts | src/frontend/redux/store.ts | import * as Redux from 'redux'
import Hermes from '~/../utils/hermes'
import {rootReducer, rootReducerMock} from '~/frontend/redux/reducers'
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: Function
}
}
const logger = new Hermes({name: 'frontend'})
const configureStore = (): Redux.Store<any> => {
const devtools = window.__REDUX_DEVTOOLS_EXTENSION__
const _m = module as any
if (_m.hot) {
logger.info('Loading rootReducerMock')
const store = Redux.createStore(rootReducerMock, devtools && devtools())
_m.hot.accept('./reducers', () => store.replaceReducer(require('./reducers')))
return store
}
const store = Redux.createStore(rootReducer, devtools && devtools())
return store
}
const store = configureStore()
export default store
| import * as Redux from 'redux'
import Hermes from '~/../utils/hermes'
import {rootReducer, rootReducerMock} from '~/frontend/redux/reducers'
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: Function
}
}
const useMock = false // Should only be true for development
const logger = new Hermes({name: 'frontend'})
const configureStore = (): Redux.Store<any> => {
const devtools = window.__REDUX_DEVTOOLS_EXTENSION__
const _m = module as any
if (_m.hot && useMock) {
logger.info('Loading rootReducerMock')
const store = Redux.createStore(rootReducerMock, devtools && devtools())
_m.hot.accept('./reducers', () => store.replaceReducer(require('./reducers')))
return store
}
const store = Redux.createStore(rootReducer, devtools && devtools())
return store
}
const store = configureStore()
export default store
| Use mock reducer only when useMock=true | Use mock reducer only when useMock=true
| TypeScript | mit | devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity,devonzuegel/clarity | ---
+++
@@ -9,13 +9,14 @@
}
}
+const useMock = false // Should only be true for development
const logger = new Hermes({name: 'frontend'})
const configureStore = (): Redux.Store<any> => {
const devtools = window.__REDUX_DEVTOOLS_EXTENSION__
const _m = module as any
- if (_m.hot) {
+ if (_m.hot && useMock) {
logger.info('Loading rootReducerMock')
const store = Redux.createStore(rootReducerMock, devtools && devtools())
_m.hot.accept('./reducers', () => store.replaceReducer(require('./reducers'))) |
2729fde6f31b2d2e53c9335a03b77c5c8a1e7bc6 | app/scripts/modules/amazon/src/serverGroup/configure/wizard/securityGroups/ServerGroupSecurityGroupsRemoved.tsx | app/scripts/modules/amazon/src/serverGroup/configure/wizard/securityGroups/ServerGroupSecurityGroupsRemoved.tsx | import * as React from 'react';
import { FirewallLabels, noop } from '@spinnaker/core';
import { IAmazonServerGroupCommand } from '../../serverGroupConfiguration.service';
export interface IServerGroupSecurityGroupsRemovedProps {
command?: IAmazonServerGroupCommand;
removed?: string[];
onClear?: () => void;
}
export class ServerGroupSecurityGroupsRemoved extends React.Component<IServerGroupSecurityGroupsRemovedProps> {
public static defaultProps: Partial<IServerGroupSecurityGroupsRemovedProps> = {
onClear: noop,
};
public render() {
const { command, onClear, removed } = this.props;
const dirtySecurityGroups = ((command && command.viewState.dirty.securityGroups) || []).concat(removed || []);
if (dirtySecurityGroups.length === 0) {
return null;
}
return (
<div className="col-md-12">
<div className="alert alert-warning">
<p>
<i className="fa fa-exclamation-triangle" />
The following {FirewallLabels.get('firewalls')} could not be found in the selected account/region/VPC and
were removed:
</p>
<ul>
{dirtySecurityGroups.map(s => (
<li key="s">{s}</li>
))}
</ul>
<p className="text-right">
<a className="btn btn-sm btn-default dirty-flag-dismiss clickable" onClick={onClear}>
Okay
</a>
</p>
</div>
</div>
);
}
}
| import * as React from 'react';
import { FirewallLabels, noop } from '@spinnaker/core';
import { IAmazonServerGroupCommand } from '../../serverGroupConfiguration.service';
export interface IServerGroupSecurityGroupsRemovedProps {
command?: IAmazonServerGroupCommand;
removed?: string[];
onClear?: () => void;
}
export class ServerGroupSecurityGroupsRemoved extends React.Component<IServerGroupSecurityGroupsRemovedProps> {
public static defaultProps: Partial<IServerGroupSecurityGroupsRemovedProps> = {
onClear: noop,
};
public render() {
const { command, onClear, removed } = this.props;
const dirtySecurityGroups = ((command && command.viewState.dirty.securityGroups) || []).concat(removed || []);
if (dirtySecurityGroups.length === 0) {
return null;
}
return (
<div className="col-md-12">
<div className="alert alert-warning">
<p>
<i className="fa fa-exclamation-triangle" />
The following {FirewallLabels.get('firewalls')} could not be found in the selected account/region/VPC and
were removed:
</p>
<ul>
{dirtySecurityGroups.map(s => (
<li key={s}>{s}</li>
))}
</ul>
<p className="text-right">
<a className="btn btn-sm btn-default dirty-flag-dismiss clickable" onClick={onClear}>
Okay
</a>
</p>
</div>
</div>
);
}
}
| Fix react key in forEach | fix(amazon/serverGroup): Fix react key in forEach
| TypeScript | apache-2.0 | icfantv/deck,ajordens/deck,icfantv/deck,duftler/deck,ajordens/deck,sgarlick987/deck,sgarlick987/deck,spinnaker/deck,sgarlick987/deck,spinnaker/deck,duftler/deck,spinnaker/deck,icfantv/deck,sgarlick987/deck,duftler/deck,icfantv/deck,duftler/deck,ajordens/deck,spinnaker/deck,ajordens/deck | ---
+++
@@ -34,7 +34,7 @@
</p>
<ul>
{dirtySecurityGroups.map(s => (
- <li key="s">{s}</li>
+ <li key={s}>{s}</li>
))}
</ul>
<p className="text-right"> |
a84fa36a36881a5e80a0e7d1b89b334f079b6ecf | src/model/literature.ts | src/model/literature.ts | /**
* @author Thomas Kleinke
*/
export interface Literature {
quotation: string;
zenonId?: string;
}
export module Literature {
export const QUOTATION = 'quotation';
export const ZENON_ID = 'zenonId';
const VALID_FIELDS = [QUOTATION, ZENON_ID];
export function generateLabel(literature: Literature, getTranslation: (key: string) => string): string {
return literature.quotation + (literature.zenonId
? ' ('
+ getTranslation('zenonId')
+ ': ' + literature.zenonId + ')'
: '');
}
export function isValid(literature: Literature, options?: any): boolean {
for (const fieldName in literature) {
if (!VALID_FIELDS.includes(fieldName)) return false;
}
return literature.quotation !== undefined && literature.quotation.length > 0;
}
}
| /**
* @author Thomas Kleinke
*/
export interface Literature {
quotation: string;
zenonId?: string;
page?: string;
figure?: string;
}
export module Literature {
export const QUOTATION = 'quotation';
export const ZENON_ID = 'zenonId';
export const PAGE = 'page';
export const FIGURE = 'figure';
const VALID_FIELDS = [QUOTATION, ZENON_ID, PAGE, FIGURE];
export function generateLabel(literature: Literature, getTranslation: (key: string) => string): string {
let additionalInformation: string[] = [];
if (literature.zenonId) {
additionalInformation.push(getTranslation('zenonId') + ': ' + literature.zenonId);
}
if (literature.page) {
additionalInformation.push(getTranslation('page') + ' ' + literature.page);
}
if (literature.figure) {
additionalInformation.push(getTranslation('figure') + ' ' + literature.figure);
}
return literature.quotation + (additionalInformation.length > 0
? '(' + additionalInformation.join(', ') + ')'
: ''
);
}
export function isValid(literature: Literature, options?: any): boolean {
for (const fieldName in literature) {
if (!VALID_FIELDS.includes(fieldName)) return false;
}
return literature.quotation !== undefined && literature.quotation.length > 0;
}
}
| Add fields page & figure to Literature | Add fields page & figure to Literature
| TypeScript | apache-2.0 | dainst/idai-components-2,dainst/idai-components-2,dainst/idai-components-2 | ---
+++
@@ -5,6 +5,8 @@
quotation: string;
zenonId?: string;
+ page?: string;
+ figure?: string;
}
@@ -12,16 +14,30 @@
export const QUOTATION = 'quotation';
export const ZENON_ID = 'zenonId';
+ export const PAGE = 'page';
+ export const FIGURE = 'figure';
- const VALID_FIELDS = [QUOTATION, ZENON_ID];
+ const VALID_FIELDS = [QUOTATION, ZENON_ID, PAGE, FIGURE];
+
export function generateLabel(literature: Literature, getTranslation: (key: string) => string): string {
- return literature.quotation + (literature.zenonId
- ? ' ('
- + getTranslation('zenonId')
- + ': ' + literature.zenonId + ')'
- : '');
+ let additionalInformation: string[] = [];
+
+ if (literature.zenonId) {
+ additionalInformation.push(getTranslation('zenonId') + ': ' + literature.zenonId);
+ }
+ if (literature.page) {
+ additionalInformation.push(getTranslation('page') + ' ' + literature.page);
+ }
+ if (literature.figure) {
+ additionalInformation.push(getTranslation('figure') + ' ' + literature.figure);
+ }
+
+ return literature.quotation + (additionalInformation.length > 0
+ ? '(' + additionalInformation.join(', ') + ')'
+ : ''
+ );
}
|
bf70ebd9501813ca3c8e68d32b6ab5d518e541fc | lib/utils/calculate-grid-points.ts | lib/utils/calculate-grid-points.ts | import lonlat from '@conveyal/lonlat'
import {PROJECTION_ZOOM_LEVEL} from 'lib/constants'
/**
* The grid extent is computed from the points. If the cell number for the right edge of the grid is rounded
* down, some points could fall outside the grid. `lonlat.toPixel` and `lonlat.toPixel` naturally truncate down, which is
* the correct behavior for binning points into cells but means the grid is (almost) always 1 row too
* narrow/short, so we add 1 to the height and width when a grid is created in this manner.
*/
export default function calculateGridPoints(
bounds: CL.Bounds,
zoom = PROJECTION_ZOOM_LEVEL
): number {
const topLeft = lonlat.toPixel([bounds.west, bounds.north], zoom)
const bottomRight = lonlat.toPixel([bounds.east, bounds.south], zoom)
const width = Math.floor(topLeft.x) - Math.floor(bottomRight.x) + 2
const height = Math.floor(topLeft.y) - Math.floor(bottomRight.y) + 2
return width * height
}
| import lonlat from '@conveyal/lonlat'
import {PROJECTION_ZOOM_LEVEL} from 'lib/constants'
/**
* The grid extent is computed from the points. If the cell number for the right edge of the grid is rounded
* down, some points could fall outside the grid. `lonlat.toPixel` and `lonlat.toPixel` naturally truncate down, which is
* the correct behavior for binning points into cells but means the grid is (almost) always 1 row too
* narrow/short, so we add 1 to the height and width when a grid is created in this manner.
*/
export default function calculateGridPoints(
bounds: CL.Bounds,
zoom = PROJECTION_ZOOM_LEVEL
): number {
const topLeft = lonlat.toPixel([bounds.west, bounds.north], zoom)
const bottomRight = lonlat.toPixel([bounds.east, bounds.south], zoom)
const width = Math.floor(topLeft.x) - Math.floor(bottomRight.x)
const height = Math.floor(topLeft.y) - Math.floor(bottomRight.y)
return (width + 2) * (height + 2)
}
| Add 2 to the height and width | Add 2 to the height and width
| TypeScript | mit | conveyal/analysis-ui,conveyal/analysis-ui,conveyal/analysis-ui | ---
+++
@@ -14,7 +14,7 @@
): number {
const topLeft = lonlat.toPixel([bounds.west, bounds.north], zoom)
const bottomRight = lonlat.toPixel([bounds.east, bounds.south], zoom)
- const width = Math.floor(topLeft.x) - Math.floor(bottomRight.x) + 2
- const height = Math.floor(topLeft.y) - Math.floor(bottomRight.y) + 2
- return width * height
+ const width = Math.floor(topLeft.x) - Math.floor(bottomRight.x)
+ const height = Math.floor(topLeft.y) - Math.floor(bottomRight.y)
+ return (width + 2) * (height + 2)
} |
5b5e3897219c2df2954a9a2980fa920c15f7be39 | src/extension.ts | src/extension.ts | 'use strict';
import {window, workspace, commands, ExtensionContext} from 'vscode';
import path = require('path');
import fs = require('fs');
import Yeoman from './yo/yo';
const yo = new Yeoman();
export function activate(context: ExtensionContext) {
const cwd = workspace.rootPath;
const disposable = commands.registerCommand('yo', () => {
list()
.then(generators => {
return window.showQuickPick(generators.map(generator => {
return {
label: generator.name.split(/\-(.+)?/)[1],
description: generator.description
};
}));
})
.then(generator => {
yo.run(generator.label, cwd);
})
.catch(err => {
console.error(err);
});
});
context.subscriptions.push(disposable);
}
function list(): Promise<any[]> {
return new Promise(resolve => {
yo.getEnvironment().lookup(() => {
resolve(yo.getGenerators());
});
});
}
| 'use strict';
import {window, workspace, commands, ExtensionContext} from 'vscode';
import path = require('path');
import fs = require('fs');
import Yeoman from './yo/yo';
const yo = new Yeoman();
export function activate(context: ExtensionContext) {
const cwd = workspace.rootPath;
const disposable = commands.registerCommand('yo', () => {
list()
.then(generators => {
return window.showQuickPick(generators.map(generator => {
return {
label: generator.name.split(/\-(.+)?/)[1],
description: generator.description
};
}));
})
.then(generator => {
if (generator !== undefined) {
yo.run(generator.label, cwd);
}
})
.catch(err => {
console.error(err);
});
});
context.subscriptions.push(disposable);
}
function list(): Promise<any[]> {
return new Promise(resolve => {
yo.getEnvironment().lookup(() => {
resolve(yo.getGenerators());
});
});
}
| Fix pressing escape when picking generator | Fix pressing escape when picking generator
| TypeScript | mit | SamVerschueren/vscode-yo | ---
+++
@@ -22,7 +22,9 @@
}));
})
.then(generator => {
- yo.run(generator.label, cwd);
+ if (generator !== undefined) {
+ yo.run(generator.label, cwd);
+ }
})
.catch(err => {
console.error(err); |
0590b82137c313ca0d78d9da9fff69b91b7b6fe6 | src/client/app/shared/name-list/name-list.service.ts | src/client/app/shared/name-list/name-list.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
/**
* This class provides the NameList service with methods to read names and add names.
*/
@Injectable()
export class NameListService {
/**
* Creates a new NameListService with the injected Http.
* @param {Http} http - The injected Http.
* @constructor
*/
constructor(private http: Http) {}
/**
* Returns an Observable for the HTTP GET request for the JSON resource.
* @return {string[]} The Observable for the HTTP request.
*/
get(): Observable<string[]> {
return this.http.get('/assets/data.json')
.map((res: Response) => res.json())
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
| import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
// import 'rxjs/add/operator/do'; // for debugging
import 'rxjs/add/operator/catch';
/**
* This class provides the NameList service with methods to read names and add names.
*/
@Injectable()
export class NameListService {
/**
* Creates a new NameListService with the injected Http.
* @param {Http} http - The injected Http.
* @constructor
*/
constructor(private http: Http) {}
/**
* Returns an Observable for the HTTP GET request for the JSON resource.
* @return {string[]} The Observable for the HTTP request.
*/
get(): Observable<string[]> {
return this.http.get('/assets/data.json')
.map((res: Response) => res.json())
// .do(data => console.log('server data:', data)) // debug
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
| Fix `TypeError` when trying to re-throw | Fix `TypeError` when trying to re-throw
without the rxjs imports, re-throwing error in `handleError` results in a `TypeError: Observable_1.Observable.throw is not a function`
I have also added in the `do` debugging lib (commented out) as its a handy tool to point out to dev's who are not familiar with rxjs (like myself) | TypeScript | mit | davewragg/agot-spa,adobley/angular2-tdd-workshop,oblong-antelope/oblong-web,radiorabe/raar-ui,NathanWalker/angular2-seed-advanced,rtang03/fabric-seed,Nightapes/angular2-seed,vyakymenko/angular-seed-express,CNSKnight/angular2-seed-advanced,NathanWalker/angular2-seed-advanced,OlivierVoyer/angular-seed-advanced,pratheekhegde/a2-redux,Nightapes/angular2-seed,hookom/climbontheway,hookom/climbontheway,llwt/angular-seed-advanced,millea1/tips1,llwt/angular-seed-advanced,felipecamargo/ACSC-SBPL-M,JohnnyQQQQ/md-dashboard,Nightapes/angular2-seed,CNSKnight/angular2-seed-advanced,prabhatsharma/bwa2,Jimmysh/angular2-seed-advanced,lhoezee/faithreg1,JohnnyQQQQ/md-dashboard,zertyz/observatorio-SUAS-formularios,MgCoders/angular-seed,ManasviA/Dashboard,davewragg/agot-spa,pieczkus/whyblogfront,ilvestoomas/angular-seed-advanced,rtang03/fabric-seed,ilvestoomas/angular-seed-advanced,sylviefiat/bdmer3,AWNICS/mesomeds-ng2,mgechev/angular-seed,watonyweng/angular-seed,maniche04/ngIntranet,wenzelj/nativescript-angular,tobiaseisenschenk/data-cube,alexmanning23/uafl-web,pieczkus/whyblogfront,lhoezee/faithreg1,zertyz/angular-seed-advanced-spikes,llwt/angular-seed-advanced,Shyiy/angular-seed,NathanWalker/angular-seed-advanced,ronikurnia1/ClientApp,mgechev/angular2-seed,pratheekhegde/a2-redux,JohnnyQQQQ/angular-seed-material2,chnoumis/angular2-seed-advanced,felipecamargo/ACSC-SBPL-M,idready/Bloody-Prophety-NG2,Karasuni/angular-seed,AnnaCasper/finance-tool,OlivierVoyer/angular-seed-advanced,dmitriyse/angular2-seed,zertyz/observatorio-SUAS,arun-awnics/mesomeds-ng2,oblong-antelope/oblong-web,lhoezee/faithreg1,rtang03/fabric-seed,ysyun/angular-seed-stub-api-environment,GeoscienceAustralia/gnss-site-manager,dmitriyse/angular2-seed,JohnnyQQQQ/angular-seed-material2,Jimmysh/angular2-seed-advanced,tobiaseisenschenk/data-cube,radiorabe/raar-ui,mgechev/angular-seed,fr-esco/angular-seed,arun-awnics/mesomeds-ng2,MgCoders/angular-seed,pratheekhegde/a2-redux,zertyz/edificando-o-controle-interno,ysyun/angular-seed-stub-api-environment,tiagomapmarques/angular-examples_books,zertyz/observatorio-SUAS-formularios,CNSKnight/angular2-seed-advanced,chnoumis/angular2-seed-advanced,zertyz/observatorio-SUAS-formularios,origamyllc/Mangular,m-abs/angular2-seed-advanced,wenzelj/nativescript-angular,pocmanu/angular2-seed-advanced,AWNICS/mesomeds-ng2,ManasviA/Dashboard,felipecamargo/ACSC-SBPL-M,AWNICS/mesomeds-ng2,tctc91/angular2-wordpress-portfolio,ilvestoomas/angular-seed-advanced,m-abs/angular2-seed-advanced,fr-esco/angular-seed,NathanWalker/angular-seed-advanced,prabhatsharma/bwa2,ronikurnia1/ClientApp,OlivierVoyer/angular-seed-advanced,maniche04/ngIntranet,Karasuni/angular-seed,zertyz/angular-seed-advanced-spikes,ppanthony/angular-seed-tutorial,radiorabe/raar-ui,tiagomapmarques/angular-examples_books,MgCoders/angular-seed,watonyweng/angular-seed,pocmanu/angular2-seed-advanced,MgCoders/angular-seed,fart-one/monitor-ngx,guilhebl/offer-web,origamyllc/Mangular,sanastasiadis/angular-seed-openlayers,jigarpt/angular-seed-semi,Shyiy/angular-seed,mgechev/angular2-seed,prabhatsharma/bwa2,NathanWalker/angular-seed-advanced,arun-awnics/mesomeds-ng2,nickaranz/robinhood-ui,davewragg/agot-spa,deanQj/angular2-seed-bric,ManasviA/Dashboard,NathanWalker/angular2-seed-advanced,deanQj/angular2-seed-bric,jigarpt/angular-seed-semi,guilhebl/offer-web,vyakymenko/angular-seed-express,shaggyshelar/Linkup,idready/Philosophers,sylviefiat/bdmer3,idready/Philosophers,natarajanmca11/angular2-seed,adobley/angular2-tdd-workshop,idready/Bloody-Prophety-NG2,ysyun/angular-seed-stub-api-environment,maniche04/ngIntranet,shaggyshelar/Linkup,AnnaCasper/finance-tool,dmitriyse/angular2-seed,Karasuni/angular-seed,trutoo/startatalk-native,guilhebl/offer-web,oblong-antelope/oblong-web,ppanthony/angular-seed-tutorial,idready/Bloody-Prophety-NG2,dmitriyse/angular2-seed,alexmanning23/uafl-web,m-abs/angular2-seed-advanced,talentspear/a2-redux,rtang03/fabric-seed,zertyz/edificando-o-controle-interno,fart-one/monitor-ngx,talentspear/a2-redux,Sn3b/angular-seed-advanced,miltador/unichat,ManasviA/Dashboard,tctc91/angular2-wordpress-portfolio,zertyz/observatorio-SUAS,mgechev/angular-seed,jelgar1/fpl-api,adobley/angular2-tdd-workshop,Shyiy/angular-seed,ysyun/angular-seed-stub-api-environment,trutoo/startatalk-native,millea1/tips1,trutoo/startatalk-native,tctc91/angular2-wordpress-portfolio,nie-ine/raeber-website,rawnics/mesomeds-ng2,OlivierVoyer/angular-seed-advanced,nickaranz/robinhood-ui,shaggyshelar/Linkup,zertyz/angular-seed-advanced-spikes,radiorabe/raar-ui,nickaranz/robinhood-ui,rawnics/mesomeds-ng2,pieczkus/whyblogfront,chnoumis/angular2-seed-advanced,rawnics/mesomeds-ng2,JohnnyQQQQ/md-dashboard,vyakymenko/angular-seed-express,alexmanning23/uafl-web,adobley/angular2-tdd-workshop,miltador/unichat,hookom/climbontheway,zertyz/edificando-o-controle-interno,Sn3b/angular-seed-advanced,millea1/tips1,ronikurnia1/ClientApp,zertyz/observatorio-SUAS,natarajanmca11/angular2-seed,zertyz/observatorio-SUAS,sanastasiadis/angular-seed-openlayers,christophersanson/js-demo-fe,christophersanson/js-demo-fe,natarajanmca11/angular2-seed,tobiaseisenschenk/data-cube,jelgar1/fpl-api,ppanthony/angular-seed-tutorial,GeoscienceAustralia/gnss-site-manager,deanQj/angular2-seed-bric,nie-ine/raeber-website,rtang03/fabric-seed,tiagomapmarques/angular-examples_books,Sn3b/angular-seed-advanced,jigarpt/angular-seed-semi,nie-ine/raeber-website,talentspear/a2-redux,pocmanu/angular2-seed-advanced,AnnaCasper/finance-tool,jelgar1/fpl-api,sanastasiadis/angular-seed-openlayers,wenzelj/nativescript-angular,sylviefiat/bdmer3,JohnnyQQQQ/angular-seed-material2,Jimmysh/angular2-seed-advanced,hookom/climbontheway,fart-one/monitor-ngx,fr-esco/angular-seed,mgechev/angular2-seed,GeoscienceAustralia/gnss-site-manager,nie-ine/raeber-website,origamyllc/Mangular,christophersanson/js-demo-fe,idready/Philosophers,miltador/unichat | ---
+++
@@ -1,6 +1,11 @@
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
+
+import 'rxjs/add/observable/throw';
+import 'rxjs/add/operator/map';
+// import 'rxjs/add/operator/do'; // for debugging
+import 'rxjs/add/operator/catch';
/**
* This class provides the NameList service with methods to read names and add names.
@@ -22,6 +27,7 @@
get(): Observable<string[]> {
return this.http.get('/assets/data.json')
.map((res: Response) => res.json())
+ // .do(data => console.log('server data:', data)) // debug
.catch(this.handleError);
}
|
6ed2ef1326cd8c2f287f1e4999b735c4af26b56e | src/SyntaxNodes/OrderedListItemNode.ts | src/SyntaxNodes/OrderedListItemNode.ts | import { RichSyntaxNode } from './RichSyntaxNode'
export class OrderedListItemNode extends RichSyntaxNode {
private NUMBERED_LIST_ITEM: any = null
} | import { SyntaxNode } from '../SyntaxNodes/SyntaxNode'
import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode'
export class OrderedListItemNode extends RichSyntaxNode {
constructor(parentOrChildren?: RichSyntaxNode | SyntaxNode[], public ordinal?: number) {
super(parentOrChildren)
}
private NUMBERED_LIST_ITEM: any = null
} | Add ordinal to ordered list items | Add ordinal to ordered list items
| TypeScript | mit | start/up,start/up | ---
+++
@@ -1,5 +1,10 @@
-import { RichSyntaxNode } from './RichSyntaxNode'
+import { SyntaxNode } from '../SyntaxNodes/SyntaxNode'
+import { RichSyntaxNode } from '../SyntaxNodes/RichSyntaxNode'
export class OrderedListItemNode extends RichSyntaxNode {
+ constructor(parentOrChildren?: RichSyntaxNode | SyntaxNode[], public ordinal?: number) {
+ super(parentOrChildren)
+ }
+
private NUMBERED_LIST_ITEM: any = null
} |
61ebc2bb8142645709aaac98182b4201c39b5aeb | packages/ng/demo/app/date-range-picker/basic/basic.component.ts | packages/ng/demo/app/date-range-picker/basic/basic.component.ts | import { Component } from '@angular/core';
import * as moment from 'moment';
import {DateRangeSelectChoice} from '../../../../src/app/date-range-picker/date-range-picker.component';
@Component({
selector: 'demo-basic-date-range-picker',
templateUrl: './basic.component.html',
styleUrls: ['./basic.component.scss']
})
export class BasicComponent {
preConfiguredRanges: DateRangeSelectChoice[];
placeholder: string;
dateMin: moment.Moment;
dateMax: moment.Moment;
constructor() {
const today = moment().startOf('day');
this.placeholder = 'Select date range';
this.preConfiguredRanges = [
{label: 'This day', dateMin: today.clone(), dateMax:today.clone().add(1, 'day')},
{label: 'This month', dateMin: today.clone().startOf('month'), dateMax: today.clone().add(1, 'month').startOf('month')}
];
}
}
| import { Component } from '@angular/core';
import * as moment from 'moment';
import {DateRangeSelectChoice} from '../../../../src/app/date-range-picker/date-range-picker.component';
@Component({
selector: 'demo-basic-date-range-picker',
templateUrl: './basic.component.html',
styles: ['']
})
export class BasicComponent {
preConfiguredRanges: DateRangeSelectChoice[];
placeholder: string;
dateMin: moment.Moment;
dateMax: moment.Moment;
constructor() {
const today = moment().startOf('day');
this.placeholder = 'Select date range';
this.preConfiguredRanges = [
{label: 'This day', dateMin: today.clone(), dateMax:today.clone().add(1, 'day')},
{label: 'This month', dateMin: today.clone().startOf('month'), dateMax: today.clone().add(1, 'month').startOf('month')}
];
}
}
| FIX forgot to delete useless scss import | FIX forgot to delete useless scss import
oops
| TypeScript | mit | LuccaSA/lucca-front,LuccaSA/lucca-front,LuccaSA/lucca-front,LuccaSA/lucca-front | ---
+++
@@ -5,7 +5,7 @@
@Component({
selector: 'demo-basic-date-range-picker',
templateUrl: './basic.component.html',
- styleUrls: ['./basic.component.scss']
+ styles: ['']
})
export class BasicComponent {
|
ef4314effd1f5233e35987265ef85cc4d3c5929d | src/app/sparrows/languages-training-set.ts | src/app/sparrows/languages-training-set.ts | import { createTrainingSet } from './training-set';
export const goRustAssignmentsTrainingSet = {
title: "Go vs Rust",
left: "Go.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 19, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const haskellRustAssignmentsTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const goRustTrainingSet = {
title: "Go vs Rust",
left: "Go.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 23, prefix: ".png" }, { name: "Rust.", number: 23, prefix: ".png" })
};
export const haskellRustTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
};
| import { createTrainingSet } from './training-set';
export const goRustAssignmentsTrainingSet = {
title: "Go vs Rust",
left: "Go.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.Assignment.", number: 19, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const haskellRustAssignmentsTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Haskell.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const goRustTrainingSet = {
title: "Go vs Rust",
left: "Go.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Go.", number: 23, prefix: ".png" }, { name: "Rust.", number: 23, prefix: ".png" })
};
export const haskellRustTrainingSet = {
title: "Haskell vs Rust",
left: "Haskell.",
right: "Rust.",
baseUrl: "languages/",
examples: createTrainingSet({ name: "Haskell.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
};
| Fix naming mismatches in the Haskell/Rust sets | Fix naming mismatches in the Haskell/Rust sets
| TypeScript | apache-2.0 | LearnWithLlew/SparrowDecks,LearnWithLlew/SparrowDecks,LearnWithLlew/SparrowDecks | ---
+++
@@ -13,7 +13,7 @@
left: "Haskell.Assignment.",
right: "Rust.Assignment.",
baseUrl: "languages/",
- examples: createTrainingSet({ name: "Go.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
+ examples: createTrainingSet({ name: "Haskell.Assignment.", number: 17, prefix: ".png" }, { name: "Rust.Assignment.", number: 18, prefix: ".png" })
};
export const goRustTrainingSet = {
@@ -29,5 +29,5 @@
left: "Haskell.",
right: "Rust.",
baseUrl: "languages/",
- examples: createTrainingSet({ name: "Go.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
+ examples: createTrainingSet({ name: "Haskell.", number: 21, prefix: ".png" }, { name: "Rust.", number: 21, prefix: ".png" })
}; |
88e13c49708800977e40791cf3fe66862ac9c4f9 | projects/hslayers/src/components/sidebar/impressum.component.ts | projects/hslayers/src/components/sidebar/impressum.component.ts | import {Component} from '@angular/core';
import * as packageJson from '../../package.json';
import {HsUtilsService} from '../utils/utils.service';
@Component({
selector: 'hs-impressum',
templateUrl: './partials/impressum.html',
})
export class HsImpressumComponent {
version = 'dev';
logo = '';
logoDisabled = false;
constructor(public hsUtilsService: HsUtilsService) {
this.version = packageJson.version;
}
}
| import {Component} from '@angular/core';
import packageJson from '../../package.json';
import {HsUtilsService} from '../utils/utils.service';
@Component({
selector: 'hs-impressum',
templateUrl: './partials/impressum.html',
})
export class HsImpressumComponent {
version = 'dev';
logo = '';
logoDisabled = false;
constructor(public hsUtilsService: HsUtilsService) {
this.version = packageJson.version;
}
}
| Change how package version is imported | fix: Change how package version is imported
| TypeScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -1,6 +1,6 @@
import {Component} from '@angular/core';
-import * as packageJson from '../../package.json';
+import packageJson from '../../package.json';
import {HsUtilsService} from '../utils/utils.service';
@Component({ |
3aab81ba1bc8b9f05687b6908dd202dbe70fa16b | src/helpers/streams.ts | src/helpers/streams.ts | import { Readable, PassThrough } from 'stream';
export function readbleFromString(data: string): Readable {
const readable = emptyReadable();
readable.push(data);
readable.push(null);
return readable;
}
export function readbleFromBuffer(data: any): Readable {
const readable = emptyReadable();
readable.push(data);
readable.push(null);
return readable;
}
export function emptyReadable(): Readable {
const readable = new Readable();
readable._read = () => { }; // avoid crash in console
return readable;
}
/**
* Duplicate a readble stream for multiple consumers
*/
export function duplicateStream(stream: Readable): [Readable, Readable] {
const pass1 = new PassThrough();
const pass2 = new PassThrough();
stream.pipe(pass1)
stream.pipe(pass2)
return [pass1, pass2];
} | import { Readable, PassThrough } from 'stream';
export function readbleFromString(data: string): Readable {
const readable = emptyReadable();
readable.push(data);
readable.push(null);
return readable;
}
export function readbleFromBuffer(data: any): Readable {
const readable = emptyReadable();
readable.push(data);
readable.push(null);
return readable;
}
/**
* Duplicate a readble stream for multiple consumers
*/
export function duplicateStream(stream: Readable): [Readable, Readable] {
const clone1 = clone(stream);
const clone2 = clone(stream);
return [clone1, clone2];
}
function clone(stream: Readable): Readable {
const readable = emptyReadable();
stream.on("data" , (chunk) => {
readable.push(chunk);
});
stream.on("end", () => {
readable.push(null);
});
stream.on("error", (err) => {
readable.emit("error", err);
});
return readable;
}
export function emptyReadable(): Readable {
const readable = new Readable();
readable._read = () => { }; // avoid crash in console
return readable;
} | Fix stream duplication logic by creating fresh redable pipelines | Fix stream duplication logic by creating fresh redable pipelines
| TypeScript | mit | arijoon/vendaire-discord-bot,arijoon/vendaire-discord-bot | ---
+++
@@ -16,22 +16,36 @@
return readable;
}
+/**
+ * Duplicate a readble stream for multiple consumers
+ */
+export function duplicateStream(stream: Readable): [Readable, Readable] {
+ const clone1 = clone(stream);
+ const clone2 = clone(stream);
+
+ return [clone1, clone2];
+}
+
+function clone(stream: Readable): Readable {
+ const readable = emptyReadable();
+ stream.on("data" , (chunk) => {
+ readable.push(chunk);
+ });
+
+ stream.on("end", () => {
+ readable.push(null);
+ });
+
+ stream.on("error", (err) => {
+ readable.emit("error", err);
+ });
+
+ return readable;
+}
+
export function emptyReadable(): Readable {
const readable = new Readable();
readable._read = () => { }; // avoid crash in console
return readable;
}
-
-/**
- * Duplicate a readble stream for multiple consumers
- */
-export function duplicateStream(stream: Readable): [Readable, Readable] {
- const pass1 = new PassThrough();
- const pass2 = new PassThrough();
-
- stream.pipe(pass1)
- stream.pipe(pass2)
-
- return [pass1, pass2];
-} |
8275bed33fd75dcc2f1c7ebcd1e7ba08b3cbb9f5 | tests/cases/fourslash/completionListInImportClause05.ts | tests/cases/fourslash/completionListInImportClause05.ts | /// <reference path='fourslash.ts' />
// @Filename: app.ts
//// import * as A from "[|/*1*/|]";
// @Filename: /node_modules/@types/a__b/index.d.ts
////declare module "@e/f" { function fun(): string; }
// @Filename: /node_modules/@types/c__d/index.d.ts
////export declare let x: number;
const [replacementSpan] = test.ranges();
verify.completionsAt("1", [
{ name: "@a/b", replacementSpan },
{ name: "@c/d", replacementSpan },
{ name: "@e/f", replacementSpan },
]);
| /// <reference path='fourslash.ts' />
// @Filename: app.ts
//// import * as A from "[|/*1*/|]";
// @Filename: /node_modules/@types/a__b/index.d.ts
////declare module "@e/f" { function fun(): string; }
// @Filename: /node_modules/@types/c__d/index.d.ts
////export declare let x: number;
// NOTE: When performing completion, the "current directory" appears to be "/",
// which is well above "." (i.e. the directory containing "app.ts"). This issue
// is specific to the virtual file system, so just work around it by putting the
// node modules folder in "/", rather than ".".
const [replacementSpan] = test.ranges();
verify.completionsAt("1", [
{ name: "@a/b", replacementSpan },
{ name: "@c/d", replacementSpan },
{ name: "@e/f", replacementSpan },
]);
| Add comment explaining test-only workaround | Add comment explaining test-only workaround
| TypeScript | apache-2.0 | SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,basarat/TypeScript,microsoft/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,kpreisser/TypeScript,kitsonk/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,Microsoft/TypeScript,basarat/TypeScript,minestarks/TypeScript,weswigham/TypeScript,weswigham/TypeScript,donaldpipowitch/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,kpreisser/TypeScript,minestarks/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,basarat/TypeScript,alexeagle/TypeScript,nojvek/TypeScript,nojvek/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript | ---
+++
@@ -9,6 +9,11 @@
// @Filename: /node_modules/@types/c__d/index.d.ts
////export declare let x: number;
+// NOTE: When performing completion, the "current directory" appears to be "/",
+// which is well above "." (i.e. the directory containing "app.ts"). This issue
+// is specific to the virtual file system, so just work around it by putting the
+// node modules folder in "/", rather than ".".
+
const [replacementSpan] = test.ranges();
verify.completionsAt("1", [
{ name: "@a/b", replacementSpan }, |
9d5db080c1679375b7cb9b4a5465b0427138073f | resources/assets/lib/beatmap-discussions/system-post.tsx | resources/assets/lib/beatmap-discussions/system-post.tsx | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import StringWithComponent from 'components/string-with-component';
import BeatmapsetDiscussionPostJson from 'interfaces/beatmapset-discussion-post-json';
import UserJson from 'interfaces/user-json';
import { route } from 'laroute';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
interface Props {
post: BeatmapsetDiscussionPostJson;
user: UserJson;
}
export default function SystemPost({ post, user }: Props) {
if (!post.system) return null;
if (post.message.type !== 'resolved') {
console.error(`unknown type: ${post.message.type}`);
}
const className = classWithModifiers('beatmap-discussion-system-post', post.message.type, {
deleted: post.deleted_at != null,
});
return (
<div className={className}>
<div className='beatmap-discussion-system-post__content'>
{post.message.type === 'resolved' && (
<StringWithComponent
mappings={{
user: <a
className='beatmap-discussion-system-post__user'
href={route('users.show', { user: user.id })}
>
{user.username}
</a>,
}}
pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
/>
)}
</div>
</div>
);
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
import StringWithComponent from 'components/string-with-component';
import BeatmapsetDiscussionPostJson from 'interfaces/beatmapset-discussion-post-json';
import UserJson from 'interfaces/user-json';
import { route } from 'laroute';
import * as React from 'react';
import { classWithModifiers } from 'utils/css';
interface Props {
post: BeatmapsetDiscussionPostJson;
user: UserJson;
}
export default function SystemPost({ post, user }: Props) {
if (!post.system) return null;
if (post.message.type !== 'resolved') return null;
const className = classWithModifiers('beatmap-discussion-system-post', post.message.type, {
deleted: post.deleted_at != null,
});
return (
<div className={className}>
<div className='beatmap-discussion-system-post__content'>
<StringWithComponent
mappings={{
user: <a
className='beatmap-discussion-system-post__user'
href={route('users.show', { user: user.id })}
>
{user.username}
</a>,
}}
pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
/>
</div>
</div>
);
}
| Revert "render blank content for unknown types" | Revert "render blank content for unknown types"
This reverts commit 3459caadd2a8f4b2ad08b323f77ca2d4570f34bb.
| TypeScript | agpl-3.0 | notbakaneko/osu-web,ppy/osu-web,nanaya/osu-web,nanaya/osu-web,nanaya/osu-web,ppy/osu-web,nanaya/osu-web,notbakaneko/osu-web,ppy/osu-web,notbakaneko/osu-web,notbakaneko/osu-web,ppy/osu-web,notbakaneko/osu-web,nanaya/osu-web,ppy/osu-web | ---
+++
@@ -15,9 +15,7 @@
export default function SystemPost({ post, user }: Props) {
if (!post.system) return null;
- if (post.message.type !== 'resolved') {
- console.error(`unknown type: ${post.message.type}`);
- }
+ if (post.message.type !== 'resolved') return null;
const className = classWithModifiers('beatmap-discussion-system-post', post.message.type, {
deleted: post.deleted_at != null,
@@ -26,19 +24,17 @@
return (
<div className={className}>
<div className='beatmap-discussion-system-post__content'>
- {post.message.type === 'resolved' && (
- <StringWithComponent
- mappings={{
- user: <a
- className='beatmap-discussion-system-post__user'
- href={route('users.show', { user: user.id })}
- >
- {user.username}
- </a>,
- }}
- pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
- />
- )}
+ <StringWithComponent
+ mappings={{
+ user: <a
+ className='beatmap-discussion-system-post__user'
+ href={route('users.show', { user: user.id })}
+ >
+ {user.username}
+ </a>,
+ }}
+ pattern={osu.trans(`beatmap_discussions.system.resolved.${post.message.value}`)}
+ />
</div>
</div>
); |
b7aac2de70fc0c1cf5159bf3bd6b5ecb3c956b4c | tooling/vite/vite-plugin-svg.ts | tooling/vite/vite-plugin-svg.ts | import { createFilter, FilterPattern } from '@rollup/pluginutils';
import fs from 'fs';
import { basename } from 'path';
const { readFile } = fs.promises;
interface Options {
include?: FilterPattern;
exclude?: FilterPattern;
}
async function transformSVG(path) {
const name = basename(path, '.svg');
const src = (await readFile(path, { encoding: 'utf-8' })).trim();
return `import { setAttributes } from '/overture/dom.js';
const src = \`${src}\`;
let cachedNode = null;
const ${name} = (props) => {
if (!cachedNode) {
cachedNode = new DOMParser().parseFromString(src, 'image/svg+xml').firstChild;
cachedNode.setAttribute('role', 'presentation');
// IE11 does not support classList on SVG
// SVG does not have a className property
cachedNode.setAttribute(
'class',
(cachedNode.getAttribute('class') || '') +
' v-Icon i-${name.toLowerCase()}'
);
}
const svg = cachedNode.cloneNode(true);
setAttributes(svg, props);
return svg;
}
export { ${name} };
`;
export default function raw(options: Options = {}) {
const filter = createFilter(options.include, options.exclude);
return {
test({ path }) {
return filter(path) && path.endsWith('.svg');
},
async transform({ path }) {
return await transformSVG(path);
},
};
}
| import { createFilter, FilterPattern } from '@rollup/pluginutils';
import fs from 'fs';
import { basename } from 'path';
const { readFile } = fs.promises;
interface Options {
include?: FilterPattern;
exclude?: FilterPattern;
}
async function transformSVG(path) {
const name = basename(path, '.svg');
const src = (await readFile(path, { encoding: 'utf-8' })).trim();
return `import { setAttributes } from '/overture/dom.js';
const src = \`${src}\`;
let cachedNode = null;
const ${name} = (props) => {
if (!cachedNode) {
cachedNode = new DOMParser().parseFromString(src, 'image/svg+xml').firstChild;
cachedNode.setAttribute('role', 'presentation');
// IE11 does not support classList on SVG
// SVG does not have a className property
cachedNode.setAttribute(
'class',
(cachedNode.getAttribute('class') || '') +
' v-Icon i-${name.toLowerCase()}'
);
}
const svg = cachedNode.cloneNode(true);
setAttributes(svg, props);
return svg;
}
export { ${name} };
`;
}
export default function raw(options: Options = {}) {
const filter = createFilter(options.include, options.exclude);
return {
test({ path }) {
return filter(path) && path.endsWith('.svg');
},
async transform({ path }) {
return await transformSVG(path);
},
};
}
| Fix vite plugin syntax error | Fix vite plugin syntax error
| TypeScript | mit | fastmail/overture | ---
+++
@@ -36,6 +36,7 @@
export { ${name} };
`;
+}
export default function raw(options: Options = {}) {
const filter = createFilter(options.include, options.exclude); |
c9e8f8f2bdd47536a0b25f6c1be778ff2d186b7d | src/app/index.tsx | src/app/index.tsx | import React from 'react';
import ReactDOM from 'react-dom';
import { injectGlobal } from 'styled-components';
import wpm from 'wexond-package-manager';
import { typography } from 'nersent-ui';
// Components
import App from './components/App';
// Models
import PluginAPI from './models/plugin-api';
import Store from './store';
injectGlobal`
body {
user-select: none;
cursor: default;
${typography.body1()}
margin: 0;
padding: 0;
}
`;
wpm.list().then((plugins) => {
for (const plugin of plugins) {
wpm.run(plugin.namespace).then((pkg) => {
const api = pkg as PluginAPI;
if (api.theme.toolbar != null) {
Store.theme.toolbar = {
...Store.theme.toolbar,
...api.theme.toolbar,
};
}
if (api.theme.accentColor != null) {
Store.theme.accentColor = api.theme.accentColor;
}
});
}
});
ReactDOM.render(<App />, document.getElementById('app'));
| import React from 'react';
import ReactDOM from 'react-dom';
import { injectGlobal } from 'styled-components';
import wpm from 'wexond-package-manager';
import { typography } from 'nersent-ui';
// Components
import App from './components/App';
// Models
import PluginAPI from './models/plugin-api';
import Store from './store';
injectGlobal`
body {
user-select: none;
cursor: default;
${typography.body1()}
margin: 0;
padding: 0;
}
`;
wpm.list().then((plugins) => {
for (const plugin of plugins) {
wpm.run(plugin.namespace).then((pkg) => {
const api = pkg as PluginAPI;
if (api.theme.toolbar != null) {
Store.theme.toolbar = {
...Store.theme.toolbar,
...api.theme.toolbar,
};
}
if (api.theme.searchBar != null) {
Store.theme.searchBar = {
...Store.theme.searchBar,
...api.theme.searchBar,
};
}
if (api.theme.accentColor != null) {
Store.theme.accentColor = api.theme.accentColor;
}
});
}
});
ReactDOM.render(<App />, document.getElementById('app'));
| Fix changing background of search bar | :ambulance: Fix changing background of search bar
| TypeScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -34,6 +34,13 @@
};
}
+ if (api.theme.searchBar != null) {
+ Store.theme.searchBar = {
+ ...Store.theme.searchBar,
+ ...api.theme.searchBar,
+ };
+ }
+
if (api.theme.accentColor != null) {
Store.theme.accentColor = api.theme.accentColor;
} |
da564d3b66ccdf60df4ff812ac1ddf7eeb9777fc | web/src/app/modules/shared/services/electron/electron.service.ts | web/src/app/modules/shared/services/electron/electron.service.ts | /*
* Copyright (c) 2020 the Octant contributors. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ElectronService {
constructor() {}
/**
* Returns true if electron is detected
*/
isElectron(): boolean {
return (
process && process.versions && process.versions.electron !== undefined
);
}
/**
* Returns the platform.
* * Returns linux, darwin, or win32 for those platforms
* * Returns unknown if the platform is not linux, darwin, or win32
* * Returns a blank string is electron is not detected
*
*/
platform(): string {
if (!this.isElectron()) {
return '';
}
switch (process.platform) {
case 'linux':
case 'darwin':
case 'win32':
return process.platform;
default:
return 'unknown';
}
}
}
| /*
* Copyright (c) 2020 the Octant contributors. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ElectronService {
constructor() {}
/**
* Returns true if electron is detected
*/
isElectron(): boolean {
if (typeof process === 'undefined') {
return false;
}
return (
process && process.versions && process.versions.electron !== undefined
);
}
/**
* Returns the platform.
* * Returns linux, darwin, or win32 for those platforms
* * Returns unknown if the platform is not linux, darwin, or win32
* * Returns a blank string is electron is not detected
*
*/
platform(): string {
if (!this.isElectron()) {
return '';
}
switch (process.platform) {
case 'linux':
case 'darwin':
case 'win32':
return process.platform;
default:
return 'unknown';
}
}
}
| Check if running electron via user agent | Check if running electron via user agent
Signed-off-by: GuessWhoSamFoo <[email protected]>
| TypeScript | apache-2.0 | vmware/octant,vmware/octant,vmware/octant,vmware/octant,vmware/octant | ---
+++
@@ -15,6 +15,9 @@
* Returns true if electron is detected
*/
isElectron(): boolean {
+ if (typeof process === 'undefined') {
+ return false;
+ }
return (
process && process.versions && process.versions.electron !== undefined
); |
c7a61a03fe3cebd8b7e35d22fe19c1ad11d22d82 | components/CodeBlock.tsx | components/CodeBlock.tsx | import React, { PureComponent } from "react"
import { PrismLight } from "react-syntax-highlighter"
import swift from "react-syntax-highlighter/dist/cjs/languages/prism/swift"
import prismStyle from "react-syntax-highlighter/dist/cjs/styles/prism/a11y-dark"
PrismLight.registerLanguage("swift", swift)
interface Props {
value: string
language?: string
}
class CodeBlock extends PureComponent<Props> {
render(): JSX.Element {
const { language, value } = this.props
return (
<PrismLight language={language} style={prismStyle}>
{value}
</PrismLight>
)
}
}
export default CodeBlock
| import React, { PureComponent } from "react"
import { PrismLight } from "react-syntax-highlighter"
import swift from "react-syntax-highlighter/dist/cjs/languages/prism/swift"
import prismStyle from "react-syntax-highlighter/dist/cjs/styles/prism/a11y-dark"
PrismLight.registerLanguage("swift", swift)
interface Props {
value: string
language?: string
}
class CodeBlock extends PureComponent<Props> {
render(): JSX.Element {
const { language, value } = this.props
return (
<PrismLight
language={language}
style={prismStyle}
customStyle={{
"color-scheme": "dark",
}}
>
{value}
</PrismLight>
)
}
}
export default CodeBlock
| Improve scrollbar colours for code blocks | Improve scrollbar colours for code blocks
| TypeScript | mit | JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk,JosephDuffy/josephduffy.co.uk | ---
+++
@@ -14,7 +14,13 @@
render(): JSX.Element {
const { language, value } = this.props
return (
- <PrismLight language={language} style={prismStyle}>
+ <PrismLight
+ language={language}
+ style={prismStyle}
+ customStyle={{
+ "color-scheme": "dark",
+ }}
+ >
{value}
</PrismLight>
) |
4788656b172b6b332a51fef1edcd8e5b3258e6ca | src/interfaces.ts | src/interfaces.ts | /**
* Interfaces and types
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
/**
* A timepoint. We only use weeks as of now.
*/
export type Timepoint = {
year: number
week: number
}
/**
* Type of time point
*/
export type Point = 'regular-week' | 'mmwr-week' | 'biweek'
/**
* Range of numbers
*/
export type Range = [number, number] | [string, string] | any[]
/**
* X, Y position as tuple
*/
export type Position = [number, number]
/**
* Event
*/
export type Event = string
| /**
* Interfaces and types
*/
/**
* Doc guard
*/
import * as d3 from 'd3'
/**
* A timepoint. We only use weeks as of now.
*/
export type Timepoint = {
year: number
week?: number,
biweek?: number
}
/**
* Type of time point
*/
export type Point = 'regular-week' | 'mmwr-week' | 'biweek'
/**
* Range of numbers
*/
export type Range = [number, number] | [string, string] | any[]
/**
* X, Y position as tuple
*/
export type Position = [number, number]
/**
* Event
*/
export type Event = string
| Add biweek key in timepoint | Add biweek key in timepoint
| TypeScript | mit | reichlab/d3-foresight,reichlab/d3-foresight | ---
+++
@@ -13,7 +13,8 @@
*/
export type Timepoint = {
year: number
- week: number
+ week?: number,
+ biweek?: number
}
/** |
9d4ede2f482d8123b9bdd31a860d28ed66870cce | lib/config.ts | lib/config.ts | export default {
sc: 'stocazzo',
routes: {
root: {
value: 'stocazzo',
big: 'gran',
},
caps: {
value: 'STOCAZZO',
big: 'GRAN',
},
camel: {
value: 'StoCazzo',
big: 'Gran',
},
ascii: {
value: '8====D',
big: '===',
},
snake: {
value: 'sto_cazzo',
big: '_gran',
},
'sto-conte': {
value: 'Sto cazzo!',
big: ' gran',
},
},
};
| export default {
sc: 'stocazzo',
routes: {
root: {
value: 'stocazzo',
big: 'gran',
},
caps: {
value: 'STOCAZZO',
big: 'GRAN',
},
camel: {
value: 'StoCazzo',
big: 'Gran',
},
ascii: {
value: '8====D',
big: '===',
},
snake: {
value: 'sto_cazzo',
big: '_gran',
},
'sto-conte': {
value: 'Sto cazzo!',
big: ' gran',
},
varg: {
value: '𝔖𝔗𝔒ℭ𝔄ℨℨ𝔒',
big: '𝕾𝕿𝕺𝕮𝕬𝖅𝖅𝕺',
},
},
};
| Add varg to stocazzies list | Add varg to stocazzies list
| TypeScript | mit | dottorblaster/stocazzo,dottorblaster/stocazzo | ---
+++
@@ -25,5 +25,9 @@
value: 'Sto cazzo!',
big: ' gran',
},
+ varg: {
+ value: '𝔖𝔗𝔒ℭ𝔄ℨℨ𝔒',
+ big: '𝕾𝕿𝕺𝕮𝕬𝖅𝖅𝕺',
+ },
},
}; |
5555c644b68006901a4fb48ce452d3cf3d6eaa22 | src/client/app/types/items.ts | src/client/app/types/items.ts | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { ChartTypes } from '../types/redux/graph';
import { LanguageTypes } from '../types/i18n';
/**
* The type of options displayed in Select components.
*/
export interface SelectOption {
label: string;
value: number;
}
/**
* An item with a name and ID number.
*/
export interface NamedIDItem {
id: number;
name: string;
}
/**
* An item that is the result of a preference request
*/
export interface PreferenceRequestItem {
displayTitle: string;
defaultChartToRender: ChartTypes;
defaultBarStacking: boolean;
defaultLanguage: LanguageTypes;
}
/**
* A collection of items giving a label to an item in a dataset, by index
*/
export interface TooltipItems {
datasetIndex: number;
yLabel: string;
[i: number]: {
xLabel: string;
};
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { ChartTypes } from '../types/redux/graph';
import { LanguageTypes } from '../types/i18n';
/**
* The type of options displayed in Select components.
*/
export interface SelectOption {
label: string;
value: number;
}
/**
* An item with a name and ID number.
*/
export interface NamedIDItem {
id: number;
name: string;
}
/**
* An item that is the result of a preference request
*/
export interface PreferenceRequestItem {
displayTitle: string;
defaultChartToRender: ChartTypes;
defaultBarStacking: boolean;
defaultLanguage: LanguageTypes;
}
/**
* A collection of items giving a label to an item in a dataset, by index
*/
export interface TooltipItems {
datasetIndex: number;
yLabel: string;
[i: number]: {
xLabel: string;
};
}
/**
* A user object to be displayed for Administrators.
*/
export interface User {
email: string;
role: string;
} | Add User type for React | Add User type for React
| TypeScript | mpl-2.0 | OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED | ---
+++
@@ -41,3 +41,11 @@
xLabel: string;
};
}
+
+/**
+ * A user object to be displayed for Administrators.
+ */
+export interface User {
+ email: string;
+ role: string;
+} |
d9be3abc77532b7bb5576bd7670e2cd35ef7f3ac | packages/codeeditor/src/mimetype.ts | packages/codeeditor/src/mimetype.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
nbformat
} from '@jupyterlab/services';
/**
* The mime type service of a code editor.
*/
export
interface IEditorMimeTypeService {
/**
* Get a mime type for the given language info.
*
* @param info - The language information.
*
* @returns A valid mimetype.
*
* #### Notes
* If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
*/
getMimeTypeByLanguage(info: nbformat.ILanguageInfoMetadata): string;
/**
* Get a mime type for the given file path.
*
* @param filePath - The full path to the file.
*
* @returns A valid mimetype.
*
* #### Notes
* If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
*/
getMimeTypeByFilePath(filePath: string): string;
}
/**
* A namespace for `IEditorMimeTypeService`.
*/
export
namespace IEditorMimeTypeService {
/**
* The default mime type.
*/
export
const defaultMimeType: string = 'text/plain';
}
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
nbformat
} from '@jupyterlab/coreutils';
/**
* The mime type service of a code editor.
*/
export
interface IEditorMimeTypeService {
/**
* Get a mime type for the given language info.
*
* @param info - The language information.
*
* @returns A valid mimetype.
*
* #### Notes
* If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
*/
getMimeTypeByLanguage(info: nbformat.ILanguageInfoMetadata): string;
/**
* Get a mime type for the given file path.
*
* @param filePath - The full path to the file.
*
* @returns A valid mimetype.
*
* #### Notes
* If a mime type cannot be found returns the defaul mime type `text/plain`, never `null`.
*/
getMimeTypeByFilePath(filePath: string): string;
}
/**
* A namespace for `IEditorMimeTypeService`.
*/
export
namespace IEditorMimeTypeService {
/**
* The default mime type.
*/
export
const defaultMimeType: string = 'text/plain';
}
| Use services nbformat in codeeditor | Use services nbformat in codeeditor
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -3,7 +3,7 @@
import {
nbformat
-} from '@jupyterlab/services';
+} from '@jupyterlab/coreutils';
/** |
cc9e070e8794547f3ea0c44976f517a3ba32efa7 | test/src/index.ts | test/src/index.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import './common/activitymonitor.spec';
import './common/observablelist.spec';
import './dialog/dialog.spec';
import './docregistry/default.spec';
import './docregistry/registry.spec';
import './filebrowser/model.spec';
import './markdownwidget/widget.spec';
import './renderers/renderers.spec';
import './renderers/latex.spec';
import './rendermime/rendermime.spec';
import './notebook/cells/editor.spec';
import './notebook/cells/model.spec';
import './notebook/cells/widget.spec';
import './notebook/completion/handler.spec';
import './notebook/completion/model.spec';
import './notebook/completion/widget.spec';
import './notebook/notebook/actions.spec';
import './notebook/notebook/default-toolbar.spec';
import './notebook/notebook/model.spec';
import './notebook/notebook/modelfactory.spec';
import './notebook/notebook/nbformat.spec';
import './notebook/notebook/panel.spec';
import './notebook/notebook/toolbar.spec';
import './notebook/notebook/trust.spec';
import './notebook/notebook/widget.spec';
import './notebook/notebook/widgetfactory.spec';
import './notebook/output-area/model.spec';
import './notebook/output-area/widget.spec';
| // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import './common/activitymonitor.spec';
import './common/observablelist.spec';
import './dialog/dialog.spec';
import './docregistry/default.spec';
import './docregistry/registry.spec';
import './filebrowser/model.spec';
import './markdownwidget/widget.spec';
import './renderers/renderers.spec';
import './renderers/latex.spec';
import './rendermime/rendermime.spec';
import './notebook/cells/editor.spec';
import './notebook/cells/model.spec';
import './notebook/cells/widget.spec';
import './notebook/completion/handler.spec';
import './notebook/completion/model.spec';
import './notebook/completion/widget.spec';
import './notebook/notebook/actions.spec';
import './notebook/notebook/default-toolbar.spec';
import './notebook/notebook/model.spec';
import './notebook/notebook/modelfactory.spec';
import './notebook/notebook/nbformat.spec';
import './notebook/notebook/panel.spec';
import './notebook/notebook/toolbar.spec';
import './notebook/notebook/trust.spec';
import './notebook/notebook/widget.spec';
import './notebook/notebook/widgetfactory.spec';
import './notebook/output-area/model.spec';
import './notebook/output-area/widget.spec';
import 'phosphor/styles/base.css';
| Add phosphor base styles for testing | Add phosphor base styles for testing
| TypeScript | bsd-3-clause | jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,eskirk/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -39,3 +39,5 @@
import './notebook/output-area/model.spec';
import './notebook/output-area/widget.spec';
+
+import 'phosphor/styles/base.css'; |
8bf8b4143b1c6bdcdaec6742f754044fc22e6ae6 | src/openstack/openstack-tenant/TenantPortsList.tsx | src/openstack/openstack-tenant/TenantPortsList.tsx | import * as React from 'react';
import { Table, connectTable, createFetcher } from '@waldur/table';
const TableComponent = (props) => {
const { translate } = props;
return (
<Table
{...props}
columns={[
{
title: translate('IPv4 address'),
render: ({ row }) => row.ip4_address || 'N/A',
},
{
title: translate('MAC address'),
render: ({ row }) => row.mac_address,
},
{
title: translate('Network name'),
render: ({ row }) => row.network_name,
},
]}
verboseName={translate('ports')}
/>
);
};
const TableOptions = {
table: 'openstack-ports',
fetchData: createFetcher('openstack-ports'),
mapPropsToFilter: (props) => ({
tenant_uuid: props.resource.uuid,
o: 'network_name',
}),
};
export const TenantPortsList = connectTable(TableOptions)(TableComponent);
| import * as React from 'react';
import { Table, connectTable, createFetcher } from '@waldur/table';
const TableComponent = (props) => {
const { translate } = props;
return (
<Table
{...props}
columns={[
{
title: translate('IPv4 address'),
render: ({ row }) => row.ip4_address || 'N/A',
},
{
title: translate('MAC address'),
render: ({ row }) => row.mac_address || 'N/A',
},
{
title: translate('Network name'),
render: ({ row }) => row.network_name || 'N/A',
},
]}
verboseName={translate('ports')}
/>
);
};
const TableOptions = {
table: 'openstack-ports',
fetchData: createFetcher('openstack-ports'),
mapPropsToFilter: (props) => ({
tenant_uuid: props.resource.uuid,
o: 'network_name',
}),
};
export const TenantPortsList = connectTable(TableOptions)(TableComponent);
| Fix tenant ports rendering if network name is not defined. | Fix tenant ports rendering if network name is not defined.
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -14,11 +14,11 @@
},
{
title: translate('MAC address'),
- render: ({ row }) => row.mac_address,
+ render: ({ row }) => row.mac_address || 'N/A',
},
{
title: translate('Network name'),
- render: ({ row }) => row.network_name,
+ render: ({ row }) => row.network_name || 'N/A',
},
]}
verboseName={translate('ports')} |
8a84606155852fe89b32b2b07895be41e8794959 | src/components/Queue/QueueTable.tsx | src/components/Queue/QueueTable.tsx | import * as React from 'react';
import { SearchMap } from '../../types';
import { Card, ResourceList, Stack, Button } from '@shopify/polaris';
import EmptyQueue from './EmptyQueue';
import QueueItem from './QueueItem';
export interface Props {
readonly queue: SearchMap;
}
export interface Handlers {
readonly onRefresh: () => void;
}
const QueueTable = ({ queue, onRefresh }: Props & Handlers) => {
return queue.isEmpty() ? (
<EmptyQueue onRefresh={onRefresh} />
) : (
<Stack vertical>
<Card sectioned>
<Button>Refresh queue.</Button>
</Card>
<Card>
<ResourceList
items={queue.toArray()}
renderItem={hit => <QueueItem hit={hit} />}
/>
</Card>
</Stack>
);
};
export default QueueTable;
| import * as React from 'react';
import { SearchMap } from '../../types';
import { Card, ResourceList, Stack, Button } from '@shopify/polaris';
import EmptyQueue from './EmptyQueue';
import QueueItem from './QueueItem';
export interface Props {
readonly queue: SearchMap;
}
export interface Handlers {
readonly onRefresh: () => void;
}
const QueueTable = ({ queue, onRefresh }: Props & Handlers) => {
return queue.isEmpty() ? (
<EmptyQueue onRefresh={onRefresh} />
) : (
<Stack vertical>
<Card sectioned>
<Button onClick={onRefresh}>Refresh queue.</Button>
</Card>
<Card>
<ResourceList
items={queue.toArray()}
renderItem={hit => <QueueItem hit={hit} />}
/>
</Card>
</Stack>
);
};
export default QueueTable;
| Fix issue of refresh queue button not refreshing queue. | Fix issue of refresh queue button not refreshing queue.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -18,7 +18,7 @@
) : (
<Stack vertical>
<Card sectioned>
- <Button>Refresh queue.</Button>
+ <Button onClick={onRefresh}>Refresh queue.</Button>
</Card>
<Card>
<ResourceList |
faf84db9cb34c539b7b005d7d50410112b41b4d9 | lib/sdkVersion.ts | lib/sdkVersion.ts | import { version } from '../package.json'
export const sdkVersionHeader = 'javascript-{$version}';
| import { version } from '../package.json'
export const sdkVersionHeader = `javascript-${version}`;
| Fix issue with string formatting | Fix issue with string formatting
| TypeScript | mit | procore/js-sdk | ---
+++
@@ -1,3 +1,3 @@
import { version } from '../package.json'
-export const sdkVersionHeader = 'javascript-{$version}';
+export const sdkVersionHeader = `javascript-${version}`; |
ed7358bb6d5fe38c1bb7539100c768421ad408af | src/app/leaflet-tile-selector/leaflet-tile-selector.component.ts | src/app/leaflet-tile-selector/leaflet-tile-selector.component.ts | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { LeafletTileProviderService } from '../leaflet-tile-provider.service';
@Component({
selector: 'app-leaflet-tile-selector',
templateUrl: './leaflet-tile-selector.component.html',
styleUrls: ['./leaflet-tile-selector.component.sass']
})
export class LeafletTileSelectorComponent implements OnInit {
@Input() map:any;
@Output() tileChange: EventEmitter<string> = new EventEmitter<string>();
public tileKeys: any;
constructor(private tileProvider: LeafletTileProviderService) {}
ngOnInit() {
this.tileKeys = Object.keys(this.tileProvider.baseMaps);
}
onTileChange(event) {
this.tileChange.emit(event.target.value);
}
}
| import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { Store } from '@ngrx/store';
import { LeafletTileProviderService } from '../leaflet-tile-provider.service';
@Component({
selector: 'app-leaflet-tile-selector',
templateUrl: './leaflet-tile-selector.component.html',
styleUrls: ['./leaflet-tile-selector.component.sass']
})
export class LeafletTileSelectorComponent implements OnInit, AfterViewInit {
@Input() map:any;
@Output() tileChange: EventEmitter<string> = new EventEmitter<string>();
public tileKeys: any;
constructor(
public store: Store<any>,
private element: ElementRef,
private tileProvider: LeafletTileProviderService
) {}
ngOnInit() {
this.tileKeys = Object.keys(this.tileProvider.baseMaps);
}
ngAfterViewInit() {
let selectEl = this.element.nativeElement.querySelector('#map-tile-selector');
// TODO: unsuscribe once it fired once already
this.store
.select('map')
.subscribe((state: any) => {
if (state.tileProvider !== null && selectEl !== null && selectEl.value !== state.tileProvider) {
console.log('trigger');
selectEl.value = state.tileProvider;
}
})
;
}
onTileChange(event) {
this.tileChange.emit(event.target.value);
}
}
| Add subscriber to reflect the currently selected map tile provider | Add subscriber to reflect the currently selected map tile provider
| TypeScript | mit | ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-ng2,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps,ecsnavarretemit/sarai-interactive-maps | ---
+++
@@ -1,4 +1,5 @@
-import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
+import { Component, OnInit, AfterViewInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
+import { Store } from '@ngrx/store';
import { LeafletTileProviderService } from '../leaflet-tile-provider.service';
@Component({
@@ -6,16 +7,36 @@
templateUrl: './leaflet-tile-selector.component.html',
styleUrls: ['./leaflet-tile-selector.component.sass']
})
-export class LeafletTileSelectorComponent implements OnInit {
+export class LeafletTileSelectorComponent implements OnInit, AfterViewInit {
@Input() map:any;
@Output() tileChange: EventEmitter<string> = new EventEmitter<string>();
public tileKeys: any;
- constructor(private tileProvider: LeafletTileProviderService) {}
+ constructor(
+ public store: Store<any>,
+ private element: ElementRef,
+ private tileProvider: LeafletTileProviderService
+ ) {}
ngOnInit() {
this.tileKeys = Object.keys(this.tileProvider.baseMaps);
+ }
+
+ ngAfterViewInit() {
+ let selectEl = this.element.nativeElement.querySelector('#map-tile-selector');
+
+ // TODO: unsuscribe once it fired once already
+ this.store
+ .select('map')
+ .subscribe((state: any) => {
+ if (state.tileProvider !== null && selectEl !== null && selectEl.value !== state.tileProvider) {
+ console.log('trigger');
+
+ selectEl.value = state.tileProvider;
+ }
+ })
+ ;
}
onTileChange(event) { |
3c5905848f9b167d714f434f5bf7fafed264abf0 | 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);
console.log(findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
}));
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);
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/ng-steroids,wishtack/wishtack-steroids,wishtack/wishtack-steroids,wishtack/ng-steroids | ---
+++
@@ -11,10 +11,12 @@
const project = getProject(tree, options.project);
- console.log(findModuleFromOptions(tree, {
+ const modulePath = findModuleFromOptions(tree, {
...options,
path: options.path || buildDefaultPath(project)
- }));
+ });
+
+ tree.read(modulePath);
return tree;
|
b68e47e16ea2c57d8c822bdfcc265774924c20d2 | packages/password/src/is-common.util.ts | packages/password/src/is-common.util.ts | // std
import { readFile } from 'fs';
import { join } from 'path';
import { promisify } from 'util';
import { gunzip } from 'zlib';
let list: string[];
/**
* Test if a password belongs to a list of 10k common passwords.
*
* @export
* @param {string} password - The password to test.
* @returns {Promise<boolean>} - True if the password is found in the list. False otherwise.
*/
export async function isCommon(password: string): Promise<boolean> {
if (!list) {
const fileContent = await promisify(readFile)(join(__dirname, './10-million-password-list-top-10000.txt.gz'));
list = (await promisify(gunzip)(fileContent)).toString().split('\n');
}
return list.includes(password);
}
| // std
import { readFile } from 'fs';
import { join } from 'path';
import { promisify } from 'util';
import { gunzip, InputType } from 'zlib';
let list: string[];
/**
* Test if a password belongs to a list of 10k common passwords.
*
* @export
* @param {string} password - The password to test.
* @returns {Promise<boolean>} - True if the password is found in the list. False otherwise.
*/
export async function isCommon(password: string): Promise<boolean> {
if (!list) {
const fileContent = await promisify(readFile)(join(__dirname, './10-million-password-list-top-10000.txt.gz'));
list = (await promisify<InputType, Buffer>(gunzip)(fileContent)).toString().split('\n');
}
return list.includes(password);
}
| Fix type error due to TSv3 | Fix type error due to TSv3
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -2,7 +2,7 @@
import { readFile } from 'fs';
import { join } from 'path';
import { promisify } from 'util';
-import { gunzip } from 'zlib';
+import { gunzip, InputType } from 'zlib';
let list: string[];
@@ -16,7 +16,7 @@
export async function isCommon(password: string): Promise<boolean> {
if (!list) {
const fileContent = await promisify(readFile)(join(__dirname, './10-million-password-list-top-10000.txt.gz'));
- list = (await promisify(gunzip)(fileContent)).toString().split('\n');
+ list = (await promisify<InputType, Buffer>(gunzip)(fileContent)).toString().split('\n');
}
return list.includes(password);
} |
cae38202562d857f472383031f42dcbc6831ebc2 | packages/socket.io/src/errors/convert-error-to-websocket-response.ts | packages/socket.io/src/errors/convert-error-to-websocket-response.ts | // 3p
import { Config } from '@foal/core';
// FoalTS
import { ISocketIOController, WebsocketContext, WebsocketErrorResponse, WebsocketResponse } from '../architecture';
import { renderWebsocketError } from './render-websocket-error';
export async function convertErrorToWebsocketResponse(
error: Error, ctx: WebsocketContext, socketIOController: ISocketIOController, log = console.error
): Promise<WebsocketResponse | WebsocketErrorResponse> {
if (Config.get('settings.logErrors', 'boolean', true)) {
log(error.stack);
}
if (socketIOController.handleError) {
try {
return await socketIOController.handleError(error, ctx);
} catch (error2) {
return renderWebsocketError(error2, ctx);
}
}
return renderWebsocketError(error, ctx);
}
| // 3p
import { Config } from '@foal/core';
// FoalTS
import { ISocketIOController, WebsocketContext, WebsocketErrorResponse, WebsocketResponse } from '../architecture';
import { renderWebsocketError } from './render-websocket-error';
export async function convertErrorToWebsocketResponse(
error: Error, ctx: WebsocketContext, socketIOController: ISocketIOController, log = console.error
): Promise<WebsocketResponse | WebsocketErrorResponse> {
if (Config.get('settings.logErrors', 'boolean', true)) {
log(error.stack);
}
if (socketIOController.handleError) {
try {
return await socketIOController.handleError(error, ctx);
} catch (error2: any) {
return renderWebsocketError(error2, ctx);
}
}
return renderWebsocketError(error, ctx);
}
| Fix socket.io to support strict [email protected] | Fix socket.io to support strict [email protected]
| TypeScript | mit | FoalTS/foal,FoalTS/foal,FoalTS/foal,FoalTS/foal | ---
+++
@@ -15,7 +15,7 @@
if (socketIOController.handleError) {
try {
return await socketIOController.handleError(error, ctx);
- } catch (error2) {
+ } catch (error2: any) {
return renderWebsocketError(error2, ctx);
}
} |
6db9e61a0bad22e89a435a626f39a9a8039ee8f3 | src/vs/workbench/contrib/notebook/browser/constants.ts | src/vs/workbench/contrib/notebook/browser/constants.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Scrollable Element
export const SCROLLABLE_ELEMENT_PADDING_TOP = 16;
// Cell sizing related
export const CELL_MARGIN = 20;
export const CELL_RUN_GUTTER = 32;
export const EDITOR_TOOLBAR_HEIGHT = 0;
export const BOTTOM_CELL_TOOLBAR_HEIGHT = 36;
export const CELL_STATUSBAR_HEIGHT = 22;
// Top margin of editor
export const EDITOR_TOP_MARGIN = 0;
// Top and bottom padding inside the monaco editor in a cell, which are included in `cell.editorHeight`
export const EDITOR_TOP_PADDING = 12;
export const EDITOR_BOTTOM_PADDING = 12;
| /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Scrollable Element
export const SCROLLABLE_ELEMENT_PADDING_TOP = 20;
// Cell sizing related
export const CELL_MARGIN = 20;
export const CELL_RUN_GUTTER = 32;
export const EDITOR_TOOLBAR_HEIGHT = 0;
export const BOTTOM_CELL_TOOLBAR_HEIGHT = 36;
export const CELL_STATUSBAR_HEIGHT = 22;
// Top margin of editor
export const EDITOR_TOP_MARGIN = 0;
// Top and bottom padding inside the monaco editor in a cell, which are included in `cell.editorHeight`
export const EDITOR_TOP_PADDING = 12;
export const EDITOR_BOTTOM_PADDING = 12;
| Increase top-padding for first cell toolbar | Increase top-padding for first cell toolbar
| TypeScript | mit | Microsoft/vscode,hoovercj/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,microsoft/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,hoovercj/vscode,hoovercj/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,microsoft/vscode,hoovercj/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,hoovercj/vscode,hoovercj/vscode,microsoft/vscode,Microsoft/vscode,Microsoft/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,eamodio/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,Microsoft/vscode,hoovercj/vscode,eamodio/vscode,Microsoft/vscode,hoovercj/vscode,eamodio/vscode,eamodio/vscode,Microsoft/vscode,Microsoft/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,hoovercj/vscode,eamodio/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microsoft/vscode,eamodio/vscode,Microsoft/vscode,eamodio/vscode,hoovercj/vscode,eamodio/vscode | ---
+++
@@ -5,7 +5,7 @@
// Scrollable Element
-export const SCROLLABLE_ELEMENT_PADDING_TOP = 16;
+export const SCROLLABLE_ELEMENT_PADDING_TOP = 20;
// Cell sizing related
export const CELL_MARGIN = 20; |
351fdc15c74a069a55a5b3b7cb1c4566c28c115a | app/scripts/components/appstore/providers/support/SankeyDiagram.tsx | app/scripts/components/appstore/providers/support/SankeyDiagram.tsx | import * as React from 'react';
import { ReactNode } from 'react';
import loadEcharts from '../../../../shims/load-echarts';
interface SankeyDiagramProps {
data: any;
}
export default class SankeyDiagram extends React.Component<SankeyDiagramProps> {
container: ReactNode;
diagram = undefined;
getChartsOptions() {
return {
series: {
type: 'sankey',
layout: 'none',
data: this.props.data.data,
links: this.props.data.links,
},
};
}
renderDiagram() {
const options = this.getChartsOptions();
this.diagram.setOption(options);
}
drawDiagram() {
loadEcharts().then(module => {
const echarts = module.default;
const diagram = echarts.getInstanceByDom(this.container);
if (!diagram) {
this.diagram = echarts.init(this.container, );
}
this.renderDiagram();
});
}
componentDidMount() {
this.drawDiagram();
}
componentWillUnmount() {
this.diagram.dispose();
}
render() {
return (
<div id="sankey-diagram" ref={container => this.container = container} />
);
}
}
| import * as React from 'react';
import { ReactNode } from 'react';
import loadEcharts from '../../../../shims/load-echarts';
interface SankeyDiagramProps {
data: any;
}
export default class SankeyDiagram extends React.Component<SankeyDiagramProps> {
container: ReactNode;
diagram = undefined;
getChartsOptions() {
return {
series: {
type: 'sankey',
layout: 'none',
data: this.props.data.data,
links: this.props.data.links,
},
tooltip: {
trigger: 'item',
triggerOn: 'mousemove'
},
};
}
renderDiagram() {
const options = this.getChartsOptions();
this.diagram.setOption(options);
}
drawDiagram() {
loadEcharts().then(module => {
const echarts = module.default;
const diagram = echarts.getInstanceByDom(this.container);
if (!diagram) {
this.diagram = echarts.init(this.container, );
}
this.renderDiagram();
});
}
componentDidMount() {
this.drawDiagram();
}
componentWillUnmount() {
this.diagram.dispose();
}
render() {
return (
<div id="sankey-diagram" ref={container => this.container = container} />
);
}
}
| Enable tooltips for Sankey diagrams | Enable tooltips for Sankey diagrams
| TypeScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -19,6 +19,10 @@
data: this.props.data.data,
links: this.props.data.links,
},
+ tooltip: {
+ trigger: 'item',
+ triggerOn: 'mousemove'
+ },
};
}
|
6fc6e3e285f5c51147571c02f91cfb0661e6a418 | packages/oidc-provider/src/index.ts | packages/oidc-provider/src/index.ts | export * from "./decorators";
export * from "./domain";
export * from "./services/OidcAdapters";
export * from "./services/OidcInteractions";
export * from "./services/OidcInteractionContext";
export * from "./services/OidcJwks";
export * from "./services/OidcProvider";
export * from "./OidcModule";
| export * from "./decorators";
export * from "./domain";
export * from "./middlewares/OidcInteractionMiddleware";
export * from "./middlewares/OidcNoCacheMiddleware";
export * from "./middlewares/OidcSecureMiddleware";
export * from "./services/OidcAdapters";
export * from "./services/OidcInteractions";
export * from "./services/OidcInteractionContext";
export * from "./services/OidcJwks";
export * from "./services/OidcProvider";
export * from "./OidcModule";
| Add missing import on oidc-provider module | fix(oidc): Add missing import on oidc-provider module
| TypeScript | mit | Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators,Romakita/ts-express-decorators | ---
+++
@@ -1,8 +1,15 @@
export * from "./decorators";
+
export * from "./domain";
+
+export * from "./middlewares/OidcInteractionMiddleware";
+export * from "./middlewares/OidcNoCacheMiddleware";
+export * from "./middlewares/OidcSecureMiddleware";
+
export * from "./services/OidcAdapters";
export * from "./services/OidcInteractions";
export * from "./services/OidcInteractionContext";
export * from "./services/OidcJwks";
export * from "./services/OidcProvider";
+
export * from "./OidcModule"; |
739379b0f1e30922d699d68f600c415fddcf77fe | src/Components/Artwork/__tests__/FillwidthItem.test.tsx | src/Components/Artwork/__tests__/FillwidthItem.test.tsx | import { render } from "enzyme"
import React from "react"
import { FillwidthItem } from "../FillwidthItem"
describe("FillwidthItem", () => {
// This scenario _should not_ happen. But it did. Every artwork should have
// an image, but somehow one snuck through in production and broke pages.
describe("No image associated with an artwork", () => {
it("Doesn't blow up when there is no image associated with an artwork", () => {
const artwork = {
" $fragmentRefs": null,
href: "my/artwork",
}
// @ts-ignore
const wrapper = render(<FillwidthItem artwork={artwork} />)
expect(wrapper.html()).toBeNull()
})
})
})
| import { render } from "enzyme"
import React from "react"
import { FillwidthItem } from "../FillwidthItem"
describe("FillwidthItem", () => {
// This scenario _should not_ happen. But it did. Every artwork should have
// an image, but somehow one snuck through in production and broke pages.
describe("No image associated with an artwork", () => {
it("Doesn't blow up when there is no image associated with an artwork", () => {
const artwork = {
" $fragmentRefs": null,
href: "my/artwork",
}
const wrapper = render(<FillwidthItem artwork={artwork as any} />)
expect(wrapper.html()).toBeNull()
})
})
})
| Use a smaller hammer to pass an invalid artwork (without an image) to FillwidthItem | Use a smaller hammer to pass an invalid artwork (without an image) to FillwidthItem
| TypeScript | mit | xtina-starr/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction,xtina-starr/reaction,xtina-starr/reaction,artsy/reaction,xtina-starr/reaction,artsy/reaction | ---
+++
@@ -12,8 +12,7 @@
href: "my/artwork",
}
- // @ts-ignore
- const wrapper = render(<FillwidthItem artwork={artwork} />)
+ const wrapper = render(<FillwidthItem artwork={artwork as any} />)
expect(wrapper.html()).toBeNull()
}) |
2d10af8984f217ecab62f5d14f32dc4e5d8f78fe | src/test/Apha/Serialization/SerializerDecorator.spec.ts | src/test/Apha/Serialization/SerializerDecorator.spec.ts |
import "reflect-metadata";
import {expect} from "chai";
import {Serializer} from "../../../main/Apha/Serialization/SerializerDecorator";
describe("SerializerDecorator", () => {
describe("Ignore", () => {
it("registers a property to be ignored during (de-)serialization", () => {
let target = new SerializerDecoratorSpecClassIgnore();
let ignores = Reflect.getMetadata(Serializer.IGNORE_SERIALIZATION_PROPERTIES, target);
expect(ignores).to.have.lengthOf(1);
expect(ignores[0]).to.eql("bar");
});
});
describe("Serializable", () => {
it("inspects a (complex) property for correct (de-)serialization", () => {
let target = new SerializerDecoratorSpecClassSerializable();
let serializables = Reflect.getMetadata(Serializer.SERIALIZABLE_PROPERTIES, target);
expect(serializables["bar"]).to.eql({
primaryType: SerializerDecoratorSpecClassIgnore
});
});
});
});
class SerializerDecoratorSpecClassIgnore {
private foo: string;
@Serializer.Ignore()
private bar: string;
}
class SerializerDecoratorSpecClassSerializable {
private foo: string;
@Serializer.Serializable()
private bar: SerializerDecoratorSpecClassIgnore;
}
|
import "reflect-metadata";
import {expect} from "chai";
import {Serializer} from "../../../main/Apha/Serialization/SerializerDecorator";
import {DecoratorException} from "../../../main/Apha/Decorators/DecoratorException";
describe("SerializerDecorator", () => {
describe("Ignore", () => {
it("registers a property to be ignored during (de-)serialization", () => {
let target = new SerializerDecoratorSpecClassIgnore();
let ignores = Reflect.getMetadata(Serializer.IGNORE_SERIALIZATION_PROPERTIES, target);
expect(ignores).to.have.lengthOf(1);
expect(ignores[0]).to.eql("bar");
});
it("throws exception if no property name was passed", () => {
let target = new SerializerDecoratorSpecClassSerializable();
expect(() => {
Serializer.Ignore()(target, undefined);
}).to.throw(DecoratorException);
});
});
describe("Serializable", () => {
it("inspects a (complex) property for correct (de-)serialization", () => {
let target = new SerializerDecoratorSpecClassSerializable();
let serializables = Reflect.getMetadata(Serializer.SERIALIZABLE_PROPERTIES, target);
expect(serializables["bar"]).to.eql({
primaryType: SerializerDecoratorSpecClassIgnore
});
});
it("throws exception if no property name was passed", () => {
let target = new SerializerDecoratorSpecClassIgnore();
expect(() => {
Serializer.Serializable()(target, undefined);
}).to.throw(DecoratorException);
});
});
});
class SerializerDecoratorSpecClassIgnore {
private foo: string;
@Serializer.Ignore()
private bar: string;
}
class SerializerDecoratorSpecClassSerializable {
private foo: string;
@Serializer.Serializable()
private bar: SerializerDecoratorSpecClassIgnore;
}
| Extend test with exceptional cases. | Extend test with exceptional cases.
| TypeScript | mit | martyn82/aphajs | ---
+++
@@ -2,6 +2,7 @@
import "reflect-metadata";
import {expect} from "chai";
import {Serializer} from "../../../main/Apha/Serialization/SerializerDecorator";
+import {DecoratorException} from "../../../main/Apha/Decorators/DecoratorException";
describe("SerializerDecorator", () => {
describe("Ignore", () => {
@@ -11,6 +12,14 @@
expect(ignores).to.have.lengthOf(1);
expect(ignores[0]).to.eql("bar");
+ });
+
+ it("throws exception if no property name was passed", () => {
+ let target = new SerializerDecoratorSpecClassSerializable();
+
+ expect(() => {
+ Serializer.Ignore()(target, undefined);
+ }).to.throw(DecoratorException);
});
});
@@ -22,6 +31,14 @@
expect(serializables["bar"]).to.eql({
primaryType: SerializerDecoratorSpecClassIgnore
});
+ });
+
+ it("throws exception if no property name was passed", () => {
+ let target = new SerializerDecoratorSpecClassIgnore();
+
+ expect(() => {
+ Serializer.Serializable()(target, undefined);
+ }).to.throw(DecoratorException);
});
});
}); |
e154b80023b4a7d21548914be2683371af34d976 | angular/projects/spark-angular/src/lib/directives/sprk-box/sprk-box.stories.ts | angular/projects/spark-angular/src/lib/directives/sprk-box/sprk-box.stories.ts | import { storyWrapper } from '../../../../../../.storybook/helpers/storyWrapper';
import { SprkBoxDirective } from './sprk-box.directive';
import { SprkBoxModule } from './sprk-box.module';
import { markdownDocumentationLinkBuilder } from '../../../../../../../storybook-utilities/markdownDocumentationLinkBuilder';
export default {
title: "Components/Box",
component: SprkBoxDirective,
decorators: [storyWrapper(storyContent => `<div class="sprk-o-Box sb-decorate">${storyContent}<div>`)],
parameters: {
info: `
${markdownDocumentationLinkBuilder('box')}
Box is a layout component that separates a group of content from its surroundings.
Use Box when you have a group of content that needs to be visually separated from other content on the page through padding.
Since the effects of Box are only seen through whitespace, the examples have a background color to illustrate how Box works.
Box has built in padding sizes that are paired with our Spacing values. Otherwise, it will default to medium spacing.
Refer to [Class Modifiers section](#class-modifiers) for default values.
`,
docs: { iframeHeight: 100 }
}
};
const modules = {
imports: [
SprkBoxModule,
],
};
export const defaultBox = () => ({
moduleMetadata: modules,
template: `
<div sprkBox>
Box
</div>
`,
});
defaultBox.story = {
name: 'Default'
};
| import { storyWrapper } from '../../../../../../.storybook/helpers/storyWrapper';
import { SprkBoxDirective } from './sprk-box.directive';
import { SprkBoxModule } from './sprk-box.module';
import { markdownDocumentationLinkBuilder } from '../../../../../../../storybook-utilities/markdownDocumentationLinkBuilder';
export default {
title: "Components/Box",
component: SprkBoxDirective,
decorators: [storyWrapper(storyContent => `<div class="sprk-o-Box sb-decorate">${storyContent}<div>`)],
parameters: {
info: `
${markdownDocumentationLinkBuilder('box')}
Box is a layout component that separates a group of content from its surroundings.
Use Box when you have a group of content that needs to be visually separated from other content on the page through padding.
Since the effects of Box are only seen through whitespace, the examples have a background color to illustrate how Box works.
Box has built in padding sizes that are paired with our Spacing values. Otherwise, it will default to medium spacing.
Refer to [Class Modifiers section](#class-modifiers) for default pixel values.
`,
docs: { iframeHeight: 100 }
}
};
const modules = {
imports: [
SprkBoxModule,
],
};
export const defaultBox = () => ({
moduleMetadata: modules,
template: `
<div sprkBox>
Box
</div>
`,
});
defaultBox.story = {
name: 'Default'
};
| Add "pixel" to last sentence for clarity | Add "pixel" to last sentence for clarity
| TypeScript | mit | sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system | ---
+++
@@ -18,8 +18,7 @@
Box has built in padding sizes that are paired with our Spacing values. Otherwise, it will default to medium spacing.
-Refer to [Class Modifiers section](#class-modifiers) for default values.
-
+Refer to [Class Modifiers section](#class-modifiers) for default pixel values.
`,
docs: { iframeHeight: 100 }
} |
a23b3640b726c7182e68b3683f78d8725f97f0b0 | step-release-vis/src/app/components/form/dataSubmissionForm_test.ts | step-release-vis/src/app/components/form/dataSubmissionForm_test.ts | import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {FormComponent} from './dataSubmissionForm';
import {FormBuilder, FormsModule, ReactiveFormsModule} from '@angular/forms';
describe('FormComponent', () => {
let component: FormComponent;
let fixture: ComponentFixture<FormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule],
declarations: [FormComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {DataSubmissionFormComponent} from './dataSubmissionForm';
import {FormBuilder, FormsModule, ReactiveFormsModule} from '@angular/forms';
describe('DataSumbissionFormComponent', () => {
let component: DataSubmissionFormComponent;
let fixture: ComponentFixture<DataSubmissionFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule],
declarations: [DataSubmissionFormComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DataSubmissionFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| Change component name in test file. | Change component name in test file.
| TypeScript | apache-2.0 | googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020,googleinterns/step251-2020 | ---
+++
@@ -1,21 +1,21 @@
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
-import {FormComponent} from './dataSubmissionForm';
+import {DataSubmissionFormComponent} from './dataSubmissionForm';
import {FormBuilder, FormsModule, ReactiveFormsModule} from '@angular/forms';
-describe('FormComponent', () => {
- let component: FormComponent;
- let fixture: ComponentFixture<FormComponent>;
+describe('DataSumbissionFormComponent', () => {
+ let component: DataSubmissionFormComponent;
+ let fixture: ComponentFixture<DataSubmissionFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule],
- declarations: [FormComponent],
+ declarations: [DataSubmissionFormComponent],
}).compileComponents();
}));
beforeEach(() => {
- fixture = TestBed.createComponent(FormComponent);
+ fixture = TestBed.createComponent(DataSubmissionFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}); |
f82eaefa3c3d6331709af1c9ed3eead96c11a39c | browser/io/FileAPI.ts | browser/io/FileAPI.ts | ///<lib="es6-promise"/>
module ghost.browser.io
{
export class FileAPI
{
public static loadFile(input:HTMLInputElement)
{
var promise:Promise<ProgressEvent> = new Promise<ProgressEvent>((resolve:(value:ProgressEvent)=>void, reject:(error:ErrorEvent|Error)=>void)=>
{
var file = input.files[0];
if(!file)
{
input.addEventListener("change", ()=>
{
this.loadFile(input).then(resolve, reject);
});
return;
}
var textType = /.*javascript/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
resolve(<ProgressEvent>e);
// fileDisplayArea.innerText = reader.result;
}
reader.onerror = function(e)
{
reject(e);
}
reader.readAsText(file);
} else {
reject(new Error( "format not readable"));
//fileDisplayArea.innerText = "File not supported!"
}
});
return promise;
}
}
}
| ///<lib="es6-promise"/>
module ghost.browser.io
{
export class FileAPI
{
public static loadFile(input:HTMLInputElement)
{
var promise:Promise<ProgressEvent> = new Promise<ProgressEvent>((resolve:(value:ProgressEvent)=>void, reject:(error:ErrorEvent|Error)=>void)=>
{
var file = input.files[0];
if(!file)
{
input.addEventListener("change", ()=>
{
this.loadFile(input).then(resolve, reject);
});
return;
}
var textType = /.*javascript/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
resolve(<ProgressEvent>e);
// fileDisplayArea.innerText = reader.result;
}
reader.onerror = function(e)
{
reject(e);
}
reader.readAsText(file);
} else {
reject(new Error( "format not readable: "+file.type));
//fileDisplayArea.innerText = "File not supported!"
}
});
return promise;
}
}
}
| Add file type to the error message | Add file type to the error message
| TypeScript | mit | mymyoux/Typescript-Ghost-framework | ---
+++
@@ -33,7 +33,7 @@
}
reader.readAsText(file);
} else {
- reject(new Error( "format not readable"));
+ reject(new Error( "format not readable: "+file.type));
//fileDisplayArea.innerText = "File not supported!"
}
|
50000c5c0a8fcf5fa2d8555a7b2da51406110cfd | src/button/index.ts | src/button/index.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
export * from './button';
@NgModule({
imports: [
CommonModule,
],
declarations: [
TlButton
],
exports: [
TlButton
]
})
export class ButtonModule {}
| import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
import { TabIndexService } from "../form/tabIndex.service";
import { IdGeneratorService } from "../core/helper/idgenerator.service";
import { NameGeneratorService } from "../core/helper/namegenerator.service";
@NgModule({
imports: [
CommonModule,
],
declarations: [
TlButton
],
exports: [
TlButton
],
providers: [
TabIndexService,
IdGeneratorService,
NameGeneratorService
]
})
export class ButtonModule {}
| Add providers services of component default to button. | refactor(button): Add providers services of component default to button.
| TypeScript | mit | TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui,TemainfoSistemas/truly-ui | ---
+++
@@ -2,8 +2,9 @@
import { CommonModule } from '@angular/common';
import { TlButton } from './button';
-
-export * from './button';
+import { TabIndexService } from "../form/tabIndex.service";
+import { IdGeneratorService } from "../core/helper/idgenerator.service";
+import { NameGeneratorService } from "../core/helper/namegenerator.service";
@NgModule({
imports: [
@@ -14,6 +15,11 @@
],
exports: [
TlButton
+ ],
+ providers: [
+ TabIndexService,
+ IdGeneratorService,
+ NameGeneratorService
]
})
export class ButtonModule {} |
cc7b7e5ac7e90e5857d98ffb1dae655dee64124e | lib/components/src/Loader/Loader.tsx | lib/components/src/Loader/Loader.tsx | import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { rotate360 } from '../shared/animation';
const LoaderWrapper = styled.div<{ size?: number }>(({ size = 32 }) => ({
borderRadius: '3em',
cursor: 'progress',
display: 'inline-block',
overflow: 'hidden',
position: 'absolute',
transition: 'all 200ms ease-out',
verticalAlign: 'top',
top: '50%',
left: '50%',
marginTop: -(size / 2),
marginLeft: -(size / 2),
height: size,
width: size,
zIndex: 4,
borderWidth: 2,
borderStyle: 'solid',
borderColor: 'rgba(97, 97, 97, 0.29)',
borderTopColor: 'rgb(100,100,100)',
animation: `${rotate360} 0.7s linear infinite`,
mixBlendMode: 'difference',
}));
export const Loader: FunctionComponent<ComponentProps<typeof LoaderWrapper>> = props => (
<LoaderWrapper aria-label="Content is loading ..." aria-live="polite" role="status" {...props} />
);
| import React, { FunctionComponent, ComponentProps } from 'react';
import { styled } from '@storybook/theming';
import { rotate360 } from '../shared/animation';
const LoaderWrapper = styled.div<{ size?: number }>(({ size = 32 }) => ({
borderRadius: '50%',
cursor: 'progress',
display: 'inline-block',
overflow: 'hidden',
position: 'absolute',
transition: 'all 200ms ease-out',
verticalAlign: 'top',
top: '50%',
left: '50%',
marginTop: -(size / 2),
marginLeft: -(size / 2),
height: size,
width: size,
zIndex: 4,
borderWidth: 2,
borderStyle: 'solid',
borderColor: 'rgba(97, 97, 97, 0.29)',
borderTopColor: 'rgb(100,100,100)',
animation: `${rotate360} 0.7s linear infinite`,
mixBlendMode: 'difference',
}));
export const Loader: FunctionComponent<ComponentProps<typeof LoaderWrapper>> = props => (
<LoaderWrapper aria-label="Content is loading ..." aria-live="polite" role="status" {...props} />
);
| CHANGE loader to always be round | CHANGE loader to always be round
| TypeScript | mit | kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -3,7 +3,7 @@
import { rotate360 } from '../shared/animation';
const LoaderWrapper = styled.div<{ size?: number }>(({ size = 32 }) => ({
- borderRadius: '3em',
+ borderRadius: '50%',
cursor: 'progress',
display: 'inline-block',
overflow: 'hidden', |
8d30209aab6ed1f060debf8688f7ad62359ea75d | gerrit-ng-ui/app/header.component.ts | gerrit-ng-ui/app/header.component.ts | /**
* Created by josh on 12/12/15.
*/
import {Component} from 'angular2/core';
import {Menu} from './menu'
@Component({
selector: 'header-component',
template:`
<menu></menu>
<h1>Main page for Gerrit review.</h1>
`,
directives: [Menu]
})
export class HeaderComponent {
}
| /**
* Created by josh on 12/12/15.
*/
import {Component} from 'angular2/core';
import {Menu} from './menu'
@Component({
selector: 'header-component',
template:`
<img src="./img/Eclipse-logo-2014.svg">
<menu></menu>
<h1>Main page for Gerrit review.</h1>
`,
directives: [Menu]
})
export class HeaderComponent {
}
| Add the Eclipse logo to the header. | Add the Eclipse logo to the header.
| TypeScript | apache-2.0 | MerritCR/merrit,MerritCR/merrit,MerritCR/merrit,MerritCR/merrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,joshuawilson/merrit,MerritCR/merrit,joshuawilson/merrit,joshuawilson/merrit | ---
+++
@@ -7,6 +7,7 @@
@Component({
selector: 'header-component',
template:`
+ <img src="./img/Eclipse-logo-2014.svg">
<menu></menu>
<h1>Main page for Gerrit review.</h1>
`, |
18c43c13a95a44d820d9ade48aa25a10712f9f83 | src/app/examples/stock-market/stock-market.service.spec.ts | src/app/examples/stock-market/stock-market.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { CoreModule } from '@app/core';
import { StockMarketService } from './stock-market.service';
describe('StockMarketService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule, CoreModule],
providers: [StockMarketService]
});
});
it(
'should be created',
inject([StockMarketService], (service: StockMarketService) => {
expect(service).toBeTruthy();
})
);
});
| import { TestBed, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { CoreModule } from '@app/core';
import { StockMarketService } from './stock-market.service';
describe('StockMarketService', () => {
let httpClientSpy: { get: jasmine.Spy };
beforeEach(() => {
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
TestBed.configureTestingModule({
imports: [RouterTestingModule, CoreModule],
providers: [
StockMarketService,
{ provide: HttpClient, useValue: httpClientSpy }
]
});
});
it(
'should be created',
inject([StockMarketService], (service: StockMarketService) => {
expect(service).toBeTruthy();
})
);
it(
'should return expected result',
inject([StockMarketService], (service: StockMarketService) => {
const expectedStock: any = {
symbol: 'TSLA',
primaryExchange: 'Nasdaq Global Select',
latestPrice: 284.96,
change: -9.88,
changePercent: -0.03351
};
httpClientSpy.get.and.returnValue(of(expectedStock));
service
.retrieveStock('TS')
.subscribe(stock => expect(stock).toBeTruthy(), fail);
expect(httpClientSpy.get.calls.count()).toBe(1, 'called once');
})
);
it(
'should return error when server returns 404',
inject([StockMarketService], (service: StockMarketService) => {
const errorResponse = new HttpErrorResponse({
error: 'call expected error',
statusText: 'Not Found',
status: 404
});
httpClientSpy.get.and.returnValue(of(errorResponse));
service
.retrieveStock('TS')
.subscribe(
() => fail('expected an error'),
error => expect(error).not.toBeUndefined()
);
})
);
});
| Add unit-tests for stock-market service | test(stock-market): Add unit-tests for stock-market service | TypeScript | mit | tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter,tomastrajan/angular-ngrx-material-starter | ---
+++
@@ -1,15 +1,24 @@
import { TestBed, inject } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
+import { HttpClient, HttpErrorResponse } from '@angular/common/http';
+import { of } from 'rxjs';
import { CoreModule } from '@app/core';
import { StockMarketService } from './stock-market.service';
describe('StockMarketService', () => {
+ let httpClientSpy: { get: jasmine.Spy };
+
beforeEach(() => {
+ httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
+
TestBed.configureTestingModule({
imports: [RouterTestingModule, CoreModule],
- providers: [StockMarketService]
+ providers: [
+ StockMarketService,
+ { provide: HttpClient, useValue: httpClientSpy }
+ ]
});
});
@@ -19,4 +28,44 @@
expect(service).toBeTruthy();
})
);
+
+ it(
+ 'should return expected result',
+ inject([StockMarketService], (service: StockMarketService) => {
+ const expectedStock: any = {
+ symbol: 'TSLA',
+ primaryExchange: 'Nasdaq Global Select',
+ latestPrice: 284.96,
+ change: -9.88,
+ changePercent: -0.03351
+ };
+
+ httpClientSpy.get.and.returnValue(of(expectedStock));
+
+ service
+ .retrieveStock('TS')
+ .subscribe(stock => expect(stock).toBeTruthy(), fail);
+
+ expect(httpClientSpy.get.calls.count()).toBe(1, 'called once');
+ })
+ );
+
+ it(
+ 'should return error when server returns 404',
+ inject([StockMarketService], (service: StockMarketService) => {
+ const errorResponse = new HttpErrorResponse({
+ error: 'call expected error',
+ statusText: 'Not Found',
+ status: 404
+ });
+ httpClientSpy.get.and.returnValue(of(errorResponse));
+
+ service
+ .retrieveStock('TS')
+ .subscribe(
+ () => fail('expected an error'),
+ error => expect(error).not.toBeUndefined()
+ );
+ })
+ );
}); |
b49fcb411150e2c74405a4fd5493a0b9abe20d88 | src/pages/edit-goal/edit-goal.ts | src/pages/edit-goal/edit-goal.ts | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { User } from '../../providers/user';
@Component({
selector: 'page-edit-goal',
templateUrl: 'edit-goal.html'
})
export class EditGoalPage {
public goal: any;
constructor(
public storage: Storage,
public user: User,
public navParams: NavParams,
public navcontroller: NavController
){}
ionViewDidEnter() {
this.goal = this.navParams.data;
console.log(this.goal);
}
confirm(formData){
console.log(formData)
let goal = {
slug: formData.slug,
title: formData.goaltitle,
gunit: formData.gunits,
goalval: formData.goalval,
}
this.user.editGoal(goal);
}
cancel(){
this.navcontroller.pop();
}
} | import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { User } from '../../providers/user';
@Component({
selector: 'page-edit-goal',
templateUrl: 'edit-goal.html'
})
export class EditGoalPage {
goal: any
constructor(
public storage: Storage,
public user: User,
public navParams: NavParams,
public navcontroller: NavController
){}
ngOnInit() {
this.goal = this.navParams.data;
}
confirm(){
console.log(this.goal)
let goal = {
slug: this.goal.slug,
title: this.goal.title,
gunit: this.goal.runits, //There isn't a gunit variable?
goalval: this.goal.goalval,
}
this.user.editGoal(goal);
this.navcontroller.pop();
}
cancel(){
this.navcontroller.pop();
}
} | Fix some undefined errors when loading the page | Fix some undefined errors when loading the page
| TypeScript | mit | beeminder-capstone/Nectar-Frontend,beeminder-capstone/Nectar-Frontend,beeminder-capstone/Nectar-Frontend | ---
+++
@@ -12,7 +12,7 @@
})
export class EditGoalPage {
- public goal: any;
+ goal: any
constructor(
public storage: Storage,
@@ -21,22 +21,22 @@
public navcontroller: NavController
){}
- ionViewDidEnter() {
+ ngOnInit() {
this.goal = this.navParams.data;
- console.log(this.goal);
}
- confirm(formData){
- console.log(formData)
+ confirm(){
+ console.log(this.goal)
let goal = {
- slug: formData.slug,
- title: formData.goaltitle,
- gunit: formData.gunits,
- goalval: formData.goalval,
+ slug: this.goal.slug,
+ title: this.goal.title,
+ gunit: this.goal.runits, //There isn't a gunit variable?
+ goalval: this.goal.goalval,
}
this.user.editGoal(goal);
+ this.navcontroller.pop();
}
cancel(){ |
443d724a33f1e4c4215dc30278c98c2dc3cee6f7 | src/ts/app.ts | src/ts/app.ts | import { Component } from "angular2/angular2";
@Component({
selector: 'app',
template: `
<h1>My Angular2 Base App</h1>
`
})
export class AppComponent { }
| import { Component } from 'angular2/angular2';
@Component({
selector: 'app',
template: `
<h1>My Angular2 Base App</h1>
`
})
export class AppComponent { }
| Replace double quotes with single quotes. | Replace double quotes with single quotes.
| TypeScript | mit | kiswa/angular2-base,kiswa/angular2-base,kiswa/angular2-base | ---
+++
@@ -1,4 +1,4 @@
-import { Component } from "angular2/angular2";
+import { Component } from 'angular2/angular2';
@Component({
selector: 'app', |
21d2715b0cedb1e9d762a4f85e0fe724692ef1b2 | docs/_constants.ts | docs/_constants.ts | export const CODESANDBOX_EXAMPLE_ID = 'q9l2j10wr4';
export const HOST_URL = 'https://material-ui-pickers.dev';
export const LOGO_URL = HOST_URL + '/static/meta-image.png';
export const GITHUB_EDIT_URL =
'https://github.com/dmtrKovalenko/material-ui-pickers/edit/develop/docs/';
| export const CODESANDBOX_EXAMPLE_ID = 'o7oojxx1pq';
export const HOST_URL = 'https://material-ui-pickers.dev';
export const LOGO_URL = HOST_URL + '/static/meta-image.png';
export const GITHUB_EDIT_URL =
'https://github.com/dmtrKovalenko/material-ui-pickers/edit/develop/docs/';
| Update usage codesandbox to the vnext | Update usage codesandbox to the vnext | TypeScript | mit | oliviertassinari/material-ui,mbrookes/material-ui,dmtrKovalenko/material-ui-pickers,mui-org/material-ui,oliviertassinari/material-ui,mui-org/material-ui,mbrookes/material-ui,callemall/material-ui,callemall/material-ui,oliviertassinari/material-ui,mbrookes/material-ui,rscnt/material-ui,rscnt/material-ui,dmtrKovalenko/material-ui-pickers,rscnt/material-ui,callemall/material-ui,mui-org/material-ui,callemall/material-ui | ---
+++
@@ -1,4 +1,4 @@
-export const CODESANDBOX_EXAMPLE_ID = 'q9l2j10wr4';
+export const CODESANDBOX_EXAMPLE_ID = 'o7oojxx1pq';
export const HOST_URL = 'https://material-ui-pickers.dev';
|
3d63385f30cc8c2822651518f34925aa9253e32f | src/app/settings/oauth-apps/oauth-app-modal.component.ts | src/app/settings/oauth-apps/oauth-app-modal.component.ts | import { Component, ChangeDetectorRef } from '@angular/core';
import { OAuthAppListItem } from './oauth-apps.component';
import { OAuthAppStore } from '../../store/oauthApp/oauth-app.store';
import { OAuthApp, OAuthApps } from '../../model';
import { ModalService } from '../../common/modal/modal.service';
@Component({
selector: 'syndesis-oauth-app-modal',
templateUrl: './oauth-app-modal.component.html',
})
export class OAuthAppModalComponent {
// Holds the candidate for clearing credentials
item: OAuthAppListItem;
constructor(
public store: OAuthAppStore,
public detector: ChangeDetectorRef,
private modalService: ModalService,
) {}
show(item: OAuthAppListItem) {
this.item = item;
this.modalService.show()
.then(result => result
? this.removeCredentials()
// TODO toast notification
.then(app => this.item.client = app)
.catch(error => {})
.then(_ => this.detector.markForCheck())
: undefined);
}
// Clear the store credentials for the selected oauth app
removeCredentials() {
const app = this.item.client;
app['clientId'] = '';
app['clientSecret'] = '';
return this.store.update(app).take(1).toPromise();
}
}
| import { Component, ChangeDetectorRef } from '@angular/core';
import { OAuthAppListItem } from './oauth-apps.component';
import { OAuthAppStore } from '../../store/oauthApp/oauth-app.store';
import { OAuthApp, OAuthApps } from '../../model';
import { ModalService } from '../../common/modal/modal.service';
@Component({
selector: 'syndesis-oauth-app-modal',
templateUrl: './oauth-app-modal.component.html',
})
export class OAuthAppModalComponent {
// Holds the candidate for clearing credentials
item: OAuthAppListItem;
constructor(
public store: OAuthAppStore,
public detector: ChangeDetectorRef,
private modalService: ModalService,
) {}
show(item: OAuthAppListItem) {
this.item = item;
this.modalService.show()
.then(result => result
? this.removeCredentials()
// TODO toast notification
.then(app => this.item.client = app)
.catch(error => {})
.then(_ => this.detector.markForCheck())
: undefined);
}
// Clear the store credentials for the selected oauth app
removeCredentials() {
const app = { ...this.item.client, clientId: '', clientSecret: '' };
return this.store.update(app).take(1).toPromise();
}
}
| Clone client settings before update to rollback on error | fix(settings): Clone client settings before update to rollback on error
| TypeScript | apache-2.0 | kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client,kahboom/ipaas-client | ---
+++
@@ -32,9 +32,7 @@
// Clear the store credentials for the selected oauth app
removeCredentials() {
- const app = this.item.client;
- app['clientId'] = '';
- app['clientSecret'] = '';
+ const app = { ...this.item.client, clientId: '', clientSecret: '' };
return this.store.update(app).take(1).toPromise();
}
} |
49c2e2afbb41861b6b51a6af46963da853351ad3 | public/react/hello_react_typescript.tsx | public/react/hello_react_typescript.tsx | /// <reference path="../../typings/react/react.d.ts" />
/// <reference path="../../typings/react-dom/react-dom.d.ts" />
import React = __React;
import ReactDom = __ReactDom;
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
}
});
ReactDom.render(
<CommentBox />,
document.getElementById('content')
);
| /// <reference path="../../typings/react/react.d.ts" />
/// <reference path="../../typings/react-dom/react-dom.d.ts" />
import React = __React;
import ReactDom = __ReactDom;
interface CommentBoxProps extends React.Props<any> {
name: string;
}
class CommentBox extends React.Component<CommentBoxProps, {}> {
output = 'Hello, world! I am ' + this.props.name + '.';
render() {
return <div className="commentBox">{this.output}</div>;
}
};
ReactDom.render(
<CommentBox name='John'/>,
document.getElementById('content')
); | Update for more typescript style. | Update for more typescript style.
| TypeScript | mit | ku-kueihsi/dummy_react,ku-kueihsi/dummy_react,ku-kueihsi/dummy_react | ---
+++
@@ -4,17 +4,18 @@
import React = __React;
import ReactDom = __ReactDom;
-var CommentBox = React.createClass({
- render: function() {
- return (
- <div className="commentBox">
- Hello, world! I am a CommentBox.
- </div>
- );
+interface CommentBoxProps extends React.Props<any> {
+ name: string;
+}
+
+class CommentBox extends React.Component<CommentBoxProps, {}> {
+ output = 'Hello, world! I am ' + this.props.name + '.';
+ render() {
+ return <div className="commentBox">{this.output}</div>;
}
-});
+};
ReactDom.render(
- <CommentBox />,
+ <CommentBox name='John'/>,
document.getElementById('content')
); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.