content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | add missing class annotations xplat/js | ee3d3c248df4e8be3a331ead5f6eea75c1cf237a | <ide><path>IntegrationTests/AccessibilityManagerTest.js
<ide> import * as React from 'react';
<ide> const {TestModule} = NativeModules;
<ide>
<ide> class AccessibilityManagerTest extends React.Component<{...}> {
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> invariant(
<ide> NativeAccessibilityManager,
<ide> "NativeAccessibilityManager doesn't exist",
<ide><path>IntegrationTests/GlobalEvalWithSourceUrlTest.js
<ide> const {View} = ReactNative;
<ide> const {TestModule} = ReactNative.NativeModules;
<ide>
<ide> class GlobalEvalWithSourceUrlTest extends React.Component<{...}> {
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> if (typeof global.globalEvalWithSourceUrl !== 'function') {
<ide> throw new Error(
<ide> 'Expected to find globalEvalWithSourceUrl function on global object but found ' +
<ide><path>IntegrationTests/ImageSnapshotTest.js
<ide> const {Image} = ReactNative;
<ide> const {TestModule} = ReactNative.NativeModules;
<ide>
<ide> class ImageSnapshotTest extends React.Component<{...}> {
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> if (!TestModule.verifySnapshot) {
<ide> throw new Error('TestModule.verifySnapshot not defined.');
<ide> }
<ide><path>IntegrationTests/IntegrationTestsApp.js
<ide> require('./LoggingTestModule');
<ide> type Test = any;
<ide>
<ide> class IntegrationTestsApp extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: {test: ?Test} = {
<ide> test: (null: ?Test),
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> if (this.state.test) {
<ide> return (
<ide> <ScrollView>
<ide><path>IntegrationTests/SimpleSnapshotTest.js
<ide> const {StyleSheet, View} = ReactNative;
<ide> const {TestModule} = ReactNative.NativeModules;
<ide>
<ide> class SimpleSnapshotTest extends React.Component<{...}> {
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> if (!TestModule.verifySnapshot) {
<ide> throw new Error('TestModule.verifySnapshot not defined.');
<ide> }
<ide><path>IntegrationTests/SyncMethodTest.js
<ide> const {View} = ReactNative;
<ide> const {TestModule, RNTesterTestModule} = ReactNative.NativeModules;
<ide>
<ide> class SyncMethodTest extends React.Component<{...}> {
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> if (
<ide> RNTesterTestModule.echoString('test string value') !== 'test string value'
<ide> ) {
<ide><path>IntegrationTests/TimersTest.js
<ide> class TimersTest extends React.Component<Props, State> {
<ide> );
<ide> }
<ide>
<del> _incrementInterval() {
<add> _incrementInterval(): void {
<ide> if (this.state.count > 3) {
<ide> throw new Error('interval incremented past end.');
<ide> }
<ide><path>IntegrationTests/WebSocketTest.js
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide> });
<ide> };
<ide>
<del> _socketIsConnected = () => {
<add> _socketIsConnected = (): boolean => {
<ide> return this.state.socketState === 1; //'OPEN'
<ide> };
<ide>
<del> _socketIsDisconnected = () => {
<add> _socketIsDisconnected = (): boolean => {
<ide> return this.state.socketState === 3; //'CLOSED'
<ide> };
<ide>
<ide> class WebSocketTest extends React.Component<{...}, State> {
<ide> this._sendText(this.state.testMessage);
<ide> };
<ide>
<del> _receivedTestExpectedResponse = () => {
<add> _receivedTestExpectedResponse = (): boolean => {
<ide> return this.state.lastMessage === this.state.testExpectedResponse;
<ide> };
<ide>
<ide><path>Libraries/Animated/AnimatedEvent.js
<ide> class AnimatedEvent {
<ide> this._listeners = this._listeners.filter(listener => listener !== callback);
<ide> }
<ide>
<del> __attach(viewRef: any, eventName: string) {
<add> __attach(viewRef: any, eventName: string): void {
<ide> invariant(
<ide> this.__isNative,
<ide> 'Only native driven events need to be attached.',
<ide> class AnimatedEvent {
<ide> );
<ide> }
<ide>
<del> __detach(viewTag: any, eventName: string) {
<add> __detach(viewTag: any, eventName: string): void {
<ide> invariant(
<ide> this.__isNative,
<ide> 'Only native driven events need to be detached.',
<ide><path>Libraries/Animated/createAnimatedComponent.js
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> // components. If you want to animate a composite component, you need to
<ide> // re-render it. In this case, we have a fallback that uses forceUpdate.
<ide> // This fallback is also called in Fabric.
<del> _animatedPropsCallback = () => {
<add> _animatedPropsCallback = (): void => {
<ide> if (this._component == null) {
<ide> // AnimatedProps is created in will-mount because it's used in render.
<ide> // But this callback may be invoked before mount in async mode,
<ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>(
<ide> }
<ide> }
<ide>
<del> _setComponentRef = setAndForwardRef({
<add> _setComponentRef: (ref: React.ElementRef<any>) => void = setAndForwardRef({
<ide> getForwardedRef: () => this.props.forwardedRef,
<ide> setLocalRef: ref => {
<ide> this._prevComponent = this._component;
<ide> this._component = ref;
<ide> },
<ide> });
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const animatedProps =
<ide> this._propsAnimated.__getValue(this._initialAnimatedProps) || {};
<ide> const {style = {}, ...props} = animatedProps;
<ide><path>Libraries/Animated/nodes/AnimatedNode.js
<ide> class AnimatedNode {
<ide> this._listeners = {};
<ide> }
<ide>
<del> __makeNative(platformConfig: ?PlatformConfig) {
<add> __makeNative(platformConfig: ?PlatformConfig): void {
<ide> if (!this.__isNative) {
<ide> throw new Error('This node cannot be made a "native" animated node');
<ide> }
<ide><path>Libraries/Animated/nodes/AnimatedStyle.js
<ide> class AnimatedStyle extends AnimatedWithChildren {
<ide> }
<ide>
<ide> // Recursively get values for nested styles (like iOS's shadowOffset)
<del> _walkStyleAndGetValues(style: any, initialStyle: ?Object) {
<add> _walkStyleAndGetValues(
<add> style: any,
<add> initialStyle: ?Object,
<add> ): {[string]: any | {...}} {
<ide> const updatedStyle: {[string]: any | {...}} = {};
<ide> for (const key in style) {
<ide> const value = style[key];
<ide> class AnimatedStyle extends AnimatedWithChildren {
<ide> }
<ide>
<ide> // Recursively get animated values for nested styles (like iOS's shadowOffset)
<del> _walkStyleAndGetAnimatedValues(style: any) {
<add> _walkStyleAndGetAnimatedValues(style: any): {[string]: any | {...}} {
<ide> const updatedStyle: {[string]: any | {...}} = {};
<ide> for (const key in style) {
<ide> const value = style[key];
<ide><path>Libraries/BatchedBridge/MessageQueue.js
<ide> class MessageQueue {
<ide> params: mixed[],
<ide> onFail: ?(...mixed[]) => void,
<ide> onSucc: ?(...mixed[]) => void,
<del> ) {
<add> ): void {
<ide> this.processCallbacks(moduleID, methodID, params, onFail, onSucc);
<ide>
<ide> this._queue[MODULE_IDS].push(moduleID);
<ide> class MessageQueue {
<ide> Systrace.endEvent();
<ide> }
<ide>
<del> __invokeCallback(cbID: number, args: mixed[]) {
<add> __invokeCallback(cbID: number, args: mixed[]): void {
<ide> this._lastFlush = Date.now();
<ide> this._eventLoopStartTime = this._lastFlush;
<ide>
<ide><path>Libraries/Blob/FileReader.js
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> }
<ide> }
<ide>
<del> readAsArrayBuffer() {
<add> readAsArrayBuffer(): any {
<ide> throw new Error('FileReader.readAsArrayBuffer is not implemented');
<ide> }
<ide>
<del> readAsDataURL(blob: ?Blob) {
<add> readAsDataURL(blob: ?Blob): void {
<ide> this._aborted = false;
<ide>
<ide> if (blob == null) {
<ide> class FileReader extends (EventTarget(...READER_EVENTS): any) {
<ide> );
<ide> }
<ide>
<del> readAsText(blob: ?Blob, encoding: string = 'UTF-8') {
<add> readAsText(blob: ?Blob, encoding: string = 'UTF-8'): void {
<ide> this._aborted = false;
<ide>
<ide> if (blob == null) {
<ide><path>Libraries/Blob/URL.js
<ide> if (
<ide> // Small subset from whatwg-url: https://github.com/jsdom/whatwg-url/tree/master/src
<ide> // The reference code bloat comes from Unicode issues with URLs, so those won't work here.
<ide> export class URLSearchParams {
<del> _searchParams = [];
<add> _searchParams: Array<Array<string>> = [];
<ide>
<ide> constructor(params: any) {
<ide> if (typeof params === 'object') {
<ide> Object.keys(params).forEach(key => this.append(key, params[key]));
<ide> }
<ide> }
<ide>
<del> append(key: string, value: string) {
<add> append(key: string, value: string): void {
<ide> this._searchParams.push([key, value]);
<ide> }
<ide>
<del> delete(name: string) {
<add> delete(name: string): void {
<ide> throw new Error('URLSearchParams.delete is not implemented');
<ide> }
<ide>
<del> get(name: string) {
<add> get(name: string): void {
<ide> throw new Error('URLSearchParams.get is not implemented');
<ide> }
<ide>
<del> getAll(name: string) {
<add> getAll(name: string): void {
<ide> throw new Error('URLSearchParams.getAll is not implemented');
<ide> }
<ide>
<del> has(name: string) {
<add> has(name: string): void {
<ide> throw new Error('URLSearchParams.has is not implemented');
<ide> }
<ide>
<del> set(name: string, value: string) {
<add> set(name: string, value: string): void {
<ide> throw new Error('URLSearchParams.set is not implemented');
<ide> }
<ide>
<del> sort() {
<add> sort(): void {
<ide> throw new Error('URLSearchParams.sort is not implemented');
<ide> }
<ide>
<ide> // $FlowFixMe[unsupported-syntax]
<add> // $FlowFixMe[missing-local-annot]
<ide> [Symbol.iterator]() {
<ide> return this._searchParams[Symbol.iterator]();
<ide> }
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> class ScrollView extends React.Component<Props, State> {
<ide> }
<ide> }
<ide>
<del> _setNativeRef = setAndForwardRef({
<add> _setNativeRef: $FlowFixMe = setAndForwardRef({
<ide> getForwardedRef: () => this.props.scrollViewRef,
<ide> setLocalRef: ref => {
<ide> this._scrollViewRef = ref;
<ide> class ScrollView extends React.Component<Props, State> {
<ide> }
<ide> };
<ide>
<del> _getKeyForIndex(index: $FlowFixMe, childArray: $FlowFixMe) {
<add> _getKeyForIndex(index: $FlowFixMe, childArray: $FlowFixMe): $FlowFixMe {
<ide> const child = childArray[index];
<ide> return child && child.key;
<ide> }
<ide> class ScrollView extends React.Component<Props, State> {
<ide> _scrollViewRef: ?React.ElementRef<HostComponent<mixed>> = null;
<ide>
<ide> _innerViewRef: ?React.ElementRef<typeof View> = null;
<del> _setInnerViewRef = setAndForwardRef({
<add> _setInnerViewRef: $FlowFixMe = setAndForwardRef({
<ide> getForwardedRef: () => this.props.innerViewRef,
<ide> setLocalRef: ref => {
<ide> this._innerViewRef = ref;
<ide><path>Libraries/Components/StatusBar/StatusBar.js
<ide> function createStackEntry(props: any): any {
<ide> * `currentHeight` (Android only) The height of the status bar.
<ide> */
<ide> class StatusBar extends React.Component<Props> {
<del> static _propsStack = [];
<add> static _propsStack: Array<any> = [];
<ide>
<del> static _defaultProps = createStackEntry({
<add> static _defaultProps: any = createStackEntry({
<ide> backgroundColor:
<ide> Platform.OS === 'android'
<ide> ? NativeStatusBarManagerAndroid.getConstants()
<ide> class StatusBar extends React.Component<Props> {
<ide> * @param color Background color.
<ide> * @param animated Animate the style change.
<ide> */
<del> static setBackgroundColor(color: string, animated?: boolean) {
<add> static setBackgroundColor(color: string, animated?: boolean): void {
<ide> if (Platform.OS !== 'android') {
<ide> console.warn('`setBackgroundColor` is only available on Android');
<ide> return;
<ide><path>Libraries/Inspector/BoxInspector.js
<ide> class BoxInspector extends React.Component<$FlowFixMeProps> {
<ide> }
<ide>
<ide> class BoxContainer extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> const box = this.props.box;
<ide> return (
<ide> <View style={styles.box}>
<ide><path>Libraries/Inspector/InspectorPanel.js
<ide> type InspectorPanelButtonProps = $ReadOnly<{|
<ide> |}>;
<ide>
<ide> class InspectorPanelButton extends React.Component<InspectorPanelButtonProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableHighlight
<ide> onPress={() => this.props.onClick(!this.props.pressed)}
<ide><path>Libraries/Inspector/NetworkOverlay.js
<ide> class NetworkOverlay extends React.Component<Props, State> {
<ide> // scroll to the bottom as new network requests come in, or if the user has
<ide> // intentionally scrolled away from the bottom - to instead flash the scroll bar
<ide> // and keep the current position
<del> _requestsListViewScrollMetrics = {
<add> _requestsListViewScrollMetrics: {
<add> contentLength: number,
<add> offset: number,
<add> visibleLength: number,
<add> } = {
<ide> offset: 0,
<ide> visibleLength: 0,
<ide> contentLength: 0,
<ide> class NetworkOverlay extends React.Component<Props, State> {
<ide> );
<ide> };
<ide>
<del> _renderItemDetail(id: number) {
<add> _renderItemDetail(id: number): React.Node {
<ide> const requestItem = this.state.requests[id];
<ide> const details = Object.keys(requestItem).map(key => {
<ide> if (key === 'id') {
<ide><path>Libraries/Linking/Linking.js
<ide> class Linking extends NativeEventEmitter<LinkingEventDefinitions> {
<ide> }
<ide> }
<ide>
<del> _validateURL(url: string) {
<add> _validateURL(url: string): void {
<ide> invariant(
<ide> typeof url === 'string',
<ide> 'Invalid URL: should be a string. Was: ' + url,
<ide><path>Libraries/Lists/CellRenderMask.js
<ide> export class CellRenderMask {
<ide> return this._regions;
<ide> }
<ide>
<del> addCells(cells: {first: number, last: number}) {
<add> addCells(cells: {first: number, last: number}): void {
<ide> invariant(
<ide> cells.first >= 0 &&
<ide> cells.first < this._numCells &&
<ide><path>Libraries/Lists/FillRateHelper.js
<ide> let _sampleRate = DEBUG ? 1 : null;
<ide> * `SceneTracker.getActiveScene` to determine the context of the events.
<ide> */
<ide> class FillRateHelper {
<del> _anyBlankStartTime = (null: ?number);
<add> _anyBlankStartTime: ?number = null;
<ide> _enabled = false;
<ide> _getFrameMetrics: (index: number, props: FrameMetricProps) => ?FrameMetrics;
<del> _info = new Info();
<del> _mostlyBlankStartTime = (null: ?number);
<del> _samplesStartTime = (null: ?number);
<add> _info: Info = new Info();
<add> _mostlyBlankStartTime: ?number = null;
<add> _samplesStartTime: ?number = null;
<ide>
<ide> static addListener(callback: FillRateInfo => void): {
<ide> remove: () => void,
<ide><path>Libraries/LogBox/Data/LogBoxData.js
<ide> export function withSubscription(
<ide> WrappedComponent: SubscribedComponent,
<ide> ): React.AbstractComponent<{||}> {
<ide> class LogBoxStateSubscription extends React.Component<Props, State> {
<del> static getDerivedStateFromError() {
<add> static getDerivedStateFromError(): {hasError: boolean} {
<ide> return {hasError: true};
<ide> }
<ide>
<ide> export function withSubscription(
<ide>
<ide> _subscription: ?Subscription;
<ide>
<del> state = {
<add> state: State = {
<ide> logs: new Set(),
<ide> isDisabled: false,
<ide> hasError: false,
<ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#presentlocalnotification
<ide> */
<del> static presentLocalNotification(details: Object) {
<add> static presentLocalNotification(details: Object): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#schedulelocalnotification
<ide> */
<del> static scheduleLocalNotification(details: Object) {
<add> static scheduleLocalNotification(details: Object): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#cancelalllocalnotifications
<ide> */
<del> static cancelAllLocalNotifications() {
<add> static cancelAllLocalNotifications(): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#setapplicationiconbadgenumber
<ide> */
<del> static setApplicationIconBadgeNumber(number: number) {
<add> static setApplicationIconBadgeNumber(number: number): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#getapplicationiconbadgenumber
<ide> */
<del> static getApplicationIconBadgeNumber(callback: Function) {
<add> static getApplicationIconBadgeNumber(callback: Function): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#cancellocalnotification
<ide> */
<del> static cancelLocalNotifications(userInfo: Object) {
<add> static cancelLocalNotifications(userInfo: Object): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#getscheduledlocalnotifications
<ide> */
<del> static getScheduledLocalNotifications(callback: Function) {
<add> static getScheduledLocalNotifications(callback: Function): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#addeventlistener
<ide> */
<del> static addEventListener(type: PushNotificationEventName, handler: Function) {
<add> static addEventListener(
<add> type: PushNotificationEventName,
<add> handler: Function,
<add> ): void {
<ide> invariant(
<ide> type === 'notification' ||
<ide> type === 'register' ||
<ide> class PushNotificationIOS {
<ide> static removeEventListener(
<ide> type: PushNotificationEventName,
<ide> handler: Function,
<del> ) {
<add> ): void {
<ide> invariant(
<ide> type === 'notification' ||
<ide> type === 'register' ||
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#abandonpermissions
<ide> */
<del> static abandonPermissions() {
<add> static abandonPermissions(): void {
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> 'PushNotificationManager is not available.',
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#checkpermissions
<ide> */
<del> static checkPermissions(callback: Function) {
<add> static checkPermissions(callback: Function): void {
<ide> invariant(typeof callback === 'function', 'Must provide a valid callback');
<ide> invariant(
<ide> NativePushNotificationManagerIOS,
<ide> class PushNotificationIOS {
<ide> *
<ide> * See https://reactnative.dev/docs/pushnotificationios#finish
<ide> */
<del> finish(fetchResult: string) {
<add> finish(fetchResult: string): void {
<ide> if (
<ide> !this._isRemote ||
<ide> !this._notificationId ||
<ide><path>Libraries/Utilities/__tests__/setAndForwardRef-test.js
<ide> describe('setAndForwardRef', () => {
<ide> let outerFuncCalled: ?boolean = false;
<ide>
<ide> class ForwardedComponent extends React.Component<{||}> {
<del> testFunc() {
<add> testFunc(): any {
<ide> innerFuncCalled = true;
<ide> return true;
<ide> }
<ide>
<del> render() {
<add> render(): any {
<ide> return null;
<ide> }
<ide> }
<ide> describe('setAndForwardRef', () => {
<ide>
<ide> class TestComponent extends React.Component<Props> {
<ide> _nativeRef: ?React.ElementRef<typeof ForwardedComponent> = null;
<del> _setNativeRef = setAndForwardRef({
<add> _setNativeRef: (ref: React.ElementRef<any>) => void = setAndForwardRef({
<ide> getForwardedRef: () => this.props.forwardedRef,
<ide> setLocalRef: ref => {
<ide> this._nativeRef = ref;
<ide> describe('setAndForwardRef', () => {
<ide> }
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return <ForwardedComponent ref={this._setNativeRef} />;
<ide> }
<ide> }
<ide> describe('setAndForwardRef', () => {
<ide> /* eslint-enable react/no-string-refs */
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> /**
<ide> * Can't directly pass the test component to `ReactTestRenderer.create`,
<ide> * otherwise it will throw. See:
<ide><path>Libraries/Utilities/__tests__/useMergeRefs-test.js
<ide> class TestViewInstance {
<ide> return testID == null ? null : new TestViewInstance(testID);
<ide> }
<ide>
<del> static named(name: string) {
<add> static named(name: string): $FlowFixMe {
<ide> // $FlowIssue[prop-missing] - Flow does not support type augmentation.
<ide> return expect.testViewInstance(name);
<ide> }
<ide><path>Libraries/Utilities/__tests__/useRefEffect-test.js
<ide> class TestEffect {
<ide> this.name = name;
<ide> this.key = key;
<ide> }
<del> static called(name: string, key: ?string) {
<add> static called(name: string, key: ?string): $FlowFixMe {
<ide> // $FlowIssue[prop-missing] - Flow does not support type augmentation.
<ide> return expect.effect(name, key);
<ide> }
<ide> class TestEffectCleanup {
<ide> this.name = name;
<ide> this.key = key;
<ide> }
<del> static called(name: string, key: ?string) {
<add> static called(name: string, key: ?string): $FlowFixMe {
<ide> // $FlowIssue[prop-missing] - Flow does not support type augmentation.
<ide> return expect.effectCleanup(name, key);
<ide> }
<ide><path>Libraries/Utilities/createPerformanceLogger.js
<ide> class PerformanceLogger implements IPerformanceLogger {
<ide> this._closed = true;
<ide> }
<ide>
<del> currentTimestamp() {
<add> currentTimestamp(): number {
<ide> return getCurrentTimestamp();
<ide> }
<ide>
<del> getExtras() {
<add> getExtras(): {[key: string]: ?ExtraValue} {
<ide> return this._extras;
<ide> }
<ide>
<del> getPoints() {
<add> getPoints(): {[key: string]: ?number} {
<ide> return this._points;
<ide> }
<ide>
<del> getPointExtras() {
<add> getPointExtras(): {[key: string]: ?Extras} {
<ide> return this._pointExtras;
<ide> }
<ide>
<del> getTimespans() {
<add> getTimespans(): {[key: string]: ?Timespan} {
<ide> return this._timespans;
<ide> }
<ide>
<del> hasTimespan(key: string) {
<add> hasTimespan(key: string): boolean {
<ide> return !!this._timespans[key];
<ide> }
<ide>
<del> isClosed() {
<add> isClosed(): boolean {
<ide> return this._closed;
<ide> }
<ide>
<ide><path>ReactAndroid/src/androidTest/js/ScrollViewTestModule.js
<ide> type ItemProps = $ReadOnly<{|
<ide> type ItemState = {||};
<ide>
<ide> class Item extends React.Component<ItemProps, ItemState> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this.props.onPress}>
<ide> <View style={styles.item_container}>
<ide><path>ReactAndroid/src/androidTest/js/UIManagerTestModule.js
<ide> import type {RootTag} from 'react-native/Libraries/Types/RootTagTypes';
<ide>
<ide> type FlexTestAppProps = $ReadOnly<{||}>;
<ide> class FlexTestApp extends React.Component<FlexTestAppProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> style={FlexTestAppStyles.container}
<ide> const FlexTestAppStyles = StyleSheet.create({
<ide>
<ide> type FlexWithTextProps = $ReadOnly<{||}>;
<ide> class FlexWithText extends React.Component<FlexWithTextProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> style={FlexWithTextStyles.container}
<ide> const FlexWithTextStyles = StyleSheet.create({
<ide>
<ide> type AbsolutePositionTestAppProps = $ReadOnly<{||}>;
<ide> class AbsolutePositionTestApp extends React.Component<AbsolutePositionTestAppProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> style={AbsolutePositionTestAppStyles.absolute}
<ide> const AbsolutePositionTestAppStyles = StyleSheet.create({
<ide>
<ide> type AbsolutePositionBottomRightTestAppProps = $ReadOnly<{||}>;
<ide> class AbsolutePositionBottomRightTestApp extends React.Component<AbsolutePositionBottomRightTestAppProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> style={AbsolutePositionBottomRightTestAppStyles.container}
<ide> type CenteredTextViewProps = $ReadOnly<{|
<ide> text?: ?string,
<ide> |}>;
<ide> class CenteredTextView extends React.Component<CenteredTextViewProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View collapsable={false}>
<ide> <View style={CenteredTextViewStyles.parent} collapsable={false}>
<ide> class UpdatePositionInListTestApp extends React.Component<
<ide> UpdatePositionInListTestAppProps,
<ide> UpdatePositionInListTestAppState,
<ide> > {
<del> state = {
<add> state: UpdatePositionInListTestAppState = {
<ide> active: false,
<ide> };
<ide>
<ide> class UpdatePositionInListTestApp extends React.Component<
<ide> flushUpdatePositionInList = () => this.setState({active: true});
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View collapsable={false} testID="container">
<ide> <View
<ide><path>packages/rn-tester/js/RNTesterApp.ios.js
<ide> * @flow
<ide> */
<ide>
<add>import type {Node} from 'react';
<add>
<ide> import {AppRegistry} from 'react-native';
<ide> import React from 'react';
<ide>
<ide> RNTesterList.Components.concat(RNTesterList.APIs).forEach(
<ide> const ExampleModule = Example.module;
<ide> if (ExampleModule.displayName) {
<ide> class Snapshotter extends React.Component<{...}> {
<del> render() {
<add> render(): Node {
<ide> return (
<ide> <SnapshotViewIOS>
<ide> <RNTesterModuleContainer
<ide><path>packages/rn-tester/js/components/createExamplePage.js
<ide> const createExamplePage = function (
<ide> exampleModule: RNTesterModule,
<ide> ): React.ComponentType<any> {
<ide> class ExamplePage extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return <RNTesterModuleContainer module={exampleModule} />;
<ide> }
<ide> }
<ide><path>packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js
<ide> class CheckboxExample extends React.Component<
<ide> checkboxState: boolean | 'mixed',
<ide> },
<ide> > {
<del> state = {
<add> state: {checkboxState: boolean | 'mixed'} = {
<ide> checkboxState: true,
<ide> };
<ide>
<ide> class CheckboxExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableOpacity
<ide> onPress={this._onCheckboxPress}
<ide> class SwitchExample extends React.Component<
<ide> switchState: boolean,
<ide> },
<ide> > {
<del> state = {
<add> state: {switchState: boolean} = {
<ide> switchState: true,
<ide> };
<ide>
<ide> class SwitchExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableOpacity
<ide> onPress={this._onSwitchToggle}
<ide> class SelectionExample extends React.Component<
<ide> current: React.ElementRef<typeof TouchableOpacity> | null,
<ide> };
<ide>
<del> state = {
<add> state: {isEnabled: boolean, isSelected: boolean} = {
<ide> isSelected: true,
<ide> isEnabled: false,
<ide> };
<ide> class ExpandableElementExample extends React.Component<
<ide> expandState: boolean,
<ide> },
<ide> > {
<del> state = {
<add> state: {expandState: boolean} = {
<ide> expandState: false,
<ide> };
<ide>
<ide> class ExpandableElementExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableOpacity
<ide> onPress={this._onElementPress}
<ide> class NestedCheckBox extends React.Component<
<ide> checkbox3: boolean | 'mixed',
<ide> },
<ide> > {
<del> state = {
<add> state: {
<add> checkbox1: boolean | 'mixed',
<add> checkbox2: boolean | 'mixed',
<add> checkbox3: boolean | 'mixed',
<add> } = {
<ide> checkbox1: false,
<ide> checkbox2: false,
<ide> checkbox3: false,
<ide> class NestedCheckBox extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TouchableOpacity
<ide> class FakeSliderExample extends React.Component<{}, FakeSliderExampleState> {
<ide> }
<ide>
<ide> class AnnounceForAccessibility extends React.Component<{}> {
<del> _handleOnPress = () =>
<add> _handleOnPress = (): TimeoutID =>
<ide> setTimeout(
<ide> () => AccessibilityInfo.announceForAccessibility('Announcement Test'),
<ide> 1000,
<ide> );
<ide>
<del> _handleOnPressQueued = () =>
<add> _handleOnPressQueued = (): TimeoutID =>
<ide> setTimeout(
<ide> () =>
<ide> AccessibilityInfo.announceForAccessibilityWithOptions(
<ide> class EnabledExample extends React.Component<
<ide> isEnabled: boolean,
<ide> },
<ide> > {
<del> state = {
<add> state: {isEnabled: boolean} = {
<ide> isEnabled: false,
<ide> };
<ide> _subscription: EventSubscription;
<del> componentDidMount() {
<add> componentDidMount(): null | Promise<mixed> {
<ide> this._subscription = AccessibilityInfo.addEventListener(
<ide> this.props.eventListener,
<ide> this._handleToggled,
<ide><path>packages/rn-tester/js/examples/Accessibility/AccessibilityIOSExample.js
<ide> const RNTesterBlock = require('../../components/RNTesterBlock');
<ide>
<ide> type Props = $ReadOnly<{||}>;
<ide> class AccessibilityIOSExample extends React.Component<Props> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <RNTesterBlock title="Accessibility iOS APIs">
<ide> <View
<ide><path>packages/rn-tester/js/examples/ActionSheetIOS/ActionSheetIOSExample.js
<ide>
<ide> 'use strict';
<ide>
<add>import type {NativeMethods} from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
<add>
<ide> const React = require('react');
<ide> const {
<ide> ActionSheetIOS,
<ide> const DISABLED_BUTTON_INDICES = [1, 2];
<ide> type Props = $ReadOnly<{||}>;
<ide> type State = {|clicked: string|};
<ide> class ActionSheetExample extends React.Component<Props, State> {
<del> state = {
<add> state: State = {
<ide> clicked: 'none',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showActionSheet} style={style.button}>
<ide> class ActionSheetTintExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {clicked: string} = {
<ide> clicked: 'none',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showActionSheet} style={style.button}>
<ide> class ActionSheetCancelButtonTintExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {clicked: string} = {
<ide> clicked: 'none',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showActionSheet} style={style.button}>
<ide> class ActionSheetAnchorExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {clicked: string} = {
<ide> clicked: 'none',
<ide> };
<ide>
<del> anchorRef = React.createRef();
<add> anchorRef: {current: null | $Exact<NativeMethods>} = React.createRef();
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <View style={style.anchorRow}>
<ide> class ActionSheetAnchorExample extends React.Component<
<ide> }
<ide>
<ide> class ActionSheetDisabledExample extends React.Component<Props, State> {
<del> state = {
<add> state: State = {
<ide> clicked: 'none',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showActionSheet} style={style.button}>
<ide> class ActionSheetDisabledExample extends React.Component<Props, State> {
<ide> }
<ide>
<ide> class ActionSheetDismissExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showAndDismissActionSheet} style={style.button}>
<ide> class ShareActionSheetExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {text: string} = {
<ide> text: '',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showShareActionSheet} style={style.button}>
<ide> class ShareScreenshotExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {text: string} = {
<ide> text: '',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text onPress={this.showShareActionSheet} style={style.button}>
<ide> class ShareScreenshotAnchorExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {text: string} = {
<ide> text: '',
<ide> };
<ide>
<del> anchorRef = React.createRef();
<add> anchorRef: {current: null | $Exact<NativeMethods>} = React.createRef();
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <View style={style.anchorRow}>
<ide><path>packages/rn-tester/js/examples/Alert/AlertIOSExample.js
<ide> class PromptOptions extends React.Component<Props, State> {
<ide> };
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text style={styles.promptValue}>
<ide><path>packages/rn-tester/js/examples/AppState/AppStateExample.js
<ide> class AppStateSubscription extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: {
<add> appState: ?string,
<add> eventsDetected: Array<string>,
<add> memoryWarnings: number,
<add> previousAppStates: Array<?(any | string)>,
<add> } = {
<ide> appState: AppState.currentState,
<ide> previousAppStates: [],
<ide> memoryWarnings: 0,
<ide> class AppStateSubscription extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> if (this.props.showMemoryWarnings) {
<ide> return (
<ide> <View>
<ide><path>packages/rn-tester/js/examples/Appearance/AppearanceExample.js
<ide> class ColorSchemeSubscription extends React.Component<
<ide> > {
<ide> _subscription: ?EventSubscription;
<ide>
<del> state = {
<add> state: {colorScheme: ?string, ...} = {
<ide> colorScheme: Appearance.getColorScheme(),
<ide> };
<ide>
<ide> class ColorSchemeSubscription extends React.Component<
<ide> this._subscription?.remove();
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <RNTesterThemeContext.Consumer>
<ide> {theme => {
<ide><path>packages/rn-tester/js/examples/Dimensions/DimensionsExample.js
<ide> class DimensionsSubscription extends React.Component<
<ide> {dim: string, ...},
<ide> {dims: Object, ...},
<ide> > {
<del> state = {
<add> state: {dims: any, ...} = {
<ide> dims: Dimensions.get(this.props.dim),
<ide> };
<ide>
<ide> class DimensionsSubscription extends React.Component<
<ide> this._dimensionsSubscription?.remove();
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return <Text>{JSON.stringify(this.state.dims, null, 2)}</Text>;
<ide> }
<ide> }
<ide><path>packages/rn-tester/js/examples/Image/ImageExample.js
<ide> type BlobImageProps = $ReadOnly<{|
<ide> |}>;
<ide>
<ide> class BlobImage extends React.Component<BlobImageProps, BlobImageState> {
<del> state = {
<add> state: BlobImageState = {
<ide> objectURL: null,
<ide> };
<ide>
<ide> class BlobImage extends React.Component<BlobImageProps, BlobImageState> {
<ide> })();
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return this.state.objectURL !== null ? (
<ide> <Image source={{uri: this.state.objectURL}} style={styles.base} />
<ide> ) : (
<ide> class BlobImageExample extends React.Component<
<ide> BlobImageExampleProps,
<ide> BlobImageExampleState,
<ide> > {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.horizontal}>
<ide> {this.props.urls.map(url => (
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> NetworkImageCallbackExampleProps,
<ide> NetworkImageCallbackExampleState,
<ide> > {
<del> state = {
<add> state: NetworkImageCallbackExampleState = {
<ide> events: [],
<ide> startLoadPrefetched: false,
<ide> mountTime: Date.now(),
<ide> class NetworkImageCallbackExample extends React.Component<
<ide> this.setState({imageHash: Date.now()});
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const {mountTime} = this.state;
<ide> return (
<ide> <View>
<ide> class NetworkImageExample extends React.Component<
<ide> NetworkImageExampleProps,
<ide> NetworkImageExampleState,
<ide> > {
<del> state = {
<add> state: NetworkImageExampleState = {
<ide> error: null,
<ide> loading: false,
<ide> progress: [],
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return this.state.error != null ? (
<ide> <Text>{this.state.error}</Text>
<ide> ) : (
<ide> class ImageSizeExample extends React.Component<
<ide> ImageSizeExampleProps,
<ide> ImageSizeExampleState,
<ide> > {
<del> state = {
<add> state: ImageSizeExampleState = {
<ide> width: 0,
<ide> height: 0,
<ide> };
<ide> class ImageSizeExample extends React.Component<
<ide> });
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={{flexDirection: 'row'}}>
<ide> <Image
<ide> class MultipleSourcesExample extends React.Component<
<ide> MultipleSourcesExampleProps,
<ide> MultipleSourcesExampleState,
<ide> > {
<del> state = {
<add> state: MultipleSourcesExampleState = {
<ide> width: 30,
<ide> height: 30,
<ide> };
<ide> class MultipleSourcesExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<ide> class LoadingIndicatorSourceExample extends React.Component<
<ide> LoadingIndicatorSourceExampleProps,
<ide> LoadingIndicatorSourceExampleState,
<ide> > {
<del> state = {
<add> state: LoadingIndicatorSourceExampleState = {
<ide> imageHash: Date.now(),
<ide> };
<ide>
<ide> class LoadingIndicatorSourceExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> loaderGif = {
<add> loaderGif: {uri: string} = {
<ide> uri: 'https://media1.giphy.com/media/3oEjI6SIIHBdRxXI40/200.gif',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const loadingImage = {
<ide> uri: `https://www.facebook.com/ads/pics/successstories.png?hash=${this.state.imageHash}`,
<ide> };
<ide> class OnLayoutExample extends React.Component<
<ide> OnLayoutExampleProps,
<ide> OnLayoutExampleState,
<ide> > {
<del> state = {
<add> state: OnLayoutExampleState = {
<ide> width: 30,
<ide> height: 30,
<ide> layoutHandlerMessage: 'No Message',
<ide> class OnLayoutExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>Adjust the image size to trigger the OnLayout handler.</Text>
<ide> class OnPartialLoadExample extends React.Component<
<ide> OnPartialLoadExampleProps,
<ide> OnPartialLoadExampleState,
<ide> > {
<del> state = {
<add> state: OnPartialLoadExampleState = {
<ide> hasLoaded: false,
<ide> };
<ide>
<ide> class OnPartialLoadExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>
<ide><path>packages/rn-tester/js/examples/InputAccessoryView/InputAccessoryViewExample.js
<ide> const {
<ide>
<ide> type MessageProps = $ReadOnly<{||}>;
<ide> class Message extends React.PureComponent<MessageProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.textBubbleBackground}>
<ide> <Text style={styles.text}>Text Message</Text>
<ide> class Message extends React.PureComponent<MessageProps> {
<ide> type TextInputProps = $ReadOnly<{||}>;
<ide> type TextInputState = {|text: string|};
<ide> class TextInputBar extends React.PureComponent<TextInputProps, TextInputState> {
<del> state = {text: ''};
<add> state: TextInputState = {text: ''};
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.textInputContainer}>
<ide> <TextInput
<ide> class TextInputBar extends React.PureComponent<TextInputProps, TextInputState> {
<ide> const BAR_HEIGHT = 44;
<ide> type InputAccessoryProps = $ReadOnly<{||}>;
<ide> class InputAccessoryViewExample extends React.Component<InputAccessoryProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <>
<ide> <ScrollView style={styles.fill} keyboardDismissMode="interactive">
<ide><path>packages/rn-tester/js/examples/Layout/LayoutAnimationExample.js
<ide> function shuffleArray(array: Array<ExampleViewSpec>) {
<ide> }
<ide>
<ide> class AddRemoveExample extends React.Component<{...}, AddRemoveExampleState> {
<del> state = {
<add> state: AddRemoveExampleState = {
<ide> views: [],
<ide> nextKey: 1,
<ide> };
<ide> class AddRemoveExample extends React.Component<{...}, AddRemoveExampleState> {
<ide> this.setState(state => ({views: shuffleArray(state.views)}));
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const views = this.state.views.map(({key}) => (
<ide> <View
<ide> key={key}
<ide> class ReparentingExample extends React.Component<
<ide> {...},
<ide> ReparentingExampleState,
<ide> > {
<del> state = {
<add> state: ReparentingExampleState = {
<ide> hasBorder: false,
<ide> };
<ide>
<ide> class ReparentingExample extends React.Component<
<ide> this.setState(state => ({hasBorder: !state.hasBorder}));
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const parentStyle = this.state.hasBorder
<ide> ? {borderWidth: 5, borderColor: 'red'}
<ide> : {};
<ide> type CrossFadeExampleState = {|
<ide> |};
<ide>
<ide> class CrossFadeExample extends React.Component<{...}, CrossFadeExampleState> {
<del> state = {
<add> state: CrossFadeExampleState = {
<ide> toggled: false,
<ide> };
<ide>
<ide> class CrossFadeExample extends React.Component<{...}, CrossFadeExampleState> {
<ide> this.setState(state => ({toggled: !state.toggled}));
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.container}>
<ide> <TouchableOpacity onPress={this._onPressToggle}>
<ide> class LayoutUpdateExample extends React.Component<
<ide> {...},
<ide> LayoutUpdateExampleState,
<ide> > {
<del> state = {
<add> state: LayoutUpdateExampleState = {
<ide> width: 200,
<ide> height: 100,
<ide> };
<ide> class LayoutUpdateExample extends React.Component<
<ide> this.timeout = setTimeout(() => this.setState({width: 100}), 500);
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const {width, height} = this.state;
<ide>
<ide> return (
<ide><path>packages/rn-tester/js/examples/Layout/LayoutEventsExample.js
<ide> class LayoutEventExample extends React.Component<Props, State> {
<ide> this.setState({imageLayout: e.nativeEvent.layout});
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const viewStyle = [styles.view, this.state.viewStyle];
<ide> const textLayout = this.state.textLayout || {width: '?', height: '?'};
<ide> const imageLayout = this.state.imageLayout || {x: '?', y: '?'};
<ide><path>packages/rn-tester/js/examples/Layout/LayoutExample.js
<ide> const React = require('react');
<ide> const {StyleSheet, Text, View} = require('react-native');
<ide>
<ide> class Circle extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> const size = this.props.size || 20;
<ide> const backgroundColor = this.props.bgColor || '#527fe4';
<ide> return (
<ide> class Circle extends React.Component<$FlowFixMeProps> {
<ide> }
<ide>
<ide> class CircleBlock extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> const circleStyle = {
<ide> flexDirection: 'row',
<ide> backgroundColor: '#f6f7f8',
<ide><path>packages/rn-tester/js/examples/NativeAnimation/NativeAnimationsExample.js
<ide> const {
<ide> const AnimatedSlider = Animated.createAnimatedComponent(Slider);
<ide>
<ide> class Tester extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<del> state = {
<add> state: any | {js: AnimatedValue, native: AnimatedValue} = {
<ide> native: new Animated.Value(0),
<ide> js: new Animated.Value(0),
<ide> };
<ide> class Tester extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<ide> }).start();
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this.onPress}>
<ide> <View>
<ide> class Tester extends React.Component<$FlowFixMeProps, $FlowFixMeState> {
<ide> }
<ide>
<ide> class ValueListenerExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {anim: AnimatedValue, progress: number} = {
<ide> anim: new Animated.Value(0),
<ide> progress: 0,
<ide> };
<ide> class ValueListenerExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }).start();
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this._onPress}>
<ide> <View>
<ide> class ValueListenerExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class LoopExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {value: AnimatedValue} = {
<ide> value: new Animated.Value(0),
<ide> };
<ide>
<ide> class LoopExample extends React.Component<{...}, $FlowFixMeState> {
<ide> ).start();
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.row}>
<ide> <Animated.View
<ide> class InternalSettings extends React.Component<
<ide> },
<ide> > {
<ide> _stallInterval: ?number;
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <RNTesterSettingSwitchRow
<ide> class InternalSettings extends React.Component<
<ide> }
<ide>
<ide> class EventExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {anim: AnimatedValue} = {
<ide> anim: new Animated.Value(0),
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Animated.View
<ide> class TrackingExample extends React.Component<
<ide> $FlowFixMeProps,
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state:
<add> | any
<add> | {
<add> js: AnimatedValue,
<add> native: AnimatedValue,
<add> toJS: AnimatedValue,
<add> toNative: AnimatedValue,
<add> } = {
<ide> native: new Animated.Value(0),
<ide> toNative: new Animated.Value(0),
<ide> js: new Animated.Value(0),
<ide> class TrackingExample extends React.Component<
<ide> this.state.toJS.setValue(nextValue);
<ide> };
<ide>
<del> renderBlock = (anim: any | AnimatedValue, dest: any | AnimatedValue) => [
<add> renderBlock = (
<add> anim: any | AnimatedValue,
<add> dest: any | AnimatedValue,
<add> ): Array<React.Node> => [
<ide> <Animated.View
<ide> key="line"
<ide> style={[styles.line, {transform: [{translateX: dest}]}]}
<ide> class TrackingExample extends React.Component<
<ide> />,
<ide> ];
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this.onPress}>
<ide> <View>
<ide><path>packages/rn-tester/js/examples/OrientationChange/OrientationChangeExample.js
<ide> import {type EventSubscription} from 'react-native/Libraries/vendor/emitter/Even
<ide> class OrientationChangeExample extends React.Component<{...}, $FlowFixMeState> {
<ide> _orientationSubscription: EventSubscription;
<ide>
<del> state = {
<add> state:
<add> | any
<add> | {
<add> currentOrientation: string,
<add> isLandscape: boolean,
<add> orientationDegrees: number,
<add> } = {
<ide> currentOrientation: '',
<ide> orientationDegrees: 0,
<ide> isLandscape: false,
<ide> class OrientationChangeExample extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>{JSON.stringify(this.state)}</Text>
<ide><path>packages/rn-tester/js/examples/PointerEvents/PointerEventsExample.js
<ide> type ExampleBoxState = $ReadOnly<{|
<ide> |}>;
<ide>
<ide> class ExampleBox extends React.Component<ExampleBoxProps, ExampleBoxState> {
<del> state = {
<add> state: ExampleBoxState = {
<ide> log: [],
<ide> };
<ide>
<ide> class ExampleBox extends React.Component<ExampleBoxProps, ExampleBoxState> {
<ide> this.state.log = this.state.log.concat(['---']);
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const {Component} = this.props;
<ide> return (
<ide> <View>
<ide> class ExampleBox extends React.Component<ExampleBoxProps, ExampleBoxState> {
<ide> }
<ide>
<ide> class NoneExample extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> onTouchStart={() => this.props.onLog('A unspecified touched')}
<ide> class NoneExample extends React.Component<$FlowFixMeProps> {
<ide> * the experiment and confuse the output.
<ide> */
<ide> class DemoText extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View pointerEvents="none">
<ide> <Text style={this.props.style}>{this.props.children}</Text>
<ide> class DemoText extends React.Component<$FlowFixMeProps> {
<ide> }
<ide>
<ide> class BoxNoneExample extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> onTouchStart={() => this.props.onLog('A unspecified touched')}
<ide> class BoxNoneExample extends React.Component<$FlowFixMeProps> {
<ide> }
<ide>
<ide> class BoxOnlyExample extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View
<ide> onTouchStart={() => this.props.onLog('A unspecified touched')}
<ide> type OverflowExampleProps = $ReadOnly<{|
<ide> |}>;
<ide>
<ide> class OverflowExample extends React.Component<OverflowExampleProps> {
<del> render() {
<add> render(): React.Node {
<ide> const {overflow} = this.props;
<ide> return (
<ide> <View
<ide> class OverflowExample extends React.Component<OverflowExampleProps> {
<ide> }
<ide>
<ide> class OverflowVisibleExample extends React.Component<ExampleBoxComponentProps> {
<del> render() {
<add> render(): React.Node {
<ide> return <OverflowExample {...this.props} overflow="visible" />;
<ide> }
<ide> }
<ide>
<ide> class OverflowHiddenExample extends React.Component<ExampleBoxComponentProps> {
<del> render() {
<add> render(): React.Node {
<ide> return <OverflowExample {...this.props} overflow="hidden" />;
<ide> }
<ide> }
<ide><path>packages/rn-tester/js/examples/RCTRootView/RCTRootViewIOSExample.js
<ide> const {
<ide> } = require('react-native');
<ide>
<ide> class AppPropertiesUpdateExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> // Do not require this unless we are actually rendering.
<ide> const UpdatePropertiesExampleView = requireNativeComponent(
<ide> 'UpdatePropertiesExampleView',
<ide> class AppPropertiesUpdateExample extends React.Component<{...}> {
<ide> }
<ide>
<ide> class RootViewSizeFlexibilityExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> // Do not require this unless we are actually rendering.
<ide> const FlexibleSizeExampleView = requireNativeComponent(
<ide> 'FlexibleSizeExampleView',
<ide><path>packages/rn-tester/js/examples/RTL/RTLExample.js
<ide> class RTLToggleExample extends React.Component<any, RTLToggleState> {
<ide> };
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <View style={styles.directionBox}>
<ide> class AnimationExample extends React.Component<any, AnimationState> {
<ide> };
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <RTLToggler setRTL={this.props.setRTL} isRTL={this.props.isRTL} />
<ide><path>packages/rn-tester/js/examples/SafeAreaView/SafeAreaViewExample.js
<ide> class SafeAreaViewExample extends React.Component<
<ide> modalVisible: boolean,
<ide> |},
<ide> > {
<del> state = {
<add> state: {modalVisible: boolean} = {
<ide> modalVisible: false,
<ide> };
<ide>
<ide> _setModalVisible = (visible: boolean) => {
<ide> this.setState({modalVisible: visible});
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Modal
<ide> class SafeAreaViewExample extends React.Component<
<ide> }
<ide>
<ide> class IsIPhoneXExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Text>
<ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewAnimatedExample.js
<ide>
<ide> 'use strict';
<ide>
<add>import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue';
<add>
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const {Component} = React;
<ide> const {StyleSheet, Text, View, Animated, Easing, TouchableOpacity, Dimensions} =
<ide> ReactNative;
<ide>
<ide> class ScrollViewAnimatedExample extends Component<{...}> {
<del> _scrollViewPos = new Animated.Value(0);
<add> _scrollViewPos: AnimatedValue = new Animated.Value(0);
<ide>
<ide> startAnimation: () => void = () => {
<ide> this._scrollViewPos.setValue(0);
<ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js
<ide> import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
<ide> import ScrollViewPressableStickyHeaderExample from './ScrollViewPressableStickyHeaderExample';
<ide>
<ide> class EnableDisableList extends React.Component<{}, {scrollEnabled: boolean}> {
<del> state = {
<add> state: {scrollEnabled: boolean} = {
<ide> scrollEnabled: true,
<ide> };
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <ScrollView
<ide> class AppendingList extends React.Component<
<ide> {},
<ide> {items: Array<React.Element<typeof Item>>},
<ide> > {
<del> state = {
<add> state: {items: Array<React.Element<typeof Item>>} = {
<ide> items: [...Array(AppendingListItemCount)].map((_, ii) => (
<ide> <Item msg={`Item ${ii}`} />
<ide> )),
<ide> };
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <ScrollView
<ide> class Item extends React.PureComponent<{|
<ide> msg?: string,
<ide> style?: ViewStyleProp,
<ide> |}> {
<del> render() {
<add> render(): $FlowFixMe {
<ide> return (
<ide> <View style={[styles.item, this.props.style]}>
<ide> <Text>{this.props.msg}</Text>
<ide><path>packages/rn-tester/js/examples/Snapshot/SnapshotExample.js
<ide> const {Alert, Image, StyleSheet, Text, View} = require('react-native');
<ide> const ScreenshotManager = require('../../../NativeModuleExample/NativeScreenshotManager');
<ide>
<ide> class ScreenshotExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {uri: void} = {
<ide> uri: undefined,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={style.container}>
<ide> <Text onPress={this.takeScreenshot} style={style.button}>
<ide><path>packages/rn-tester/js/examples/StatusBar/StatusBarExample.js
<ide> function getValue<T>(values: Array<T>, index: number): T {
<ide> }
<ide>
<ide> class StatusBarHiddenExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state:
<add> | $FlowFixMe
<add> | {animated: boolean, hidden: boolean, showHideTransition: string} = {
<ide> animated: true,
<ide> hidden: false,
<ide> showHideTransition: getValue(showHideTransitions, 0),
<ide> class StatusBarHiddenExample extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <StatusBar
<ide> hidden={this.state.hidden}
<add> // $FlowFixMe[incompatible-type]
<ide> showHideTransition={this.state.showHideTransition}
<ide> animated={this.state.animated}
<ide> />
<ide> class StatusBarStyleExample extends React.Component<{...}, $FlowFixMeState> {
<ide> this.setState({animated: !this.state.animated});
<ide> };
<ide>
<del> state = {
<add> state: $FlowFixMe | {animated: boolean, barStyle: string} = {
<ide> animated: true,
<ide> barStyle: getValue(barStyles, this._barStyleIndex),
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <StatusBar
<ide> animated={this.state.animated}
<add> // $FlowFixMe[incompatible-type]
<ide> barStyle={this.state.barStyle}
<ide> />
<ide> <TouchableHighlight
<ide> class StatusBarNetworkActivityExample extends React.Component<
<ide> {...},
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: $FlowFixMe | {networkActivityIndicatorVisible: boolean} = {
<ide> networkActivityIndicatorVisible: false,
<ide> };
<ide>
<ide> class StatusBarNetworkActivityExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <StatusBar
<ide> class StatusBarBackgroundColorExample extends React.Component<
<ide> {...},
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: $FlowFixMe | {animated: boolean, backgroundColor: string} = {
<ide> animated: true,
<ide> backgroundColor: getValue(colors, 0),
<ide> };
<ide> class StatusBarBackgroundColorExample extends React.Component<
<ide> this.setState({animated: !this.state.animated});
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <StatusBar
<ide> class StatusBarTranslucentExample extends React.Component<
<ide> {...},
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: $FlowFixMe | {translucent: boolean} = {
<ide> translucent: false,
<ide> };
<ide>
<ide> class StatusBarTranslucentExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <StatusBar translucent={this.state.translucent} />
<ide> class StatusBarTranslucentExample extends React.Component<
<ide> }
<ide>
<ide> class StatusBarStaticIOSExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TouchableHighlight
<ide> class StatusBarStaticIOSExample extends React.Component<{...}> {
<ide> }
<ide>
<ide> class StatusBarStaticAndroidExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TouchableHighlight
<ide> class StatusBarStaticAndroidExample extends React.Component<{...}> {
<ide> }
<ide>
<ide> class ModalExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: $FlowFixMe | {modalVisible: boolean} = {
<ide> modalVisible: false,
<ide> };
<ide>
<ide> _onChangeModalVisible = () => {
<ide> this.setState({modalVisible: !this.state.modalVisible});
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TouchableHighlight
<ide><path>packages/rn-tester/js/examples/Switch/SwitchExample.js
<ide> class BasicSwitchExample extends React.Component<
<ide> {||},
<ide> SimpleSwitchExampleState,
<ide> > {
<del> state = {
<add> state: SimpleSwitchExampleState = {
<ide> trueSwitchIsOn: true,
<ide> falseSwitchIsOn: false,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <ExampleRow>
<ide> class DisabledSwitchExample extends React.Component<
<ide> {||},
<ide> SimpleSwitchExampleState,
<ide> > {
<del> state = {
<add> state: SimpleSwitchExampleState = {
<ide> trueSwitchIsOn: true,
<ide> falseSwitchIsOn: false,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <ExampleRow>
<ide> class DisabledSwitchExample extends React.Component<
<ide> }
<ide>
<ide> class ColorSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {colorFalseSwitchIsOn: boolean, colorTrueSwitchIsOn: boolean} = {
<ide> colorTrueSwitchIsOn: true,
<ide> colorFalseSwitchIsOn: false,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Switch
<ide> class ColorSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class EventSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<del> eventSwitchIsOn: false,
<del> eventSwitchRegressionIsOn: true,
<del> };
<add> state: any | {eventSwitchIsOn: boolean, eventSwitchRegressionIsOn: boolean} =
<add> {
<add> eventSwitchIsOn: false,
<add> eventSwitchRegressionIsOn: true,
<add> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<ide> <View>
<ide> class EventSwitchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class IOSBackgroundColEx extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {iosBackgroundColor: string} = {
<ide> iosBackgroundColor: '#ffa500',
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Switch
<ide> class IOSBackgroundColEx extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class OnChangeExample extends React.Component<{...}, $FlowFixMeState> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Switch
<ide> class ContainerBackgroundColorStyleExample extends React.Component<
<ide> {...},
<ide> $FlowFixMeState,
<ide> > {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <Switch
<ide><path>packages/rn-tester/js/examples/Text/TextExample.ios.js
<ide> class TextAlignRTLExample extends React.Component<
<ide> };
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const {isRTL} = this.state;
<ide> const toggleRTL = () => this.setState({isRTL: !isRTL});
<ide> return (
<ide> class TextAlignRTLExample extends React.Component<
<ide> }
<ide>
<ide> class Entity extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <Text style={{fontWeight: '500', color: '#527fe4'}}>
<ide> {this.props.children}
<ide> class Entity extends React.Component<$FlowFixMeProps> {
<ide> }
<ide>
<ide> class AttributeToggler extends React.Component<{...}, $FlowFixMeState> {
<del> state = {fontWeight: 'bold', fontSize: 15};
<add> state: any | {fontSize: number, fontWeight: string} = {
<add> fontWeight: 'bold',
<add> fontSize: 15,
<add> };
<ide>
<ide> toggleWeight = () => {
<ide> this.setState({
<ide> class AttributeToggler extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const curStyle = {
<ide> fontWeight: this.state.fontWeight,
<ide> fontSize: this.state.fontSize,
<ide> };
<ide> return (
<ide> <View>
<add> {/* $FlowFixMe[incompatible-type] */}
<ide> <Text style={curStyle}>
<ide> Tap the controls below to change attributes.
<ide> </Text>
<ide> <Text>
<ide> <Text>
<del> See how it will even work on{' '}
<add> See how it will even work on {/* $FlowFixMe[incompatible-type] */}
<ide> <Text style={curStyle}>this nested text</Text>
<ide> </Text>
<ide> </Text>
<ide> class AdjustingFontSize extends React.Component<
<ide> AdjustingFontSizeProps,
<ide> AdjustingFontSizeState,
<ide> > {
<del> state = {
<add> state: AdjustingFontSizeState = {
<ide> dynamicText: '',
<ide> shouldRender: true,
<ide> };
<ide> class AdjustingFontSize extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> if (!this.state.shouldRender) {
<ide> return <View />;
<ide> }
<ide> class AdjustingFontSize extends React.Component<
<ide> }
<ide>
<ide> class TextBaseLineLayoutExample extends React.Component<{}, mixed> {
<del> render() {
<add> render(): React.Node {
<ide> const texts = [];
<ide> for (let i = 9; i >= 0; i--) {
<ide> texts.push(
<ide> class TextRenderInfoExample extends React.Component<
<ide> }>,
<ide> },
<ide> > {
<del> state = {
<add> state: {
<add> fontSize: number,
<add> numberOfTextBlocks: number,
<add> textMetrics: $ReadOnly<{
<add> ascender: number,
<add> capHeight: number,
<add> descender: number,
<add> height: number,
<add> text?: string,
<add> width: number,
<add> x: number,
<add> xHeight: number,
<add> y: number,
<add> }>,
<add> } = {
<ide> textMetrics: {
<ide> x: 0,
<ide> y: 0,
<ide> class TextRenderInfoExample extends React.Component<
<ide> fontSize: 14,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const topOfBox =
<ide> this.state.textMetrics.y +
<ide> this.state.textMetrics.height -
<ide> class TextWithCapBaseBox extends React.Component<
<ide> }>,
<ide> },
<ide> > {
<del> state = {
<add> state: {
<add> textMetrics: $ReadOnly<{
<add> ascender: number,
<add> capHeight: number,
<add> descender: number,
<add> height: number,
<add> text?: string,
<add> width: number,
<add> x: number,
<add> xHeight: number,
<add> y: number,
<add> }>,
<add> } = {
<ide> textMetrics: {
<ide> x: 0,
<ide> y: 0,
<ide> class TextWithCapBaseBox extends React.Component<
<ide> xHeight: 0,
<ide> },
<ide> };
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <Text
<ide> onTextLayout={event => {
<ide><path>packages/rn-tester/js/examples/TextInput/TextInputExample.ios.js
<ide> const TextInputSharedExamples = require('./TextInputSharedExamples.js');
<ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes';
<ide>
<ide> class WithLabel extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.labelContainer}>
<ide> <View style={styles.label}>
<ide> class TextInputAccessoryViewChangeTextExample extends React.Component<
<ide> this.state = {text: 'Placeholder Text'};
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const inputAccessoryViewID = 'inputAccessoryView1';
<ide> return (
<ide> <View>
<ide> class TextInputAccessoryViewChangeKeyboardExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const inputAccessoryViewID = 'inputAccessoryView2';
<ide> return (
<ide> <View>
<ide> class TextInputAccessoryViewDefaultDoneButtonExample extends React.Component<
<ide> this.state = {text: ''};
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TextInput
<ide> style={styles.default}
<ide> class RewriteExampleKana extends React.Component<$FlowFixMeProps, any> {
<ide> super(props);
<ide> this.state = {text: ''};
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.rewriteContainer}>
<ide> <TextInput
<ide> class SecureEntryExample extends React.Component<$FlowFixMeProps, any> {
<ide> isSecureTextEntry: true,
<ide> };
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> class AutogrowingTextInputExample extends React.Component<
<ide> });
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const {style, multiline, ...props} = this.props;
<ide> return (
<ide> <View>
<ide><path>packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js
<ide> const styles = StyleSheet.create({
<ide> });
<ide>
<ide> class WithLabel extends React.Component<$FlowFixMeProps> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.labelContainer}>
<ide> <View style={styles.label}>
<ide> class RewriteExample extends React.Component<$FlowFixMeProps, any> {
<ide> super(props);
<ide> this.state = {text: ''};
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> const limit = 20;
<ide> const remainder = limit - this.state.text.length;
<ide> const remainderColor = remainder > 5 ? 'blue' : 'red';
<ide> class RewriteExampleInvalidCharacters extends React.Component<
<ide> super(props);
<ide> this.state = {text: ''};
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.rewriteContainer}>
<ide> <TextInput
<ide> class RewriteInvalidCharactersAndClearExample extends React.Component<
<ide> super(props);
<ide> this.state = {text: ''};
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={styles.rewriteContainer}>
<ide> <TextInput
<ide> class BlurOnSubmitExample extends React.Component<{...}> {
<ide> ref4 = React.createRef();
<ide> ref5 = React.createRef();
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> class SubmitBehaviorExample extends React.Component<{...}> {
<ide> ref10 = React.createRef();
<ide> ref11 = React.createRef();
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> class SubmitBehaviorExample extends React.Component<{...}> {
<ide> }
<ide>
<ide> class TextEventsExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state:
<add> | any
<add> | {
<add> curText: string,
<add> prev2Text: string,
<add> prev3Text: string,
<add> prevText: string,
<add> } = {
<ide> curText: '<No Event>',
<ide> prevText: '<No Event>',
<ide> prev2Text: '<No Event>',
<ide> class TextEventsExample extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TextInput
<ide> class TokenizedTextExample extends React.Component<
<ide> super(props);
<ide> this.state = {text: 'Hello #World'};
<ide> }
<del> render() {
<add> render(): React.Node {
<ide> //define delimiter
<ide> let delimiter = /\s+/;
<ide>
<ide> class SelectionExample extends React.Component<
<ide> this.setState({selection});
<ide> }
<ide>
<del> getRandomPosition() {
<add> getRandomPosition(): number {
<ide> const length = this.state.value.length;
<ide> return Math.round(Math.random() * length);
<ide> }
<ide> class SelectionExample extends React.Component<
<ide> this.placeAt(this.getRandomPosition());
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const length = this.state.value.length;
<ide>
<ide> return (
<ide><path>packages/rn-tester/js/examples/Timer/TimerExample.js
<ide> class RequestIdleCallbackTester extends React.Component<
<ide> RequestIdleCallbackTesterProps,
<ide> RequestIdleCallbackTesterState,
<ide> > {
<del> state = {
<add> state: RequestIdleCallbackTesterState = {
<ide> message: '-',
<ide> };
<ide>
<ide> class RequestIdleCallbackTester extends React.Component<
<ide> }
<ide> }
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> {/* $FlowFixMe[method-unbinding] added when improving typing for this
<ide> class TimerTester extends React.Component<TimerTesterProps> {
<ide> _immediateId: ?Object = null;
<ide> _timerFn: ?() => any = null;
<ide>
<del> render() {
<add> render(): any {
<ide> const args =
<ide> 'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : '');
<ide> return (
<ide> class IntervalExample extends React.Component<
<ide> showTimer: boolean,
<ide> |},
<ide> > {
<del> state = {
<add> state: {showTimer: boolean} = {
<ide> showTimer: true,
<ide> };
<ide>
<ide> _timerTester: ?React.ElementRef<typeof TimerTester>;
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> {this.state.showTimer && this._renderTimer()}
<ide> class IntervalExample extends React.Component<
<ide> );
<ide> }
<ide>
<del> _renderTimer = () => {
<add> _renderTimer = (): React.Node => {
<ide> return (
<ide> <View>
<ide> <TimerTester
<ide><path>packages/rn-tester/js/examples/Touchable/TouchableExample.js
<ide> const forceTouchAvailable =
<ide> (Platform.OS === 'ios' && Platform.constants.forceTouchAvailable) || false;
<ide>
<ide> class TouchableHighlightBox extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {timesPressed: number} = {
<ide> timesPressed: 0,
<ide> };
<ide>
<ide> class TouchableHighlightBox extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> let textLog = '';
<ide> if (this.state.timesPressed > 1) {
<ide> textLog = this.state.timesPressed + 'x TouchableHighlight onPress';
<ide> class TouchableWithoutFeedbackBox extends React.Component<
<ide> {...},
<ide> $FlowFixMeState,
<ide> > {
<del> state = {
<add> state: any | {timesPressed: number} = {
<ide> timesPressed: 0,
<ide> };
<ide>
<ide> class TouchableWithoutFeedbackBox extends React.Component<
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> let textLog = '';
<ide> if (this.state.timesPressed > 1) {
<ide> textLog = this.state.timesPressed + 'x TouchableWithoutFeedback onPress';
<ide> class TouchableWithoutFeedbackBox extends React.Component<
<ide> }
<ide>
<ide> class TextOnPressBox extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {timesPressed: number} = {
<ide> timesPressed: 0,
<ide> };
<ide>
<ide> class TextOnPressBox extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> let textLog = '';
<ide> if (this.state.timesPressed > 1) {
<ide> textLog = this.state.timesPressed + 'x text onPress';
<ide> class TextOnPressBox extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class TouchableFeedbackEvents extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {eventLog: Array<string>} = {
<ide> eventLog: [],
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View testID="touchable_feedback_events">
<ide> <View style={[styles.row, styles.centered]}>
<ide> class TouchableFeedbackEvents extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class TouchableDelayEvents extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {eventLog: Array<string>} = {
<ide> eventLog: [],
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View testID="touchable_delay_events">
<ide> <View style={[styles.row, styles.centered]}>
<ide> class TouchableDelayEvents extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class ForceTouchExample extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {force: number} = {
<ide> force: 0,
<ide> };
<ide>
<del> _renderConsoleText = () => {
<add> _renderConsoleText = (): string => {
<ide> return forceTouchAvailable
<ide> ? 'Force: ' + this.state.force.toFixed(3)
<ide> : '3D Touch is not available on this device';
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View testID="touchable_3dtouch_event">
<ide> <View style={styles.forceTouchBox} testID="touchable_3dtouch_output">
<ide> class ForceTouchExample extends React.Component<{...}, $FlowFixMeState> {
<ide> }
<ide>
<ide> class TouchableHitSlop extends React.Component<{...}, $FlowFixMeState> {
<del> state = {
<add> state: any | {timesPressed: number} = {
<ide> timesPressed: 0,
<ide> };
<ide>
<ide> class TouchableHitSlop extends React.Component<{...}, $FlowFixMeState> {
<ide> });
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> let log = '';
<ide> if (this.state.timesPressed > 1) {
<ide> log = this.state.timesPressed + 'x onPress';
<ide> function TouchableNativeMethods() {
<ide> }
<ide>
<ide> class TouchableDisabled extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View>
<ide> <TouchableOpacity disabled={true} style={[styles.row, styles.block]}>
<ide><path>packages/rn-tester/js/examples/TransparentHitTest/TransparentHitTestExample.js
<ide> const React = require('react');
<ide> const {Text, View, TouchableOpacity, Alert} = require('react-native');
<ide>
<ide> class TransparentHitTestExample extends React.Component<{...}> {
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <View style={{flex: 1}}>
<ide> <TouchableOpacity onPress={() => Alert.alert('Alert', 'Hi!')}>
<ide><path>packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> | 'promise'
<ide> | 'rejectPromise'
<ide> | 'voidFunc',
<del> ) {
<add> ): React.Node {
<ide> const result = this.state.testResults[name] || {};
<ide> return (
<ide> <View style={styles.result}>
<ide> class SampleTurboModuleExample extends React.Component<{||}, State> {
<ide> );
<ide> }
<ide>
<del> componentDidMount() {
<add> componentDidMount(): void {
<ide> if (global.__turboModuleProxy == null) {
<ide> throw new Error(
<ide> 'Cannot load this example because TurboModule is not configured.',
<ide><path>packages/rn-tester/js/examples/View/ViewExample.js
<ide> class ViewBorderStyleExample extends React.Component<
<ide> $ReadOnly<{||}>,
<ide> {|showBorder: boolean|},
<ide> > {
<del> state = {
<add> state: {showBorder: boolean} = {
<ide> showBorder: true,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this._handlePress}>
<ide> <View>
<ide> class OffscreenAlphaCompositing extends React.Component<
<ide> active: boolean,
<ide> |},
<ide> > {
<del> state = {
<add> state: {active: boolean} = {
<ide> active: false,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this._handlePress}>
<ide> <View>
<ide> class ZIndexExample extends React.Component<
<ide> flipped: boolean,
<ide> |},
<ide> > {
<del> state = {
<add> state: {flipped: boolean} = {
<ide> flipped: false,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> const indices = this.state.flipped ? [-1, 0, 1, 2] : [2, 1, 0, -1];
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this._handlePress}>
<ide> class DisplayNoneStyle extends React.Component<
<ide> index: number,
<ide> |},
<ide> > {
<del> state = {
<add> state: {index: number} = {
<ide> index: 0,
<ide> };
<ide>
<del> render() {
<add> render(): React.Node {
<ide> return (
<ide> <TouchableWithoutFeedback onPress={this._handlePress}>
<ide> <View>
<ide><path>packages/rn-tester/js/examples/XHR/XHRExampleFetch.js
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> });
<ide> }
<ide>
<del> _renderHeaders() {
<add> _renderHeaders(): null | Array<React.Node> {
<ide> if (!this.responseHeaders) {
<ide> return null;
<ide> }
<ide><path>packages/rn-tester/js/utils/RNTesterStatePersister.js
<ide> function createContainer<Props: Object, State>(
<ide> Props,
<ide> $FlowFixMeState,
<ide> > {
<del> static displayName = `RNTesterStatePersister(${String(
<add> static displayName: ?string = `RNTesterStatePersister(${String(
<ide> Component.displayName ?? Component.name,
<ide> )})`;
<del> state = {value: spec.getInitialState(this.props)};
<del> _cacheKey = `RNTester:${spec.version || 'v1'}:${spec.cacheKeySuffix(
<add> state: any | {value: State} = {value: spec.getInitialState(this.props)};
<add> _cacheKey: string = `RNTester:${spec.version || 'v1'}:${spec.cacheKeySuffix(
<ide> this.props,
<ide> )}`;
<ide> componentDidMount() { | 66 |
Python | Python | remove outdated error condition | 2189f30001585196634ef22afc395642e3c96f97 | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide> % (availability_zone.name))
<ide> params['Placement.AvailabilityZone'] = availability_zone.name
<ide>
<del> if 'auth' in kwargs and 'ex_keyname' in kwargs:
<del> raise AttributeError('Cannot specify auth and ex_keyname together')
<del>
<ide> if 'auth' in kwargs:
<ide> auth = self._get_and_check_auth(kwargs['auth'])
<ide> key = self.ex_find_or_import_keypair_by_key_material(auth.pubkey, kwargs.get('ex_keyname')) | 1 |
PHP | PHP | remove check for items in apc driver | 24fefe9eb26b202e3cd56c0132e086343d40bd16 | <ide><path>system/cache/driver/apc.php
<ide> public function has($key)
<ide> */
<ide> public function get($key)
<ide> {
<del> if (array_key_exists($key, $this->items))
<del> {
<del> return $this->items[$key];
<del> }
<del>
<ide> $cache = apc_fetch(\System\Config::get('cache.key').$key);
<ide>
<ide> if ($cache === false) | 1 |
Javascript | Javascript | revert a new line i have wrongly removed | 0cd15ca493faf140fe0b73becfcf2273ae67a451 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide> geometries.push( geometry );
<ide>
<ide> }
<add>
<ide> }
<ide>
<ide> return geometries; | 1 |
PHP | PHP | add test case for shorter statement | 682d6179bf8558e93176c03d6532cd744eae8705 | <ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> protected function compileStatements($value)
<ide> {
<ide> $match[0] = $this->$method(array_get($match, 3));
<ide> }
<del> else if (isset($this->statements[$match[1]]))
<add> elseif (isset($this->statements[$match[1]]))
<ide> {
<ide> $match[0] = call_user_func($this->statements[$match[1]], array_get($match, 3));
<ide> }
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testCustomStatements()
<ide> }
<ide>
<ide>
<add> public function testCustomShortStatements()
<add> {
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add> $compiler->addStatement('customControl', function($expression) {
<add> return '<?php echo custom_control(); ?>';
<add> });
<add>
<add> $string = '@customControl';
<add> $expected = '<?php echo custom_control(); ?>';
<add> $this->assertEquals($expected, $compiler->compileString($string));
<add> }
<add>
<add>
<ide> public function testConfiguringContentTags()
<ide> {
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__); | 2 |
Text | Text | remove duplicate issue template | 68092aa311c5f262377fee7681a9a8fc3b92eb33 | <ide><path>.github/ISSUE_TEMPLATE.md
<del><!-- NOTE: If you're reporting a security issue, don't create a GitHub issue. Instead, email security@freecodecamp.org. We will look into it immediately. -->
<del>
<del>#### Describe your problem and - if possible - how to reproduce it
<del>
<del>
<del>#### Add a Link to the page with the problem
<del>
<del>
<del>#### Tell us about your browser and operating system
<del>
<del>* Browser Name:
<del>* Browser Version:
<del>* Operating System:
<del>
<del>
<del>#### If possible, add a screenshot here
<del>
<del> | 1 |
Text | Text | add comment explaining no need for solutions | 5dce06fccb035bb0d8e1bb53919f5a7587c79223 | <ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/announce-new-users.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/authentication-strategies.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/authentication-with-socket.io.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/clean-up-your-project-with-modules.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/communicate-by-emitting.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/create-new-middleware.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/handle-a-disconnect.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/hashing-your-passwords.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/how-to-put-a-profile-together.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/how-to-use-passport-strategies.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/implement-the-serialization-of-a-passport-user.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/implementation-of-social-authentication-ii.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/implementation-of-social-authentication-iii.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/implementation-of-social-authentication.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/logging-a-user-out.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/registration-of-new-users.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/send-and-display-chat-messages.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/serialization-of-a-user-object.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/set-up-a-template-engine.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/set-up-passport.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/set-up-the-environment.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/advanced-node-and-express/use-a-template-engines-powers.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-and-quality-assurance-projects/anonymous-message-board.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-and-quality-assurance-projects/issue-tracker.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-and-quality-assurance-projects/metric-imperial-converter.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-and-quality-assurance-projects/personal-library.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-and-quality-assurance-projects/stock-price-checker.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/ask-browsers-to-access-your-site-via-https-only-with-helmet.hsts.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/avoid-inferring-the-response-mime-type-with-helmet.nosniff.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/configure-helmet-using-the-parent-helmet-middleware.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/disable-client-side-caching-with-helmet.nocache.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/disable-dns-prefetching-with-helmet.dnsprefetchcontrol.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/hash-and-compare-passwords-asynchronously.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/hash-and-compare-passwords-synchronously.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/hide-potentially-dangerous-information-using-helmet.hidepoweredby.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/install-and-require-helmet.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/mitigate-the-risk-of-clickjacking-with-helmet.frameguard.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/mitigate-the-risk-of-cross-site-scripting-xss-attacks-with-helmet.xssfilter.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/prevent-ie-from-opening-untrusted-html-with-helmet.ienoopen.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/set-a-content-security-policy-with-helmet.contentsecuritypolicy.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/information-security-with-helmetjs/understand-bcrypt-hashes.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/assert-deep-equality-with-.deepequal-and-.notdeepequal.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/compare-the-properties-of-two-elements.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/learn-how-javascript-assertions-work.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-an-api-response-using-chai-http-iii---put-method.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-an-api-response-using-chai-http-iv---put-method.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-api-endpoints-using-chai-http-ii.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-on-api-endpoints-using-chai-http.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-using-a-headless-browser-ii.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/run-functional-tests-using-a-headless-browser.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-for-truthiness.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-string-contains-a-substring.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-falls-within-a-specific-range.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-a-string.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-an-array.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-value-is-of-a-specific-data-structure-type.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-a-variable-or-function-is-defined.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-array-contains-an-item.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-object-has-a-property.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-an-object-is-an-instance-of-a-constructor.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/test-if-one-value-is-below-or-at-least-as-large-as-another.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/use-assert.isok-and-assert.isnotok.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/use-regular-expressions-to-test-a-string.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/use-the-double-equals-to-assert-equality.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/06-information-security-and-quality-assurance/quality-assurance-and-testing-with-chai/use-the-triple-equals-to-assert-strict-equality.english.md
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>/**
<add> Backend challenges don't need solutions,
<add> because they would need to be tested against a full working project.
<add> Please check our contributing guidelines to learn more.
<add>*/
<ide> ```
<ide>
<ide> </section> | 65 |
Javascript | Javascript | remove unused variable | c0a77029c4acb60844108fbbd7f5e960b1d81b7c | <ide><path>fixtures/ssr2/src/index.js
<ide> import {hydrateRoot} from 'react-dom';
<ide> import App from './App';
<ide>
<del>const root = hydrateRoot(document, <App assets={window.assetManifest} />);
<add>hydrateRoot(document, <App assets={window.assetManifest} />); | 1 |
Javascript | Javascript | support an array for line chart pointborderwidth | cc9e88aebcbef79f60b560213227792d4324871c | <ide><path>src/controllers/controller.line.js
<ide> module.exports = function(Chart) {
<ide>
<ide> if (!isNaN(custom.borderWidth)) {
<ide> borderWidth = custom.borderWidth;
<del> } else if (!isNaN(dataset.pointBorderWidth)) {
<add> } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) {
<ide> borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
<ide> } else if (!isNaN(dataset.borderWidth)) {
<ide> borderWidth = dataset.borderWidth;
<ide><path>test/specs/controller.line.tests.js
<ide> describe('Line controller tests', function() {
<ide>
<ide> expect(point._model.borderWidth).toBe(0);
<ide> });
<add>
<add> it('should allow an array as the point border width setting', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> data: [10, 15, 0, -4],
<add> label: 'dataset1',
<add> pointBorderWidth: [1, 2, 3, 4]
<add> }],
<add> labels: ['label1', 'label2', 'label3', 'label4']
<add> }
<add> });
<add>
<add> var meta = chart.getDatasetMeta(0);
<add> expect(meta.data[0]._model.borderWidth).toBe(1);
<add> expect(meta.data[1]._model.borderWidth).toBe(2);
<add> expect(meta.data[2]._model.borderWidth).toBe(3);
<add> expect(meta.data[3]._model.borderWidth).toBe(4);
<add> });
<ide> }); | 2 |
Ruby | Ruby | remove dead code in duplicable.rb | 59f450500c37466fe7834cb1d3fa3a6cc8e643b5 | <ide><path>activesupport/lib/active_support/core_ext/object/duplicable.rb
<add>
<ide> # frozen_string_literal: true
<ide>
<ide> #--
<ide> def duplicable?
<ide> end
<ide> end
<ide>
<del>class NilClass
<del> begin
<del> nil.dup
<del> rescue TypeError
<del>
<del> # +nil+ is not duplicable:
<del> #
<del> # nil.duplicable? # => false
<del> # nil.dup # => TypeError: can't dup NilClass
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>class FalseClass
<del> begin
<del> false.dup
<del> rescue TypeError
<del>
<del> # +false+ is not duplicable:
<del> #
<del> # false.duplicable? # => false
<del> # false.dup # => TypeError: can't dup FalseClass
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>class TrueClass
<del> begin
<del> true.dup
<del> rescue TypeError
<del>
<del> # +true+ is not duplicable:
<del> #
<del> # true.duplicable? # => false
<del> # true.dup # => TypeError: can't dup TrueClass
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>class Symbol
<del> begin
<del> :symbol.dup
<del>
<del> # Some symbols couldn't be duped in Ruby 2.4.0 only, due to a bug.
<del> # This feature check catches any regression.
<del> "symbol_from_string".to_sym.dup
<del> rescue TypeError
<del>
<del> # Symbols are not duplicable:
<del> #
<del> # :my_symbol.duplicable? # => false
<del> # :my_symbol.dup # => TypeError: can't dup Symbol
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>class Numeric
<del> begin
<del> 1.dup
<del> rescue TypeError
<del>
<del> # Numbers are not duplicable:
<del> #
<del> # 3.duplicable? # => false
<del> # 3.dup # => TypeError: can't dup Integer
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>require "bigdecimal"
<del>class BigDecimal
<del> # BigDecimals are duplicable:
<del> #
<del> # BigDecimal("1.2").duplicable? # => true
<del> # BigDecimal("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
<del> def duplicable?
<del> true
<del> end
<del>end
<del>
<ide> class Method
<ide> # Methods are not duplicable:
<ide> #
<ide> def duplicable?
<ide> false
<ide> end
<ide> end
<del>
<del>class Complex
<del> begin
<del> Complex(1).dup
<del> rescue TypeError
<del>
<del> # Complexes are not duplicable:
<del> #
<del> # Complex(1).duplicable? # => false
<del> # Complex(1).dup # => TypeError: can't copy Complex
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end
<del>
<del>class Rational
<del> begin
<del> Rational(1).dup
<del> rescue TypeError
<del>
<del> # Rationals are not duplicable:
<del> #
<del> # Rational(1).duplicable? # => false
<del> # Rational(1).dup # => TypeError: can't copy Rational
<del> def duplicable?
<del> false
<del> end
<del> end
<del>end | 1 |
Ruby | Ruby | add some tests for no_color! behavior | 44633dc7a587424d21917413500b2d71fa3d31bb | <ide><path>railties/lib/commands/destroy.rb
<ide> end
<ide>
<ide> name = ARGV.shift
<del>Rails::Generators.invoke name, ARGV, :revoke
<add>Rails::Generators.invoke name, ARGV, :behavior => :revoke
<ide><path>railties/lib/commands/generate.rb
<ide> end
<ide>
<ide> name = ARGV.shift
<del>Rails::Generators.invoke name, ARGV, :invoke
<add>Rails::Generators.invoke name, ARGV, :behavior => :invoke
<ide><path>railties/lib/commands/update.rb
<ide> end
<ide>
<ide> name = ARGV.shift
<del>Rails::Generators.invoke name, ARGV, :skip
<add>Rails::Generators.invoke name, ARGV, :behavior => :skip
<ide><path>railties/lib/generators.rb
<ide> def self.help
<ide> # It's used as the default entry point for generate, destroy and update
<ide> # commands.
<ide> #
<del> def self.invoke(namespace, args=ARGV, behavior=:invoke)
<add> def self.invoke(namespace, args=ARGV, config={})
<ide> if klass = find_by_namespace(namespace, "rails")
<ide> args << "--help" if klass.arguments.any? { |a| a.required? } && args.empty?
<del> klass.start args, :behavior => behavior
<add> klass.start args, config
<ide> else
<ide> puts "Could not find generator #{namespace}."
<ide> end
<ide><path>railties/test/generators_test.rb
<ide> def test_help_when_a_generator_with_required_arguments_is_invoked_without_argume
<ide> assert_match /Description:/, output
<ide> end
<ide>
<del> def test_invoke_with_default_behavior
<del> Rails::Generators::ModelGenerator.expects(:start).with(["Account"], :behavior => :invoke)
<add> def test_invoke_with_default_values
<add> Rails::Generators::ModelGenerator.expects(:start).with(["Account"], {})
<ide> Rails::Generators.invoke :model, ["Account"]
<ide> end
<ide>
<del> def test_invoke_with_given_behavior
<add> def test_invoke_with_config_values
<ide> Rails::Generators::ModelGenerator.expects(:start).with(["Account"], :behavior => :skip)
<del> Rails::Generators.invoke :model, ["Account"], :skip
<add> Rails::Generators.invoke :model, ["Account"], :behavior => :skip
<ide> end
<ide>
<ide> def test_find_by_namespace_without_base_or_context
<ide> def test_rails_generators_with_others_information
<ide> output = capture(:stdout){ Rails::Generators.help }.split("\n").last
<ide> assert_equal "Others: active_record:fixjour, fixjour, rails:javascripts.", output
<ide> end
<add>
<add> def test_no_color_sets_proper_shell
<add> Rails::Generators.no_color!
<add> assert_equal Thor::Shell::Basic, Thor::Base.shell
<add> ensure
<add> Thor::Base.shell = Thor::Shell::Color
<add> end
<ide> end | 5 |
Go | Go | handle cases where onbuild is not uppercase | a34831f0168156ded7ecf96a1734c2735fede1ca | <ide><path>builder/dispatchers.go
<ide> import (
<ide> "fmt"
<ide> "io/ioutil"
<ide> "path/filepath"
<add> "regexp"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/nat"
<ide> func onbuild(b *Builder, args []string, attributes map[string]bool, original str
<ide> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction)
<ide> }
<ide>
<del> original = strings.TrimSpace(strings.TrimLeft(original, "ONBUILD"))
<add> original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "")
<ide>
<ide> b.Config.OnBuild = append(b.Config.OnBuild, original)
<ide> return b.commit("", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original))
<ide><path>integration-cli/docker_cli_build_test.go
<ide> import (
<ide> "github.com/docker/docker/pkg/archive"
<ide> )
<ide>
<add>func TestBuildOnBuildLowercase(t *testing.T) {
<add> name := "testbuildonbuildlowercase"
<add> name2 := "testbuildonbuildlowercase2"
<add>
<add> defer deleteImages(name, name2)
<add>
<add> _, err := buildImage(name,
<add> `
<add> FROM busybox
<add> onbuild run echo quux
<add> `, true)
<add>
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> _, out, err := buildImageWithOut(name2, fmt.Sprintf(`
<add> FROM %s
<add> `, name), true)
<add>
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if !strings.Contains(out, "quux") {
<add> t.Fatalf("Did not receive the expected echo text, got %s", out)
<add> }
<add>
<add> if strings.Contains(out, "ONBUILD ONBUILD") {
<add> t.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", out)
<add> }
<add>
<add> logDone("build - handle case-insensitive onbuild statement")
<add>}
<add>
<ide> func TestBuildEnvEscapes(t *testing.T) {
<ide> name := "testbuildenvescapes"
<ide> defer deleteAllContainers() | 2 |
Java | Java | eliminate aj @async warning in test case | cf68cc5f0b2650bb1cd34064d7e43747f79285a4 | <ide><path>spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java
<ide> public class AnnotationAsyncExecutionAspectTests {
<ide>
<ide> @Before
<ide> public void setUp() {
<add> Assume.group(TestGroup.PERFORMANCE);
<add>
<ide> executor = new CountingExecutor();
<ide> AnnotationAsyncExecutionAspect.aspectOf().setExecutor(executor);
<ide> }
<ide>
<ide> @Test
<ide> public void asyncMethodGetsRoutedAsynchronously() {
<del> Assume.group(TestGroup.PERFORMANCE);
<del>
<ide> ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation();
<ide> obj.incrementAsync();
<ide> executor.waitForCompletion();
<ide> public void methodReturningFutureInAsyncClassGetsRoutedAsynchronouslyAndReturnsA
<ide> assertEquals(1, executor.submitCompleteCounter);
<ide> }
<ide>
<add> /*
<ide> @Test
<ide> public void methodReturningNonVoidNonFutureInAsyncClassGetsRoutedSynchronously() {
<ide> ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation();
<ide> public void methodReturningNonVoidNonFutureInAsyncClassGetsRoutedSynchronously()
<ide> assertEquals(0, executor.submitStartCounter);
<ide> assertEquals(0, executor.submitCompleteCounter);
<ide> }
<add> */
<ide>
<ide> @Test
<ide> public void qualifiedAsyncMethodsAreRoutedToCorrectExecutor() throws InterruptedException, ExecutionException {
<ide> public void increment() {
<ide>
<ide> // Manually check that there is a warning from the 'declare warning' statement in
<ide> // AnnotationAsyncExecutionAspect
<add> /*
<ide> public int return5() {
<ide> return 5;
<ide> }
<add> */
<ide>
<ide> public Future<Integer> incrementReturningAFuture() {
<ide> counter++; | 1 |
Javascript | Javascript | dump the stack with unhandled rejections | 97a40252dcec831158c29c86bc84000f9546173d | <ide><path>src/util.js
<ide> var Promise = PDFJS.Promise = (function PromiseClosure() {
<ide> var now = Date.now();
<ide> for (var i = 0; i < this.unhandledRejections.length; i++) {
<ide> if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
<del> warn('Unhandled rejection: ' +
<del> this.unhandledRejections[i].promise._value);
<add> var unhandled = this.unhandledRejections[i].promise._value;
<add> var msg = 'Unhandled rejection: ' + unhandled;
<add> if (unhandled.stack) {
<add> msg += '\n' + unhandled.stack;
<add> }
<add> warn(msg);
<ide> this.unhandledRejections.splice(i);
<ide> i--;
<ide> } | 1 |
Javascript | Javascript | implement module concatenation for json modules | bd2106b512d496b5430dde39bec24987b1bf1bf5 | <ide><path>lib/json/JsonGenerator.js
<ide>
<ide> "use strict";
<ide>
<del>const { ConcatSource, RawSource } = require("webpack-sources");
<add>const { RawSource } = require("webpack-sources");
<add>const ConcatenationScope = require("../ConcatenationScope");
<ide> const { UsageState } = require("../ExportsInfo");
<ide> const Generator = require("../Generator");
<ide> const RuntimeGlobals = require("../RuntimeGlobals");
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../ExportsInfo")} ExportsInfo */
<ide> /** @typedef {import("../Generator").GenerateContext} GenerateContext */
<add>/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
<ide> /** @typedef {import("../NormalModule")} NormalModule */
<ide> /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
<ide>
<ide> class JsonGenerator extends Generator {
<ide> return stringifySafe(data).length + 10;
<ide> }
<ide>
<add> /**
<add> * @param {NormalModule} module module for which the bailout reason should be determined
<add> * @param {ConcatenationBailoutReasonContext} context context
<add> * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
<add> */
<add> getConcatenationBailoutReason(module, context) {
<add> return undefined;
<add> }
<add>
<ide> /**
<ide> * @param {NormalModule} module module for which the code should be generated
<ide> * @param {GenerateContext} generateContext context for generate
<ide> * @returns {Source} generated code
<ide> */
<ide> generate(
<ide> module,
<del> { moduleGraph, runtimeTemplate, runtimeRequirements, runtime }
<add> {
<add> moduleGraph,
<add> runtimeTemplate,
<add> runtimeRequirements,
<add> runtime,
<add> concatenationScope
<add> }
<ide> ) {
<del> const source = new ConcatSource();
<ide> const data = module.buildInfo.jsonData;
<ide> if (data === undefined) {
<ide> return new RawSource(
<ide> class JsonGenerator extends Generator {
<ide> })
<ide> );
<ide> }
<del> runtimeRequirements.add(RuntimeGlobals.module);
<ide> const exportsInfo = moduleGraph.getExportsInfo(module);
<ide> let finalJson =
<ide> typeof data === "object" &&
<ide> class JsonGenerator extends Generator {
<ide> jsonStr.length > 20 && typeof finalJson === "object"
<ide> ? `JSON.parse(${JSON.stringify(jsonStr)})`
<ide> : jsonStr;
<del> source.add(`${module.moduleArgument}.exports = ${jsonExpr};`);
<del> return source;
<add> let content;
<add> if (concatenationScope) {
<add> content = `${runtimeTemplate.supportsConst() ? "const" : "var"} ${
<add> ConcatenationScope.NAMESPACE_OBJECT_EXPORT
<add> } = ${jsonExpr};`;
<add> concatenationScope.registerNamespaceExport(
<add> ConcatenationScope.NAMESPACE_OBJECT_EXPORT
<add> );
<add> } else {
<add> runtimeRequirements.add(RuntimeGlobals.module);
<add> content = `${module.moduleArgument}.exports = ${jsonExpr};`;
<add> }
<add> return new RawSource(content);
<ide> }
<ide> }
<ide> | 1 |
Python | Python | add support for python 3.4 ast.nameconstant | 0b7191397e7893011fda16402e1fbd56afb911d3 | <ide><path>numpy/lib/utils.py
<ide> def visitName(self, node):
<ide> else:
<ide> raise SyntaxError("Unknown name: %s" % node.id)
<ide>
<add> def visitNameConstant(self, node):
<add> return node.value
<add>
<ide> def safe_eval(source):
<ide> """
<ide> Protected string evaluation. | 1 |
PHP | PHP | apply fixes from styleci | eaf9db5d1f079a02aa6536c09481d138754fb7f8 | <ide><path>src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php
<ide> protected function writeErrorAndDie(InvalidFileException $e)
<ide> $output->writeln('The environment file is invalid!');
<ide> $output->writeln($e->getMessage());
<ide>
<del> die(1);
<add> exit(1);
<ide> }
<ide> }
<ide><path>src/Illuminate/Queue/Listener.php
<ide> public function memoryExceeded($memoryLimit)
<ide> */
<ide> public function stop()
<ide> {
<del> die;
<add> exit;
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Support/Traits/EnumeratesValues.php
<ide> public function dd(...$args)
<ide> {
<ide> call_user_func_array([$this, 'dump'], $args);
<ide>
<del> die(1);
<add> exit(1);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Queue/RedisQueueIntegrationTest.php
<ide> public function testBlockingPop($driver)
<ide> $this->setQueue('phpredis');
<ide> sleep(1);
<ide> $this->queue->push(new RedisQueueIntegrationTestJob(12));
<del> die;
<add> exit;
<ide> } else {
<ide> $this->fail('Cannot fork');
<ide> } | 4 |
Text | Text | add marsonya as a triager | 3bba40abc636ff50b03930cb510f7d1082272563 | <ide><path>README.md
<ide> maintaining the Node.js project.
<ide>
<ide> ### Triagers
<ide>
<add>* [marsonya](https://github.com/marsonya) -
<add>**Akhil Marsonya** <akhil.marsonya27@gmail.com> (he/him)
<ide> * [PoojaDurgad](https://github.com/PoojaDurgad) -
<ide> **Pooja Durgad** <Pooja.D.P@ibm.com>
<ide> * [RaisinTen](https://github.com/RaisinTen) - | 1 |
Python | Python | remove trailing whitespace | 93b41a2f6082ee7293c45c7538d898369e158a61 | <ide><path>numpy/core/tests/test_datetime.py
<ide> class TestDateTime(TestCase):
<ide> def test_creation(self):
<ide> for unit in ['Y', 'M', 'W', 'B', 'D',
<ide> 'h', 'm', 's', 'ms', 'us',
<del> 'ns', 'ps', 'fs', 'as']:
<add> 'ns', 'ps', 'fs', 'as']:
<ide> dt1 = np.dtype('M8[750%s]'%unit)
<ide> assert dt1 == np.dtype('datetime64[750%s]' % unit)
<ide> dt2 = np.dtype('m8[%s]' % unit)
<ide> assert dt2 == np.dtype('timedelta64[%s]' % unit)
<del>
<add>
<ide> def test_divisor_conversion_year(self):
<ide> assert np.dtype('M8[Y/4]') == np.dtype('M8[3M]')
<ide> assert np.dtype('M8[Y/13]') == np.dtype('M8[4W]')
<ide> def test_divisor_conversion_week(self):
<ide> assert np.dtype('m8[W/5]') == np.dtype('m8[B]')
<ide> assert np.dtype('m8[W/7]') == np.dtype('m8[D]')
<ide> assert np.dtype('m8[3W/14]') == np.dtype('m8[36h]')
<del> assert np.dtype('m8[5W/140]') == np.dtype('m8[360m]')
<del>
<add> assert np.dtype('m8[5W/140]') == np.dtype('m8[360m]')
<add>
<ide> def test_divisor_conversion_bday(self):
<ide> assert np.dtype('M8[B/12]') == np.dtype('M8[2h]')
<ide> assert np.dtype('M8[B/120]') == np.dtype('M8[12m]')
<ide> def test_divisor_conversion_fs(self):
<ide>
<ide> def test_divisor_conversion_as(self):
<ide> self.assertRaises(ValueError, lambda : np.dtype('M8[as/10]'))
<del> | 1 |
Javascript | Javascript | remove needless expression | ec75705f88dd4b44ec133d5167b69e88c175bb24 | <ide><path>src/manipulation.js
<ide> jQuery.extend({
<ide> // Deserialize a standard representation
<ide> tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase();
<ide> wrap = wrapMap[ tag ] || wrapMap._default;
<del> tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + ( wrap[ 2 ] || "" );
<add> tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" );
<ide>
<ide> // Descend through wrappers to the right content
<ide> j = wrap[0]; | 1 |
Text | Text | add redux-falcor to ecosystem | 4e0e5eb0ecd23d798e4e66bbe7a357e4cc23c9f4 | <ide><path>docs/introduction/Ecosystem.md
<ide> On this page we will only feature a few of them that the Redux maintainers have
<ide> * [ng-redux](https://github.com/wbuchwalter/ng-redux) — Angular
<ide> * [ng2-redux](https://github.com/wbuchwalter/ng2-redux) — Angular 2
<ide> * [backbone-redux](https://github.com/redbooth/backbone-redux) — Backbone
<add>* [redux-falcor](https://github.com/ekosz/redux-falcor) — Falcor
<ide>
<ide> ## Middleware
<ide> | 1 |
Javascript | Javascript | add spec for accessibilitymanager | 71461cb3dd4ad40dbe4de656bfec4b1a614ffa95 | <ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.ios.js
<ide>
<ide> 'use strict';
<ide>
<del>const NativeModules = require('../../BatchedBridge/NativeModules');
<add>import NativeAccessibilityManager from './NativeAccessibilityManager';
<add>
<ide> const Promise = require('../../Promise');
<ide> const RCTDeviceEventEmitter = require('../../EventEmitter/RCTDeviceEventEmitter');
<ide>
<del>const AccessibilityManager = NativeModules.AccessibilityManager;
<del>
<ide> const CHANGE_EVENT_NAME = {
<ide> announcementFinished: 'announcementFinished',
<ide> boldTextChanged: 'boldTextChanged',
<ide> const AccessibilityInfo = {
<ide> */
<ide> isBoldTextEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentBoldTextState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentBoldTextState(resolve, reject);
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> */
<ide> isGrayscaleEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentGrayscaleState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentGrayscaleState(resolve, reject);
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> */
<ide> isInvertColorsEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentInvertColorsState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentInvertColorsState(resolve, reject);
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> */
<ide> isReduceMotionEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentReduceMotionState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentReduceMotionState(resolve, reject);
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> */
<ide> isReduceTransparencyEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentReduceTransparencyState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentReduceTransparencyState(
<add> resolve,
<add> reject,
<add> );
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> */
<ide> isScreenReaderEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> AccessibilityManager.getCurrentVoiceOverState(resolve, reject);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.getCurrentVoiceOverState(resolve, reject);
<add> } else {
<add> reject(reject);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#setaccessibilityfocus
<ide> */
<ide> setAccessibilityFocus: function(reactTag: number): void {
<del> AccessibilityManager.setAccessibilityFocus(reactTag);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.setAccessibilityFocus(reactTag);
<add> }
<ide> },
<ide>
<ide> /**
<ide> const AccessibilityInfo = {
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#announceforaccessibility
<ide> */
<ide> announceForAccessibility: function(announcement: string): void {
<del> AccessibilityManager.announceForAccessibility(announcement);
<add> if (NativeAccessibilityManager) {
<add> NativeAccessibilityManager.announceForAccessibility(announcement);
<add> }
<ide> },
<ide>
<ide> /**
<ide><path>Libraries/Components/AccessibilityInfo/NativeAccessibilityManager.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +getCurrentBoldTextState: (
<add> onSuccess: (isBoldTextEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +getCurrentGrayscaleState: (
<add> onSuccess: (isGrayscaleEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +getCurrentInvertColorsState: (
<add> onSuccess: (isInvertColorsEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +getCurrentReduceMotionState: (
<add> onSuccess: (isReduceMotionEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +getCurrentReduceTransparencyState: (
<add> onSuccess: (isReduceTransparencyEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +getCurrentVoiceOverState: (
<add> onSuccess: (isScreenReaderEnabled: boolean) => void,
<add> onError: (error: Object) => void,
<add> ) => void;
<add> +setAccessibilityFocus: (reactTag: number) => void;
<add> +announceForAccessibility: (announcement: string) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('AccessibilityManager'); | 2 |
Text | Text | describe rem unit for font-size | 810d6d398563fc68447d0916f94e2fe985b3966a | <ide><path>guide/english/css/fonts/index.md
<ide> p {
<ide> font-family: "Times New Roman", Times, serif;
<ide> }
<ide> ```
<del>In the above example, "Times New Roman" is the *family-name* of the font, while "serif" is the *generic-name*. Generic names are used as a fallback mechanism for preserving style if the family-name is unavailable. A generic name should always be the last item in the list of font family names.
<add>In the above example, "Times New Roman" is the *family-name* of the font, while "serif" is the *generic-name*. Generic names are used as a fallback mechanism for preserving style if the family-name is unavailable. A generic name should always be the last item in the list of font family names.
<ide>
<ide> Generic family names are:
<ide> * serif
<ide> There are different types of font size values:
<ide>
<ide> * `px` (pixels) - The default size of text being `16px`
<ide> * `em` - based on the current or inherited font size of an element
<del>* `rem` - like `em`, but always based on the base font-size of the document
<add>* `rem` - like `em`, but based on the base font-size of the document
<ide> * `small`, `medium`, `large` - known as absolute size values
<ide> * `%` - percentages
<ide>
<ide> The `font-weight`property specifies the weight (or boldness) of the font. Accept
<ide>
<ide> ```css
<ide> p {
<del> font-weight: bold
<add> font-weight: bold;
<ide> }
<ide> ```
<ide> | 1 |
Ruby | Ruby | change the hash.to_xml with a lamda example | b00c69cd1f0b0143ad8e6b92c982c106845583c7 | <ide><path>activesupport/lib/active_support/core_ext/hash/conversions.rb
<ide> class Hash
<ide> # with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
<ide> # callable can add nodes by using <tt>options[:builder]</tt>.
<ide> #
<del> # 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
<add> # {foo: lambda { |options, key| options[:builder].b(key) }}.to_xml
<ide> # # => "<b>foo</b>"
<ide> #
<ide> # * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>. | 1 |
Text | Text | fix doc notebooks links | 691cdbb7d723a32f5a53a2954fb4b24a79903357 | <ide><path>notebooks/README.md
<ide> You can open any page of the documentation as a notebook in colab (there is a bu
<ide>
<ide> | Notebook | Description | | |
<ide> |:----------|:-------------|:-------------|------:|
<del>| [Quicktour of the library](https://github.com/huggingface/notebooks/blob/main/transformers_doc/quicktour.ipynb) | A presentation of the various APIs in Transformers |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/quicktour.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/quicktour.ipynb)|
<del>| [Summary of the tasks](https://github.com/huggingface/notebooks/blob/main/transformers_doc/task_summary.ipynb) | How to run the models of the Transformers library task by task |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/task_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/task_summary.ipynb)|
<del>| [Preprocessing data](https://github.com/huggingface/notebooks/blob/main/transformers_doc/preprocessing.ipynb) | How to use a tokenizer to preprocess your data |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/preprocessing.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/preprocessing.ipynb)|
<del>| [Fine-tuning a pretrained model](https://github.com/huggingface/notebooks/blob/main/transformers_doc/training.ipynb) | How to use the Trainer to fine-tune a pretrained model |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/training.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/training.ipynb)|
<del>| [Summary of the tokenizers](https://github.com/huggingface/notebooks/blob/main/transformers_doc/tokenizer_summary.ipynb) | The differences between the tokenizers algorithm |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/tokenizer_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/tokenizer_summary.ipynb)|
<del>| [Multilingual models](https://github.com/huggingface/notebooks/blob/main/transformers_doc/multilingual.ipynb) | How to use the multilingual models of the library |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/multilingual.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/multilingual.ipynb)|
<del>| [Fine-tuning with custom datasets](https://github.com/huggingface/notebooks/blob/main/transformers_doc/custom_datasets.ipynb) | How to fine-tune a pretrained model on various tasks |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/custom_datasets.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/custom_datasets.ipynb)|
<add>| [Quicktour of the library](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb) | A presentation of the various APIs in Transformers |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quicktour.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/en/transformers_doc/quicktour.ipynb)|
<add>| [Summary of the tasks](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb) | How to run the models of the Transformers library task by task |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/task_summary.ipynb)|
<add>| [Preprocessing data](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb) | How to use a tokenizer to preprocess your data |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/preprocessing.ipynb)|
<add>| [Fine-tuning a pretrained model](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb) | How to use the Trainer to fine-tune a pretrained model |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/training.ipynb)|
<add>| [Summary of the tokenizers](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb) | The differences between the tokenizers algorithm |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tokenizer_summary.ipynb)|
<add>| [Multilingual models](https://github.com/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb) | How to use the multilingual models of the library |[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)| [](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/multilingual.ipynb)|
<add>
<ide>
<ide> ### PyTorch Examples
<ide> | 1 |
Javascript | Javascript | return an empty string for empty sections | 6d5e3865e748dad308317b27fd28411464986378 | <ide><path>client/src/templates/Challenges/components/Challenge-Description.js
<ide> const propTypes = {
<ide> section: PropTypes.string
<ide> };
<ide>
<del>function emptyInstruction(instructions) {
<del> return /^<section\s+id\s*=\s*("|')instructions\1\s*>\s*<\/section>$/.test(
<del> instructions
<del> );
<del>}
<del>
<ide> function ChallengeDescription({ description, instructions, section }) {
<ide> return (
<ide> <div className={`challenge-instructions ${section}`}>
<ide> <div dangerouslySetInnerHTML={{ __html: description }} />
<del> {!emptyInstruction(instructions) && (
<add> {instructions && (
<ide> <Fragment>
<ide> <hr />
<ide> <div dangerouslySetInnerHTML={{ __html: instructions }} />
<ide><path>curriculum/schema/challengeSchema.js
<ide> const Joi = require('joi');
<ide> Joi.objectId = require('joi-objectid')(Joi);
<ide>
<add>const { challengeTypes } = require('../../client/utils/challengeTypes');
<add>
<ide> function getSchemaForLang(lang) {
<ide> let schema = Joi.object().keys({
<ide> block: Joi.string(),
<ide> function getSchemaForLang(lang) {
<ide> .required(),
<ide> checksum: Joi.number(),
<ide> dashedName: Joi.string(),
<del> description: Joi.string().required(),
<add> description: Joi.when('challengeType', {
<add> is: challengeTypes.step,
<add> then: Joi.string().allow(''),
<add> otherwise: Joi.string().required()
<add> }),
<ide> fileName: Joi.string(),
<ide> files: Joi.array().items(
<ide> Joi.object().keys({
<ide> function getSchemaForLang(lang) {
<ide> videoUrl: Joi.string().allow(''),
<ide> helpRoom: Joi.string(),
<ide> id: Joi.objectId().required(),
<del> instructions: Joi.string().required(),
<add> instructions: Joi.string().allow(''),
<ide> isBeta: Joi.bool(),
<ide> isComingSoon: Joi.bool(),
<ide> isLocked: Joi.bool(),
<ide><path>tools/challenge-md-parser/text-to-data.js
<ide> function textToData(sectionIds) {
<ide> }
<ide> }
<ide> });
<del> const textArray = toHTML({ ...node, children: newChildren });
<add> const hasData = newChildren.some(
<add> node => node.type !== 'text' || !/^\s*$/.test(node.value)
<add> );
<add> const textArray = hasData
<add> ? toHTML({ ...node, children: newChildren })
<add> : '';
<ide> file.data = {
<ide> ...file.data,
<ide> [sectionId]: textArray | 3 |
Ruby | Ruby | remove tests that tree manager takes an engine | 0e71d45b00208c7e62b8bd358392725f215e833a | <ide><path>activerecord/test/cases/arel/delete_manager_test.rb
<ide>
<ide> module Arel
<ide> class DeleteManagerTest < Arel::Spec
<del> describe "new" do
<del> it "takes an engine" do
<del> Arel::DeleteManager.new
<del> end
<del> end
<del>
<ide> it "handles limit properly" do
<ide> table = Table.new(:users)
<ide> dm = Arel::DeleteManager.new
<ide><path>activerecord/test/cases/arel/insert_manager_test.rb
<ide>
<ide> module Arel
<ide> class InsertManagerTest < Arel::Spec
<del> describe "new" do
<del> it "takes an engine" do
<del> Arel::InsertManager.new
<del> end
<del> end
<del>
<ide> describe "insert" do
<ide> it "can create a ValuesList node" do
<ide> manager = Arel::InsertManager.new
<ide><path>activerecord/test/cases/arel/update_manager_test.rb
<ide>
<ide> module Arel
<ide> class UpdateManagerTest < Arel::Spec
<del> describe "new" do
<del> it "takes an engine" do
<del> Arel::UpdateManager.new
<del> end
<del> end
<del>
<ide> it "should not quote sql literals" do
<ide> table = Table.new(:users)
<ide> um = Arel::UpdateManager.new | 3 |
Javascript | Javascript | make code-uri more robust | 415a39ea17f9944f6679bf4a7489427d49248570 | <ide><path>client/commonFramework/code-uri.js
<ide> window.common = (function(global) {
<ide> replaceFccfaaAttr
<ide> } = common;
<ide>
<add> const queryRegex = /^(\?|#\?)/;
<ide> function encodeFcc(val) {
<ide> return replaceScriptTags(replaceFormActionAttr(val));
<ide> }
<ide> window.common = (function(global) {
<ide> return false;
<ide> }
<ide> return decoded
<del> .split('?')
<del> .splice(1)
<del> .pop()
<add> .replace(queryRegex, '')
<ide> .split('&')
<ide> .reduce(function(found, param) {
<ide> var key = param.split('=')[0];
<ide> window.common = (function(global) {
<ide> .split('&')
<ide> .reduce(function(oldValue, param) {
<ide> var key = param.split('=')[0];
<del> var value = param.split('=')[1];
<add> var value = param
<add> .split('=')
<add> .slice(1)
<add> .join('=');
<add>
<ide> if (key === keyToFind) {
<ide> return value;
<ide> }
<ide> window.common = (function(global) {
<ide> enabled: true,
<ide> shouldRun() {
<ide> return !this.getKeyInQuery(
<del> (location.search || location.hash).replace(/^(\?|#\?)/, ''),
<add> (location.search || location.hash).replace(queryRegex, ''),
<ide> 'run'
<ide> );
<ide> } | 1 |
Ruby | Ruby | remove an unnecessary default argument | 566442606a817ceaa3d3e305b53f5f2634e3e793 | <ide><path>Library/Homebrew/dependency.rb
<ide> def satisfied?(inherited_options)
<ide> installed? && missing_options(inherited_options).empty?
<ide> end
<ide>
<del> def missing_options(inherited_options=[])
<add> def missing_options(inherited_options)
<ide> missing = options | inherited_options
<ide> missing -= Tab.for_formula(to_formula).used_options
<ide> missing | 1 |
Python | Python | fix param rendering in docs of sparksubmithook | 6322dad2caa0e5b4d339c5d9a73ec7ff3fd4bc25 | <ide><path>airflow/providers/apache/spark/hooks/spark_submit.py
<ide> class SparkSubmitHook(BaseHook, LoggingMixin):
<ide> comma. Files will be placed in the working directory of each executor.
<ide> For example, serialized objects.
<ide> :param py_files: Additional python files used by the job, can be .zip, .egg or .py.
<del> :param: archives: Archives that spark should unzip (and possibly tag with #ALIAS) into
<add> :param archives: Archives that spark should unzip (and possibly tag with #ALIAS) into
<ide> the application working directory.
<ide> :param driver_class_path: Additional, driver-specific, classpath settings.
<ide> :param jars: Submit additional jars to upload and place them in executor classpath. | 1 |
Java | Java | create java implementation of turbo modules | 38bea0bbf38c7c54c7c1d3b5a6665ddece7f8229 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> import com.facebook.react.bridge.CatalystInstanceImpl;
<ide> import com.facebook.react.bridge.JSBundleLoader;
<ide> import com.facebook.react.bridge.JSIModulePackage;
<add>import com.facebook.react.bridge.JSIModuleRegistry;
<ide> import com.facebook.react.bridge.JavaJSExecutor;
<ide> import com.facebook.react.bridge.JavaScriptExecutor;
<ide> import com.facebook.react.bridge.JavaScriptExecutorFactory;
<ide> private void attachRootViewToInstance(
<ide> Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()");
<ide> Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance");
<ide> UIManager uiManagerModule = UIManagerHelper.getUIManager(mCurrentReactContext, rootView.getUIManagerType());
<add>
<ide> final int rootTag = uiManagerModule.addRootView(rootView);
<ide> rootView.setRootViewTag(rootTag);
<ide> rootView.runApplication(); | 1 |
Text | Text | add comment to use stack overflow before jira | a0bba453da6e10c9b8d3c5822032b01cf5dcfd5f | <ide><path>CONTRIBUTING.md
<ide> request; this will save time for everyone!_
<ide> Not sure what a pull request is, or how to submit one? Take a look at GitHub's
<ide> excellent [help documentation][] first.
<ide>
<add>### Check and/or Discuss on Stack Overflow first
<ide>
<del>### Search JIRA first; create an issue if necessary
<add>If you're unsure why something doesn't work or wondering if there is a better
<add>way of doing something please check on Stack Overflow first. If necessary start
<add>a discussion and do the necessary homework. Before creating a ticket in the
<add>Spring Framework issue tracker you should have a reasinably good sense that
<add>there there is a problem or a missing feature.
<add>
<add>### Search JIRA; create an issue if necessary
<ide>
<ide> Is there already an issue that addresses your concern? Do a bit of searching
<ide> in our [JIRA issue tracker][] to see if you can find something similar. If you | 1 |
PHP | PHP | apply fixes from styleci | fc46309cfa4678f06acf0a91a5eee34d33f3516d | <ide><path>src/Illuminate/Foundation/Providers/FoundationServiceProvider.php
<ide> public function registerRequestSignatureValidation()
<ide> });
<ide>
<ide> Request::macro('hasValidSignatureWhileIgnoring', function ($ignoreQuery = [], $absolute = true) {
<del> return URL::hasValidSignature($this, $absolute, $ignoreQuery);
<del> });
<add> return URL::hasValidSignature($this, $absolute, $ignoreQuery);
<add> });
<ide> }
<ide> } | 1 |
Go | Go | fix host header on stream commands | e457b21db32359af085b04b5900ca6aab993ac86 | <ide><path>api/client/utils.go
<ide> func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in
<ide> in = bytes.NewReader([]byte{})
<ide> }
<ide>
<del> req, err := http.NewRequest(method, fmt.Sprintf("http://v%s%s", api.APIVERSION, path), in)
<add> req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), in)
<ide> if err != nil {
<ide> return err
<ide> } | 1 |
PHP | PHP | remove unused property | 6da050fc7084cb2efa9b433340c9c5546e44ec3b | <ide><path>tests/TestCase/Shell/Task/LoadTaskTest.php
<ide> */
<ide> class LoadTaskTest extends ConsoleIntegrationTestCase
<ide> {
<del> /**
<del> * @var \Cake\Shell\Task\LoadTask|\PHPUnit_Framework_MockObject_MockObject
<del> */
<del> protected $Task;
<del>
<ide> /**
<ide> * setUp method
<ide> * | 1 |
Ruby | Ruby | remove redundant \s* in mime type regexp | ba0d473ed955a099ed329bb11fc4b05ca9498bd1 | <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb
<ide> def unregister(symbol)
<ide> MIME_NAME = "[a-zA-Z0-9][a-zA-Z0-9#{Regexp.escape('!#$&-^_.+')}]{0,126}"
<ide> MIME_PARAMETER_VALUE = "#{Regexp.escape('"')}?#{MIME_NAME}#{Regexp.escape('"')}?"
<ide> MIME_PARAMETER = "\s*\;\s*#{MIME_NAME}(?:\=#{MIME_PARAMETER_VALUE})?"
<del> MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?>\s*#{MIME_PARAMETER}\s*)*)\z/
<add> MIME_REGEXP = /\A(?:\*\/\*|#{MIME_NAME}\/(?:\*|#{MIME_NAME})(?>#{MIME_PARAMETER})*\s*)\z/
<ide>
<ide> class InvalidMimeType < StandardError; end
<ide> | 1 |
Go | Go | pull missing images on run. addresses #31 | f6d64738d05d62596d94a5567916e3b3b5209b2c | <ide><path>server/server.go
<ide> func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string)
<ide> fl_tty := cmd.Bool("t", false, "Allocate a pseudo-tty")
<ide> fl_comment := cmd.String("c", "", "Comment")
<ide> var fl_ports ports
<add> var img *image.Image
<add>
<ide> cmd.Var(&fl_ports, "p", "Map a network port to the container")
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide> func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string)
<ide> *fl_attach = true
<ide> cmdline = []string{"/bin/bash", "-i"}
<ide> }
<add>
<ide> // Find the image
<del> img := srv.images.Find(name)
<add> img = srv.images.Find(name)
<ide> if img == nil {
<del> return errors.New("No such image: " + name)
<add> devnull, err := os.Open("/dev/null")
<add> if err != nil {
<add> return errors.New("Error opening /dev/null")
<add> }
<add> if srv.CmdPull(devnull, stdout, name) != nil {
<add> return errors.New("Error downloading image: " + name)
<add> }
<add> img = srv.images.Find(name)
<ide> }
<add>
<ide> // Create new container
<ide> container, err := srv.CreateContainer(img, fl_ports, *fl_user, *fl_tty, *fl_stdin, *fl_comment, cmdline[0], cmdline[1:]...)
<ide> if err != nil { | 1 |
Python | Python | set gold.sent_starts in ud_train | eddc0e0c74491dc3ed14c51ea17b8d5b76b51bd5 | <ide><path>spacy/cli/ud_train.py
<ide> def read_conllu(file_):
<ide> return docs
<ide>
<ide>
<del>def _make_gold(nlp, text, sent_annots):
<add>def _make_gold(nlp, text, sent_annots, drop_deps=0.0):
<ide> # Flatten the conll annotations, and adjust the head indices
<ide> flat = defaultdict(list)
<add> sent_starts = []
<ide> for sent in sent_annots:
<ide> flat['heads'].extend(len(flat['words'])+head for head in sent['heads'])
<ide> for field in ['words', 'tags', 'deps', 'entities', 'spaces']:
<ide> flat[field].extend(sent[field])
<add> sent_starts.append(True)
<add> sent_starts.extend([False] * (len(sent['words'])-1))
<ide> # Construct text if necessary
<ide> assert len(flat['words']) == len(flat['spaces'])
<ide> if text is None:
<ide> text = ''.join(word+' '*space for word, space in zip(flat['words'], flat['spaces']))
<ide> doc = nlp.make_doc(text)
<ide> flat.pop('spaces')
<ide> gold = GoldParse(doc, **flat)
<add> gold.sent_starts = sent_starts
<add> for i in range(len(gold.heads)):
<add> if random.random() < drop_deps:
<add> gold.heads[i] = None
<add> gold.labels[i] = None
<add>
<ide> return doc, gold
<ide>
<ide> ############################# | 1 |
Ruby | Ruby | remove redundant `all.scoping` | 334c4c533f427e126acb1edb561ad6fabea216de | <ide><path>activerecord/lib/active_record/scoping/named.rb
<ide> def scope(name, body, &block)
<ide>
<ide> if body.respond_to?(:to_proc)
<ide> singleton_class.send(:define_method, name) do |*args|
<del> scope = all
<del> scope = scope._exec_scope(*args, &body)
<add> scope = all._exec_scope(*args, &body)
<ide> scope = scope.extending(extension) if extension
<ide> scope
<ide> end
<ide> else
<ide> singleton_class.send(:define_method, name) do |*args|
<del> scope = all
<del> scope = scope.scoping { body.call(*args) || scope }
<add> scope = body.call(*args) || all
<ide> scope = scope.extending(extension) if extension
<ide> scope
<ide> end | 1 |
Ruby | Ruby | use friendlier method name | 16bee7618c328ecd790db366221639661912c477 | <ide><path>activesupport/lib/active_support/multibyte/chars.rb
<ide> def compose
<ide> #
<ide> # Example:
<ide> # 'क्षि'.mb_chars.length # => 4
<del> # 'क्षि'.mb_chars.g_length # => 3
<del> def g_length
<add> # 'क्षि'.mb_chars.grapheme_length # => 3
<add> def grapheme_length
<ide> Unicode.unpack_graphemes(@wrapped_string).length
<ide> end
<ide>
<ide><path>activesupport/test/multibyte_chars_test.rb
<ide> def test_should_compute_grapheme_length
<ide> else
<ide> str = input
<ide> end
<del> assert_equal expected_length, chars(str).g_length
<add> assert_equal expected_length, chars(str).grapheme_length
<ide> end
<ide> end
<ide> | 2 |
Python | Python | add session hook for benchmark metric logging. | 4b85dab1e9d3a4c541d873cb473ee2e82dd810c9 | <ide><path>official/utils/logging/metric_hook.py
<add># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Session hook for logging benchmark metric."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import tensorflow as tf
<add>
<add>from official.utils.logging import logger
<add>
<add>
<add>class LoggingMetricHook(tf.train.LoggingTensorHook):
<add> """Hook to log benchmark metric information.
<add>
<add> This hook is very similar as tf.train.LoggingTensorHook, which logs given
<add> tensors every N local steps, every N seconds, or at the end. The metric
<add> information will be logged to given log_dir or via metric_logger in JSON
<add> format, which can be consumed by data analysis pipeline later.
<add>
<add> Note that if `at_end` is True, `tensors` should not include any tensor
<add> whose evaluation produces a side effect such as consuming additional inputs.
<add> """
<add>
<add> def __init__(self, tensors, log_dir=None, metric_logger=None,
<add> every_n_iter=None, every_n_secs=None, at_end=False):
<add> """Initializer for LoggingMetricHook.
<add>
<add> Args:
<add> tensors: `dict` that maps string-valued tags to tensors/tensor names,
<add> or `iterable` of tensors/tensor names.
<add> log_dir: `string`, directory path that metric hook should write log to.
<add> metric_logger: instance of `BenchmarkLogger`, the benchmark logger that
<add> hook should use to write the log. Exactly one of the `log_dir` and
<add> `metric_logger` should be provided.
<add> every_n_iter: `int`, print the values of `tensors` once every N local
<add> steps taken on the current worker.
<add> every_n_secs: `int` or `float`, print the values of `tensors` once every N
<add> seconds. Exactly one of `every_n_iter` and `every_n_secs` should be
<add> provided.
<add> at_end: `bool` specifying whether to print the values of `tensors` at the
<add> end of the run.
<add>
<add> Raises:
<add> ValueError:
<add> 1. `every_n_iter` is non-positive, or
<add> 2. Exactly one of every_n_iter and every_n_secs should be provided.
<add> 3. Exactly one of log_dir and metric_logger should be provided.
<add> """
<add> super(LoggingMetricHook, self).__init__(
<add> tensors=tensors,
<add> every_n_iter=every_n_iter,
<add> every_n_secs=every_n_secs,
<add> at_end=at_end)
<add>
<add> if (log_dir is None) == (metric_logger is None):
<add> raise ValueError(
<add> "exactly one of log_dir and metric_logger should be provided.")
<add>
<add> if log_dir is not None:
<add> self._logger = logger.BenchmarkLogger(log_dir)
<add> else:
<add> self._logger = metric_logger
<add>
<add> def begin(self):
<add> super(LoggingMetricHook, self).begin()
<add> self._global_step_tensor = tf.train.get_global_step()
<add> if self._global_step_tensor is None:
<add> raise RuntimeError(
<add> "Global step should be created to use LoggingMetricHook.")
<add> if self._global_step_tensor.name not in self._current_tensors:
<add> self._current_tensors[self._global_step_tensor.name] = (
<add> self._global_step_tensor)
<add>
<add> def after_run(self, unused_run_context, run_values):
<add> # should_trigger is a internal state that populated at before_run, and it is
<add> # using self_timer to determine whether it should trigger.
<add> if self._should_trigger:
<add> self._log_metric(run_values.results)
<add>
<add> self._iter_count += 1
<add>
<add> def end(self, session):
<add> if self._log_at_end:
<add> values = session.run(self._current_tensors)
<add> self._log_metric(values)
<add>
<add> def _log_metric(self, tensor_values):
<add> self._timer.update_last_triggered_step(self._iter_count)
<add> global_step = tensor_values[self._global_step_tensor.name]
<add> # self._tag_order is populated during the init of LoggingTensorHook
<add> for tag in self._tag_order:
<add> self._logger.log_metric(tag, tensor_values[tag], global_step=global_step)
<ide><path>official/utils/logging/metric_hook_test.py
<add># Copyright 2018 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Tests for metric_hook."""
<add>
<add>from __future__ import absolute_import
<add>from __future__ import division
<add>from __future__ import print_function
<add>
<add>import tempfile
<add>import time
<add>
<add>import tensorflow as tf
<add>from tensorflow.python.training import monitored_session
<add>
<add>from official.utils.logging import metric_hook
<add>
<add>
<add>class LoggingMetricHookTest(tf.test.TestCase):
<add>
<add> def setUp(self):
<add> super(LoggingMetricHookTest, self).setUp()
<add>
<add> class MockMetricLogger(object):
<add> def __init__(self):
<add> self.logged_metric = []
<add>
<add> def log_metric(self, name, value, unit=None, global_step=None,
<add> extras=None):
<add> self.logged_metric.append({
<add> "name": name,
<add> "value": float(value),
<add> "unit": unit,
<add> "global_step": global_step,
<add> "extras": extras})
<add>
<add> self._log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
<add> self._logger = MockMetricLogger()
<add>
<add> def tearDown(self):
<add> super(LoggingMetricHookTest, self).tearDown()
<add> tf.gfile.DeleteRecursively(self.get_temp_dir())
<add>
<add> def test_illegal_args(self):
<add> with self.assertRaisesRegexp(ValueError, 'nvalid every_n_iter'):
<add> metric_hook.LoggingMetricHook(tensors=['t'], every_n_iter=0)
<add> with self.assertRaisesRegexp(ValueError, 'nvalid every_n_iter'):
<add> metric_hook.LoggingMetricHook(tensors=['t'], every_n_iter=-10)
<add> with self.assertRaisesRegexp(ValueError, 'xactly one of'):
<add> metric_hook.LoggingMetricHook(
<add> tensors=['t'], every_n_iter=5, every_n_secs=5)
<add> with self.assertRaisesRegexp(ValueError, 'xactly one of'):
<add> metric_hook.LoggingMetricHook(tensors=['t'])
<add> with self.assertRaisesRegexp(ValueError, 'log_dir and metric_logger'):
<add> metric_hook.LoggingMetricHook(tensors=['t'], every_n_iter=5)
<add> with self.assertRaisesRegexp(ValueError, 'log_dir and metric_logger'):
<add> metric_hook.LoggingMetricHook(
<add> tensors=['t'], every_n_iter=5, log_dir=self._log_dir,
<add> metric_logger=self._logger)
<add>
<add> def test_print_at_end_only(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> t = tf.constant(42.0, name='foo')
<add> train_op = tf.constant(3)
<add> hook = metric_hook.LoggingMetricHook(
<add> tensors=[t.name], at_end=True, metric_logger=self._logger)
<add> hook.begin()
<add> mon_sess = monitored_session._HookedSession(sess, [hook])
<add> sess.run(tf.global_variables_initializer())
<add>
<add> for _ in range(3):
<add> mon_sess.run(train_op)
<add> self.assertEqual(self._logger.logged_metric, [])
<add>
<add> hook.end(sess)
<add> self.assertEqual(len(self._logger.logged_metric), 1)
<add> metric = self._logger.logged_metric[0]
<add> self.assertRegexpMatches(metric["name"], "foo")
<add> self.assertEqual(metric["value"], 42.0)
<add> self.assertEqual(metric["unit"], None)
<add> self.assertEqual(metric["global_step"], 0)
<add>
<add> def test_global_step_not_found(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> t = tf.constant(42.0, name='foo')
<add> hook = metric_hook.LoggingMetricHook(
<add> tensors=[t.name], at_end=True, metric_logger=self._logger)
<add>
<add> with self.assertRaisesRegexp(
<add> RuntimeError, 'should be created to use LoggingMetricHook.'):
<add> hook.begin()
<add>
<add> def test_log_tensors(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> t1 = tf.constant(42.0, name='foo')
<add> t2 = tf.constant(43.0, name='bar')
<add> train_op = tf.constant(3)
<add> hook = metric_hook.LoggingMetricHook(
<add> tensors=[t1, t2], at_end=True, metric_logger=self._logger)
<add> hook.begin()
<add> mon_sess = monitored_session._HookedSession(sess, [hook])
<add> sess.run(tf.global_variables_initializer())
<add>
<add> for _ in range(3):
<add> mon_sess.run(train_op)
<add> self.assertEqual(self._logger.logged_metric, [])
<add>
<add> hook.end(sess)
<add> self.assertEqual(len(self._logger.logged_metric), 2)
<add> metric1 = self._logger.logged_metric[0]
<add> self.assertRegexpMatches(str(metric1["name"]), "foo")
<add> self.assertEqual(metric1["value"], 42.0)
<add> self.assertEqual(metric1["unit"], None)
<add> self.assertEqual(metric1["global_step"], 0)
<add>
<add> metric2 = self._logger.logged_metric[1]
<add> self.assertRegexpMatches(str(metric2["name"]), "bar")
<add> self.assertEqual(metric2["value"], 43.0)
<add> self.assertEqual(metric2["unit"], None)
<add> self.assertEqual(metric2["global_step"], 0)
<add>
<add> def _validate_print_every_n_steps(self, sess, at_end):
<add> t = tf.constant(42.0, name='foo')
<add>
<add> train_op = tf.constant(3)
<add> hook = metric_hook.LoggingMetricHook(
<add> tensors=[t.name], every_n_iter=10, at_end=at_end,
<add> metric_logger=self._logger)
<add> hook.begin()
<add> mon_sess = monitored_session._HookedSession(sess, [hook])
<add> sess.run(tf.global_variables_initializer())
<add> mon_sess.run(train_op)
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add> for _ in range(3):
<add> self._logger.logged_metric = []
<add> for _ in range(9):
<add> mon_sess.run(train_op)
<add> # assertNotRegexpMatches is not supported by python 3.1 and later
<add> self.assertEqual(str(self._logger.logged_metric).find(t.name), -1)
<add> mon_sess.run(train_op)
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add>
<add> # Add additional run to verify proper reset when called multiple times.
<add> self._logger.logged_metric = []
<add> mon_sess.run(train_op)
<add> # assertNotRegexpMatches is not supported by python 3.1 and later
<add> self.assertEqual(str(self._logger.logged_metric).find(t.name), -1)
<add>
<add> self._logger.logged_metric = []
<add> hook.end(sess)
<add> if at_end:
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add> else:
<add> # assertNotRegexpMatches is not supported by python 3.1 and later
<add> self.assertEqual(str(self._logger.logged_metric).find(t.name), -1)
<add>
<add> def test_print_every_n_steps(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> self._validate_print_every_n_steps(sess, at_end=False)
<add> # Verify proper reset.
<add> self._validate_print_every_n_steps(sess, at_end=False)
<add>
<add> def test_print_every_n_steps_and_end(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> self._validate_print_every_n_steps(sess, at_end=True)
<add> # Verify proper reset.
<add> self._validate_print_every_n_steps(sess, at_end=True)
<add>
<add> def _validate_print_every_n_secs(self, sess, at_end):
<add> t = tf.constant(42.0, name='foo')
<add> train_op = tf.constant(3)
<add>
<add> hook = metric_hook.LoggingMetricHook(
<add> tensors=[t.name], every_n_secs=1.0, at_end=at_end,
<add> metric_logger=self._logger)
<add> hook.begin()
<add> mon_sess = monitored_session._HookedSession(sess, [hook])
<add> sess.run(tf.global_variables_initializer())
<add>
<add> mon_sess.run(train_op)
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add>
<add> # assertNotRegexpMatches is not supported by python 3.1 and later
<add> self._logger.logged_metric = []
<add> mon_sess.run(train_op)
<add> self.assertEqual(str(self._logger.logged_metric).find(t.name), -1)
<add> time.sleep(1.0)
<add>
<add> self._logger.logged_metric = []
<add> mon_sess.run(train_op)
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add>
<add> self._logger.logged_metric = []
<add> hook.end(sess)
<add> if at_end:
<add> self.assertRegexpMatches(str(self._logger.logged_metric), t.name)
<add> else:
<add> # assertNotRegexpMatches is not supported by python 3.1 and later
<add> self.assertEqual(str(self._logger.logged_metric).find(t.name), -1)
<add>
<add> def test_print_every_n_secs(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> self._validate_print_every_n_secs(sess, at_end=False)
<add> # Verify proper reset.
<add> self._validate_print_every_n_secs(sess, at_end=False)
<add>
<add> def test_print_every_n_secs_and_end(self):
<add> with tf.Graph().as_default(), tf.Session() as sess:
<add> tf.train.get_or_create_global_step()
<add> self._validate_print_every_n_secs(sess, at_end=True)
<add> # Verify proper reset.
<add> self._validate_print_every_n_secs(sess, at_end=True)
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main() | 2 |
Javascript | Javascript | fix path.js again | ff23c44179a82db4e95e3ca139479a43fda94497 | <ide><path>src/extras/core/Path.js
<ide> THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
<ide> var deltaAngle = aEndAngle - aStartAngle;
<ide> var angle;
<ide> var tdivisions = divisions * 2;
<del> var t;
<ide>
<ide> for ( j = 1; j <= tdivisions; j ++ ) {
<ide>
<ide> THREE.Path.prototype.toShapes = function() {
<ide>
<ide> if ( subPaths.length == 0 ) return [];
<ide>
<add> var tmpPath, tmpShape, shapes = [];
<add>
<ide> var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
<add> // console.log("Holes first", holesFirst);
<add>
<ide> if ( subPaths.length == 1) {
<ide> tmpPath = subPaths[0];
<ide> tmpShape = new THREE.Shape();
<ide> tmpShape.actions = tmpPath.actions;
<ide> tmpShape.curves = tmpPath.curves;
<del> return tmpShape;
<add> shapes.push( tmpShape );
<add> return shapes;
<ide> };
<ide>
<del> var tmpPath, tmpShape, shapes = [];
<del>
<del> // console.log("Holes first", holesFirst);
<del>
<del>
<del>
<ide> if ( holesFirst ) {
<ide>
<ide> tmpShape = new THREE.Shape(); | 1 |
Javascript | Javascript | update media.js and html5.js feature access | e60f2eef5ca0b481a65402bafb68c23f4ca954be | <ide><path>src/js/media/html5.js
<ide> vjs.Html5 = vjs.MediaTechController.extend({
<ide> this['fullscreenResizeFeature'] = true;
<ide>
<ide> // HTML video supports progress events
<del> this.features['progressEvents'] = true;
<add> this['progressEventsFeature'] = true;
<ide>
<ide> vjs.MediaTechController.call(this, player, options, ready);
<ide> this.setupTriggers();
<ide><path>src/js/media/media.js
<ide> vjs.MediaTechController = vjs.Component.extend({
<ide> vjs.Component.call(this, player, options, ready);
<ide>
<ide> // Manually track progress in cases where the browser/flash player doesn't report it.
<del> if (!this.features['progressEvents']) {
<add> if (!this['progressEventsFeature']) {
<ide> this.manualProgressOn();
<ide> }
<ide>
<ide> // Manually track timeudpates in cases where the browser/flash player doesn't report it.
<del> if (!this.features['timeupdateEvents']) {
<add> if (!this['timeupdateEventsFeature']) {
<ide> this.manualTimeUpdatesOn();
<ide> }
<ide>
<ide> vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){
<ide> // Watch for native timeupdate event
<ide> this.one('timeupdate', function(){
<ide> // Update known progress support for this playback technology
<del> this.features['timeupdateEvents'] = true;
<add> this['timeupdateEventsFeature'] = true;
<ide> // Turn off manual progress tracking
<ide> this.manualTimeUpdatesOff();
<ide> }); | 2 |
Python | Python | finish pr backporting | 2902149f776e20623ec49cec485455c057bd26ba | <ide><path>examples/antirectifier.py
<ide> def call(self, x, mask=None):
<ide> nb_classes = 10
<ide> nb_epoch = 40
<ide>
<del># the data, shuffled and split between tran and test sets
<add># the data, shuffled and split between train and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide>
<ide> X_train = X_train.reshape(60000, 784)
<ide><path>examples/mnist_cnn.py
<ide> # convolution kernel size
<ide> nb_conv = 3
<ide>
<del># the data, shuffled and split between tran and test sets
<add># the data, shuffled and split between train and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide>
<ide> X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
<ide><path>examples/mnist_mlp.py
<ide> nb_classes = 10
<ide> nb_epoch = 20
<ide>
<del># the data, shuffled and split between tran and test sets
<add># the data, shuffled and split between train and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide>
<ide> X_train = X_train.reshape(60000, 784)
<ide><path>examples/mnist_siamese_graph.py
<ide> def compute_accuracy(predictions, labels):
<ide> return labels[predictions.ravel() < 0.5].mean()
<ide>
<ide>
<del># the data, shuffled and split between tran and test sets
<add># the data, shuffled and split between train and test sets
<ide> (X_train, y_train), (X_test, y_test) = mnist.load_data()
<ide> X_train = X_train.reshape(60000, 784)
<ide> X_test = X_test.reshape(10000, 784)
<ide><path>keras/engine/training.py
<ide> from __future__ import print_function
<ide> from __future__ import absolute_import
<ide>
<add>import warnings
<ide> import copy
<ide> import time
<ide> import numpy as np
<ide> def generate_arrays_from_file(path):
<ide> samples_seen += batch_size
<ide>
<ide> # epoch finished
<add> if samples_seen > samples_per_epoch:
<add> warnings.warn('Epoch comprised more than '
<add> '`samples_per_epoch` samples, '
<add> 'which might affect learning results. '
<add> 'Set `samples_per_epoch` correctly '
<add> 'to avoid this warning.')
<ide> if samples_seen >= samples_per_epoch and do_validation:
<ide> if val_gen:
<ide> val_outs = self.evaluate_generator(validation_data,
<ide><path>keras/preprocessing/image.py
<ide>
<ide> from os import listdir
<ide> from os.path import isfile, join
<del>import random
<ide> import math
<ide> from six.moves import range
<ide> import threading
<ide>
<ide>
<ide> def random_rotation(x, rg, fill_mode='nearest', cval=0.):
<del> angle = random.uniform(-rg, rg)
<add> angle = np.random.uniform(-rg, rg)
<ide> x = ndimage.interpolation.rotate(x, angle,
<ide> axes=(1, 2),
<ide> reshape=False,
<ide> def random_shift(x, wrg, hrg, fill_mode='nearest', cval=0.):
<ide> shift_x = shift_y = 0
<ide>
<ide> if wrg:
<del> shift_x = random.uniform(-wrg, wrg) * x.shape[2]
<add> shift_x = np.random.uniform(-wrg, wrg) * x.shape[2]
<ide> if hrg:
<del> shift_y = random.uniform(-hrg, hrg) * x.shape[1]
<add> shift_y = np.random.uniform(-hrg, hrg) * x.shape[1]
<ide> x = ndimage.interpolation.shift(x, (0, shift_y, shift_x),
<ide> order=0,
<ide> mode=fill_mode,
<ide> def random_barrel_transform(x, intensity):
<ide>
<ide>
<ide> def random_shear(x, intensity, fill_mode='nearest', cval=0.):
<del> shear = random.uniform(-intensity, intensity)
<add> shear = np.random.uniform(-intensity, intensity)
<ide> shear_matrix = np.array([[1.0, -math.sin(shear), 0.0],
<ide> [0.0, math.cos(shear), 0.0],
<ide> [0.0, 0.0, 1.0]])
<ide> def random_channel_shift(x, rg):
<ide>
<ide>
<ide> def random_zoom(x, rg, fill_mode='nearest', cval=0.):
<del> zoom_w = random.uniform(1.-rg, 1.)
<del> zoom_h = random.uniform(1.-rg, 1.)
<add> zoom_w = np.random.uniform(1.-rg, 1.)
<add> zoom_h = np.random.uniform(1.-rg, 1.)
<ide> x = ndimage.interpolation.zoom(x, zoom=(1., zoom_w, zoom_h),
<ide> mode=fill_mode,
<ide> cval=cval)
<ide> def random_transform(self, x):
<ide> if self.width_shift_range or self.height_shift_range:
<ide> x = random_shift(x, self.width_shift_range, self.height_shift_range)
<ide> if self.horizontal_flip:
<del> if random.random() < 0.5:
<add> if np.random.random() < 0.5:
<ide> x = horizontal_flip(x)
<ide> if self.vertical_flip:
<del> if random.random() < 0.5:
<add> if np.random.random() < 0.5:
<ide> x = vertical_flip(x)
<ide> if self.shear_range:
<ide> x = random_shear(x, self.shear_range) | 6 |
Javascript | Javascript | update gitpod testing | 1ef12d5605b208cf5d8f00e52119bfcc1c0c5d4e | <ide><path>api-server/server/utils/getSetAccessToken.test.js
<ide> describe('getSetAccessToken', () => {
<ide> const invalidJWTSecret = 'This is not correct secret';
<ide> const now = new Date(Date.now());
<ide> const theBeginningOfTime = new Date(0);
<add> const domain = process.env.COOKIE_DOMAIN || 'localhost';
<ide> const accessToken = {
<ide> id: '123abc',
<ide> userId: '456def',
<ide> describe('getSetAccessToken', () => {
<ide> expectedJWT,
<ide> {
<ide> signed: false,
<del> domain: 'localhost',
<add> domain,
<ide> maxAge: accessToken.ttl
<ide> }
<ide> ]);
<ide> describe('getSetAccessToken', () => {
<ide> // expect.assertions(4);
<ide> const req = mockReq();
<ide> const res = mockRes();
<add> const jwtOptions = { signed: false, domain };
<ide>
<ide> removeCookies(req, res);
<ide>
<ide> expect(res.clearCookie.getCall(0).args).toEqual([
<ide> 'jwt_access_token',
<del> {
<del> signed: false,
<del> domain: 'localhost'
<del> }
<add> jwtOptions
<ide> ]);
<ide> expect(res.clearCookie.getCall(1).args).toEqual([
<ide> 'access_token',
<del> {
<del> signed: false,
<del> domain: 'localhost'
<del> }
<del> ]);
<del> expect(res.clearCookie.getCall(2).args).toEqual([
<del> 'userId',
<del> {
<del> signed: false,
<del> domain: 'localhost'
<del> }
<del> ]);
<del> expect(res.clearCookie.getCall(3).args).toEqual([
<del> '_csrf',
<del> {
<del> signed: false,
<del> domain: 'localhost'
<del> }
<add> jwtOptions
<ide> ]);
<add> expect(res.clearCookie.getCall(2).args).toEqual(['userId', jwtOptions]);
<add> expect(res.clearCookie.getCall(3).args).toEqual(['_csrf', jwtOptions]);
<ide> });
<ide> });
<ide> }); | 1 |
PHP | PHP | remove reference to method that doesn't exist | 5ea40038b9f5117e729e59748a100c18ff72f2be | <ide><path>src/Routing/Router.php
<ide> * ### Connecting routes
<ide> *
<ide> * Connecting routes is done using Router::connect(). When parsing incoming requests or reverse matching
<del> * parameters, routes are enumerated in the order they were connected. You can modify the order of connected
<del> * routes using Router::promote(). For more information on routes and how to connect them see Router::connect().
<del> *
<add> * parameters, routes are enumerated in the order they were connected. For more information on routes and
<add> * how to connect them see Router::connect().
<ide> */
<ide> class Router
<ide> { | 1 |
Text | Text | add 4 new mongoose queries to mongoose cheatsheet | 045f6d46df340c198696900b467dd57b00537ebc | <ide><path>README.md
<ide> I also tried to make it as **generic** and **reusable** as possible to cover mos
<ide> without being too specific. In the worst case you can use this as a guide for your projects, if for example you are only
<ide> interested in **Sign in with Google** authentication and nothing else.
<ide>
<del>Chances are, you might not need all 4 types of OAuth 1.0a/OAuth2 authentication methods, or all 9 API examples.
<del>Sadly, there is no step-by-step wizard to configure the boilerplate code just for your use case. So, use what you need, simply delete what you don't need.
<add>Chances are, you might not need all 4 types of OAuth 1.0a/OAuth2 authentication methods, or all 12+ API examples. So, use what you need and delete what you don't need. As of recently, it is possible to selectively *enable/disable* authentication methods in `config/secrets.js`.
<ide>
<ide> <h4 align="center">Flatly Bootstrap Theme</h3>
<ide>
<ide> Table of Contents
<ide> - [Pro Tips](#pro-tips)
<ide> - [FAQ](#faq)
<ide> - [How It Works](#how-it-works-mini-guides)
<add>- [Mongoose Cheatsheet](#mongoose-cheatsheet)
<ide> - [Deployment](#deployment)
<ide> - [TODO](#todo)
<ide> - [Contributing](#contributing)
<ide> If you want to see a really cool real-time dashboard check out this [live exampl
<ide>
<ide> Mongoose Cheatsheet
<ide> -------------------
<del>TODO
<add>#### Find all users:
<add>```js
<add>User.find(function(err, users) {
<add> console.log(users);
<add>});
<add>```
<add>
<add>#### Find a user by email:
<add>```js
<add>var userEmail = 'example@gmail.com';
<add>User.findOne({ email: userEmail }, function(err, user) {
<add> console.log(user);
<add>});
<add>```
<add>
<add>#### Find 5 most recent user accounts:
<add>```js
<add>User
<add> .find()
<add> .sort({ _id: -1 })
<add> .limit(5)
<add> .exec(function(err, users) {
<add> console.log(users);
<add> });
<add>```
<add>
<add>#### Get total count of a field from all documents:
<add>Let's suppose that each user has a `votes` field and you would like to count the total number of votes in your database accross all users. One very inefficient way would be to loop through each document and manually accumulate the count. Or you could use [MongoDB Aggregation Framework](http://docs.mongodb.org/manual/core/aggregation-introduction/) instead:
<add>```js
<add>User.aggregate({ $group: { _id: null, total: { $sum: '$votes' } } }, function(err, votesCount) {
<add> console.log(votesCount.total);
<add>});
<add>```
<ide>
<ide> Deployment
<ide> ---------- | 1 |
Ruby | Ruby | fix associations when using per class databases | 9f8b4d1510f66597bbe8732e507173217df9f14d | <ide><path>activerecord/lib/active_record/associations/alias_tracker.rb
<ide> module Associations
<ide> # Keeps track of table aliases for ActiveRecord::Associations::ClassMethods::JoinDependency and
<ide> # ActiveRecord::Associations::ThroughAssociationScope
<ide> class AliasTracker # :nodoc:
<del> attr_reader :aliases, :table_joins
<add> attr_reader :aliases, :table_joins, :connection
<ide>
<ide> # table_joins is an array of arel joins which might conflict with the aliases we assign here
<del> def initialize(table_joins = [])
<add> def initialize(connection = ActiveRecord::Model.connection, table_joins = [])
<ide> @aliases = Hash.new { |h,k| h[k] = initial_count_for(k) }
<ide> @table_joins = table_joins
<add> @connection = connection
<ide> end
<ide>
<ide> def aliased_table_for(table_name, aliased_name = nil)
<ide> def initial_count_for(name)
<ide> def truncate(name)
<ide> name.slice(0, connection.table_alias_length - 2)
<ide> end
<del>
<del> def connection
<del> ActiveRecord::Base.connection
<del> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/association_scope.rb
<ide> class AssociationScope #:nodoc:
<ide>
<ide> def initialize(association)
<ide> @association = association
<del> @alias_tracker = AliasTracker.new
<add> @alias_tracker = AliasTracker.new klass.connection
<ide> end
<ide>
<ide> def scope
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def initialize(base, associations, joins)
<ide> @join_parts = [JoinBase.new(base)]
<ide> @associations = {}
<ide> @reflections = []
<del> @alias_tracker = AliasTracker.new(joins)
<add> @alias_tracker = AliasTracker.new(base.connection, joins)
<ide> @alias_tracker.aliased_name_for(base.table_name) # Updates the count for base.table_name to 1
<ide> build(associations)
<ide> end | 3 |
PHP | PHP | print new line at end of `about` command output | 51b5edaa2f8dfb0acb520ecb394706ade2200a35 | <ide><path>src/Illuminate/Foundation/Console/AboutCommand.php
<ide> public function handle()
<ide> })
<ide> ->pipe(fn ($data) => $this->display($data));
<ide>
<add> $this->newLine();
<add>
<ide> return 0;
<ide> }
<ide> | 1 |
PHP | PHP | correct doc blocks | 97d8902fb92bdee7376e987ca82366747c1ce04c | <ide><path>src/Database/Connection.php
<ide> public function schemaCollection(SchemaCollection $collection = null)
<ide> /**
<ide> * Executes an INSERT query on the specified table.
<ide> *
<del> * @param string $table the table to update values in
<add> * @param string $table the table to insert values in
<ide> * @param array $data values to be inserted
<ide> * @param array $types list of associative array containing the types to be used for casting
<ide> * @return \Cake\Database\StatementInterface
<ide> public function insert($table, array $data, array $types = [])
<ide> /**
<ide> * Executes an UPDATE statement on the specified table.
<ide> *
<del> * @param string $table the table to delete rows from
<add> * @param string $table the table to update rows from
<ide> * @param array $data values to be updated
<ide> * @param array $conditions conditions to be set for update statement
<ide> * @param array $types list of associative array containing the types to be used for casting | 1 |
Ruby | Ruby | remove unnecessary use of kernel#silence_warnings | 712baccef56974f754d77775d04924bfa52ca76e | <ide><path>activesupport/lib/active_support/deprecation.rb
<ide> def deprecation_horizon
<ide> end
<ide>
<ide> class DeprecationProxy #:nodoc:
<del> silence_warnings do
<del> instance_methods.each { |m| undef_method m unless m =~ /^__/ }
<del> end
<add> instance_methods.each { |m| undef_method m unless m =~ /^__/ }
<ide>
<ide> # Don't give a deprecation warning on inspect since test/unit and error
<ide> # logs rely on it for diagnostics. | 1 |
Text | Text | add align properties and code samples | c835c4485a3e10d97caf140c0780449a360bda2c | <ide><path>guide/english/css/layout-horizontal-and-vertical-align/index.md
<ide> title: Layout Horizontal and Vertical Align
<ide> ---
<ide> ## Layout Horizontal and Vertical Align
<add>CSS has properties that create space both around and inside an element. You will use one, or a combination of these properties to create layouts.
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/css/layout-horizontal-and-vertical-align/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>### Properties Used To Create Layouts
<add>You will use the following properties to align elements and create layouts:
<add>- [margin](https://guide.freecodecamp.org/css/margins/)
<add>- [position](https://guide.freecodecamp.org/css/css-position)
<add>- [float and clear](https://guide.freecodecamp.org/css/layout/float-and-clear)
<add>- [text-align](https://guide.freecodecamp.org/css/text-align)
<add>- [padding](https://guide.freecodecamp.org/css/padding)
<add>- [line-height](https://guide.freecodecamp.org/css/text)
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>### Horizontal Align
<add>The `margin` property will create space around an element. Use the `auto` value to equally distribute remaining space on either side.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>```css
<add>.horizontal-center {
<add> margin: auto;
<add>}
<add>```
<ide>
<del>#### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>`Block` elements must have a `width` set to avoid filling the viewport:
<ide>
<add>```html
<add><div class="square horizontal-center"><div>
<add>```
<ide>
<add>```css
<add>.square {
<add> width: 250px;
<add> height: 250px;
<add> background-color: tomato;
<add>}
<add>.horizontal-center {
<add> margin: auto;
<add>}
<add>```
<add>`Inline-block` elements, such as an `<img>`, can be aligned by setting the `display` property to `block`.
<add>
<add>```html
<add><img src="image.jpg" alt="image">
<add>```
<add>
<add>```css
<add>img {
<add> display: block;
<add> width: 250px;
<add> margin: auto;
<add>}
<add>```
<add>
<add>Use the `position` property and set left and right location of the element.
<add>
<add>```html
<add><div class="left-square"><div>
<add><div class="right-square"><div>
<add>```
<add>```css
<add>.left-square {
<add> position: absolute;
<add> left: 100px;
<add> width: 250px;
<add> height: 250px;
<add> background-color: tomato;
<add>}
<add>.right-square {
<add> position: absolute;
<add> right: 100px;
<add> width: 250px;
<add> height: 250px;
<add> background-color: tomato;
<add>}
<add>```
<add>Send an element to the right, or left of the page using the `float` property.
<add>
<add>```css
<add>img {
<add> float: right;
<add>}
<add>```
<add>
<add>```css
<add>img {
<add> float: left;
<add>}
<add>```
<add>
<add>Remember floated items are removed from the normal flow. You will need to [clear](https://guide.freecodecamp.org/css/layout/float-and-clear/) your items to get the proper layout.
<add>
<add>Text can be aligned by setting the parent element's `text-align` property.
<add>
<add>```css
<add>div {
<add> text-align: center;
<add>}
<add>```
<add>
<add>### Vertical Align
<add>Using `margin` there isn't an `auto` property to vertically align elements. You will set the distance unit for `margin-top` and/or `margin-bottom` properties.
<add>
<add>```css
<add>img {
<add> margin-top: 100px;
<add> width: 250px;
<add> height: 250px;
<add>}
<add>```
<add>
<add>The same applies when using the `position` property.
<add>```css
<add>img {
<add> position: absolute;
<add> top: 100px;
<add> width: 250px;
<add> height: 250px;
<add>}
<add>```
<add>
<add>Aligning child elements can be done by setting the parent element's `padding`.
<add>
<add>```html
<add><div>
<add> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<add></div>
<add>```
<add>
<add>```css
<add>div {
<add> padding: 100px 0;
<add>}
<add>```
<add>
<add>For text, set the `line-height` to the parent element's height for a center alignment.
<add>
<add>```html
<add><div>
<add> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<add></div>
<add>```
<add>
<add>```css
<add>div {
<add> height: 250px;
<add> line-height: 250px;
<add>}
<add>```
<add>
<add>#### Encouraged Reading:
<add>- MDN Web docs: [CSS Layouts](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout)
<add>- w3schools: [CSS Layout - Horizontal & Vertical Align](https://www.w3schools.com/css/css_align.asp) | 1 |
PHP | PHP | remove @package from classes | bde6b0afe5de18b1c0461229dcde2f610c8b0e84 | <ide><path>src/Database/Driver/Mysql.php
<ide>
<ide> /**
<ide> * Class Mysql
<del> * @package Cake\Database\Driver
<ide> */
<ide> class Mysql extends Driver
<ide> {
<ide><path>src/Database/Driver/Postgres.php
<ide>
<ide> /**
<ide> * Class Postgres
<del> * @package Cake\Database\Driver
<ide> */
<ide> class Postgres extends Driver
<ide> {
<ide><path>src/Database/Driver/Sqlite.php
<ide>
<ide> /**
<ide> * Class Sqlite
<del> * @package Cake\Database\Driver
<ide> */
<ide> class Sqlite extends Driver
<ide> {
<ide><path>src/Database/Exception/MissingConnectionException.php
<ide>
<ide> /**
<ide> * Class MissingConnectionException
<del> * @package Cake\Database\Exception
<ide> */
<ide> class MissingConnectionException extends Exception
<ide> {
<ide><path>src/Database/Exception/MissingDriverException.php
<ide>
<ide> /**
<ide> * Class MissingDriverException
<del> * @package Cake\Database\Exception
<ide> */
<ide> class MissingDriverException extends Exception
<ide> {
<ide><path>src/Database/Exception/MissingExtensionException.php
<ide>
<ide> /**
<ide> * Class MissingExtensionException
<del> * @package Cake\Database\Exception
<ide> */
<ide> class MissingExtensionException extends Exception
<ide> {
<ide><path>src/Database/Exception/NestedTransactionRollbackException.php
<ide>
<ide> /**
<ide> * Class NestedTransactionRollbackException
<del> * @package Cake\Database\Exception
<ide> */
<ide> class NestedTransactionRollbackException extends Exception
<ide> {
<ide><path>src/Database/Type/DateType.php
<ide>
<ide> /**
<ide> * Class DateType
<del> * @package Cake\Database\Type
<ide> */
<ide> class DateType extends DateTimeType
<ide> {
<ide><path>src/Database/TypeMapTrait.php
<ide> */
<ide> /**
<ide> * Trait TypeMapTrait
<del> * @package Cake\Database
<ide> */
<ide> trait TypeMapTrait
<ide> {
<ide><path>src/Datasource/FactoryLocator.php
<ide>
<ide> /**
<ide> * Class FactoryLocator
<del> * @package Cake\Datasource
<ide> */
<ide> class FactoryLocator
<ide> {
<ide><path>src/Error/ExceptionRendererInterface.php
<ide>
<ide> /**
<ide> * Interface ExceptionRendererInterface
<del> * @package Cake\Error
<ide> */
<ide> interface ExceptionRendererInterface
<ide> {
<ide><path>src/Event/Event.php
<ide>
<ide> /**
<ide> * Class Event
<del> * @package Cake\Event
<ide> */
<ide> class Event implements EventInterface
<ide> {
<ide><path>src/Event/EventManagerInterface.php
<ide>
<ide> /**
<ide> * Interface EventManagerInterface
<del> * @package Cake\Event
<ide> */
<ide> interface EventManagerInterface
<ide> {
<ide><path>src/ORM/Behavior/TimestampBehavior.php
<ide>
<ide> /**
<ide> * Class TimestampBehavior
<del> * @package Cake\ORM\Behavior
<ide> */
<ide> class TimestampBehavior extends Behavior
<ide> { | 14 |
Javascript | Javascript | increase coverage for worker_threads | c7bf02a99fe62a2e1bb91e4f23537fafadc91455 | <ide><path>test/parallel/test-worker-onmessage-not-a-function.js
<add>// When MessagePort.onmessage is set to a value that is not a function, the
<add>// setter should call .unref() and .stop(), clearing a previous onmessage
<add>// listener from holding the event loop open. This test confirms that
<add>// functionality.
<add>
<add>// Flags: --experimental-worker
<add>'use strict';
<add>const common = require('../common');
<add>const { Worker, parentPort } = require('worker_threads');
<add>
<add>// Do not use isMainThread so that this test itself can be run inside a Worker.
<add>if (!process.env.HAS_STARTED_WORKER) {
<add> process.env.HAS_STARTED_WORKER = 1;
<add> const w = new Worker(__filename);
<add> w.postMessage(2);
<add>} else {
<add> // .onmessage uses a setter. Set .onmessage to a function that ultimately
<add> // should not be called. This will call .ref() and .start() which will keep
<add> // the event loop open (and prevent this from exiting) if the subsequent
<add> // assignment of a value to .onmessage doesn't call .unref() and .stop().
<add> parentPort.onmessage = common.mustNotCall();
<add> // Setting `onmessage` to a value that is not a function should clear the
<add> // previous value and also should allow the event loop to exit. (In other
<add> // words, this test should exit rather than run indefinitely.)
<add> parentPort.onmessage = 'fhqwhgads';
<add>} | 1 |
Go | Go | refuse swarm spec not named "default" | 9dba9e3248f8476d15242ce3ec0bf6d6d50c1a76 | <ide><path>daemon/cluster/cluster.go
<ide> func validateAndSanitizeInitRequest(req *types.InitRequest) error {
<ide> return fmt.Errorf("invalid ListenAddr %q: %v", req.ListenAddr, err)
<ide> }
<ide>
<add> if req.Spec.Annotations.Name == "" {
<add> req.Spec.Annotations.Name = "default"
<add> } else if req.Spec.Annotations.Name != "default" {
<add> return errors.New(`swarm spec must be named "default"`)
<add> }
<add>
<ide> return nil
<ide> }
<ide> | 1 |
Javascript | Javascript | remove useless checks on chunkgroup | e763d87960bdcf4b43f433b8b6d3a11f23552c83 | <ide><path>lib/Chunk.js
<ide> class Chunk {
<ide> for (const group of this.groupsIterable) {
<ide> if (group.chunks[group.chunks.length - 1] === this) {
<ide> for (const childGroup of group.childrenIterable) {
<del> // TODO webpack 5 remove this check for options
<del> if (typeof childGroup.options === "object") {
<del> for (const key of Object.keys(childGroup.options)) {
<del> if (key.endsWith("Order")) {
<del> const name = key.substr(0, key.length - "Order".length);
<del> let list = lists.get(name);
<del> if (list === undefined) lists.set(name, (list = []));
<del> list.push({
<del> order: childGroup.options[key],
<del> group: childGroup
<del> });
<del> }
<add> for (const key of Object.keys(childGroup.options)) {
<add> if (key.endsWith("Order")) {
<add> const name = key.substr(0, key.length - "Order".length);
<add> let list = lists.get(name);
<add> if (list === undefined) lists.set(name, (list = []));
<add> list.push({
<add> order: childGroup.options[key],
<add> group: childGroup
<add> });
<ide> }
<ide> }
<ide> }
<ide> class Chunk {
<ide> list.sort((a, b) => {
<ide> const cmp = b.order - a.order;
<ide> if (cmp !== 0) return cmp;
<del> // TOOD webpack 5 remove this check of compareTo
<del> if (a.group.compareTo) {
<del> return a.group.compareTo(b.group);
<del> }
<del> return 0;
<add> return a.group.compareTo(b.group);
<ide> });
<ide> result[name] = Array.from(
<ide> list.reduce((set, item) => {
<ide><path>lib/ChunkGroup.js
<ide> class ChunkGroup {
<ide> getChildrenByOrders() {
<ide> const lists = new Map();
<ide> for (const childGroup of this._children) {
<del> // TODO webpack 5 remove this check for options
<del> if (typeof childGroup.options === "object") {
<del> for (const key of Object.keys(childGroup.options)) {
<del> if (key.endsWith("Order")) {
<del> const name = key.substr(0, key.length - "Order".length);
<del> let list = lists.get(name);
<del> if (list === undefined) {
<del> lists.set(name, (list = []));
<del> }
<del> list.push({
<del> order: childGroup.options[key],
<del> group: childGroup
<del> });
<add> for (const key of Object.keys(childGroup.options)) {
<add> if (key.endsWith("Order")) {
<add> const name = key.substr(0, key.length - "Order".length);
<add> let list = lists.get(name);
<add> if (list === undefined) {
<add> lists.set(name, (list = []));
<ide> }
<add> list.push({
<add> order: childGroup.options[key],
<add> group: childGroup
<add> });
<ide> }
<ide> }
<ide> }
<ide> class ChunkGroup {
<ide> list.sort((a, b) => {
<ide> const cmp = b.order - a.order;
<ide> if (cmp !== 0) return cmp;
<del> // TOOD webpack 5 remove this check of compareTo
<del> if (a.group.compareTo) {
<del> return a.group.compareTo(b.group);
<del> }
<del> return 0;
<add> return a.group.compareTo(b.group);
<ide> });
<ide> result[name] = list.map(i => i.group);
<ide> }
<ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> allCreatedChunkGroups.add(c);
<ide> }
<ide> } else {
<del> // TODO webpack 5 remove addOptions check
<del> if (c.addOptions) c.addOptions(b.groupOptions);
<add> c.addOptions(b.groupOptions);
<ide> c.addOrigin(module, b.loc, b.request);
<ide> }
<ide> | 3 |
Text | Text | fix nits in code examples of async_hooks.md | 5d9dc94509253845642e617f9d6d47ce0d09d7da | <ide><path>doc/api/async_hooks.md
<ide> while `triggerId` shows *why* a resource was created.
<ide> The following is a simple demonstration of `triggerId`:
<ide>
<ide> ```js
<del>const async_hooks = require('async_hooks');
<del>
<ide> async_hooks.createHook({
<ide> init(asyncId, type, triggerId) {
<ide> const cId = async_hooks.currentId();
<del> fs.writeSync(1, `${type}(${asyncId}): ` +
<del> `trigger: ${triggerId} scope: ${cId}\n`);
<add> fs.writeSync(
<add> 1, `${type}(${asyncId}): trigger: ${triggerId} scope: ${cId}\n`);
<ide> }
<ide> }).enable();
<ide>
<ide> callback to `listen()` will look like. The output formatting is slightly more
<ide> elaborate to make calling context easier to see.
<ide>
<ide> ```js
<del>const async_hooks = require('async_hooks');
<del>
<ide> let indent = 0;
<ide> async_hooks.createHook({
<ide> init(asyncId, type, triggerId) {
<ide> const cId = async_hooks.currentId();
<del> fs.writeSync(1, ' '.repeat(indent) + `${type}(${asyncId}): ` +
<del> `trigger: ${triggerId} scope: ${cId}\n`);
<add> const indentStr = ' '.repeat(indent);
<add> fs.writeSync(
<add> 1,
<add> `${indentStr}${type}(${asyncId}): trigger: ${triggerId} scope: ${cId}\n`);
<ide> },
<ide> before(asyncId) {
<del> fs.writeSync(1, ' '.repeat(indent) + `before: ${asyncId}`);
<add> const indentStr = ' '.repeat(indent);
<add> fs.writeSync(1, `${indentStr}before: ${asyncId}\n`);
<ide> indent += 2;
<ide> },
<ide> after(asyncId) {
<ide> indent -= 2;
<del> fs.writeSync(1, ' '.repeat(indent) + `after: ${asyncId}`);
<add> const indentStr = ' '.repeat(indent);
<add> fs.writeSync(1, `${indentStr}after: ${asyncId}\n`);
<ide> },
<ide> destroy(asyncId) {
<del> fs.writeSync(1, ' '.repeat(indent) + `destroy: ${asyncId}`);
<add> const indentStr = ' '.repeat(indent);
<add> fs.writeSync(1, `${indentStr}destroy: ${asyncId}\n`);
<ide> },
<ide> }).enable();
<ide>
<ide> before: 5
<ide> >>> 4
<ide> TickObject(9): trigger: 4 scope: 4
<ide> after: 4
<del> destroy: 4
<ide> after: 5
<ide> before: 9
<ide> after: 9
<add>destroy: 4
<ide> destroy: 9
<ide> destroy: 5
<ide> ```
<ide> For example:
<ide>
<ide> ```js
<ide> console.log(async_hooks.currentId()); // 1 - bootstrap
<del>fs.open(path, (err, fd) => {
<del> console.log(async_hooks.currentId()); // 2 - open()
<add>fs.open(path, 'r', (err, fd) => {
<add> console.log(async_hooks.currentId()); // 6 - open()
<ide> });
<ide> ```
<ide>
<ide> For example:
<ide>
<ide> ```js
<ide> const server = net.createServer((conn) => {
<del> // Though the resource that caused (or triggered) this callback to
<del> // be called was that of the new connection. Thus the return value
<del> // of triggerId() is the ID of "conn".
<add> // The resource that caused (or triggered) this callback to be called
<add> // was that of the new connection. Thus the return value of triggerId()
<add> // is the asyncId of "conn".
<ide> async_hooks.triggerId();
<ide>
<ide> }).listen(port, () => {
<ide> will occur and node will abort.
<ide> The following is an overview of the `AsyncResource` API.
<ide>
<ide> ```js
<add>const { AsyncResource } = require('async_hooks');
<add>
<ide> // AsyncResource() is meant to be extended. Instantiating a
<ide> // new AsyncResource() also triggers init. If triggerId is omitted then
<ide> // async_hook.currentId() is used. | 1 |
Python | Python | remove unused imports and unused variables | c0d95fd6c2cd8ffc0738819825c3065e3c89977c | <ide><path>examples/image_ocr.py
<ide> import pylab
<ide> from keras import backend as K
<ide> from keras.layers.convolutional import Convolution2D, MaxPooling2D
<del>from keras.layers import Input, Layer, Dense, Activation, Flatten
<del>from keras.layers import Reshape, Lambda, merge, Permute, TimeDistributed
<add>from keras.layers import Input, Dense, Activation
<add>from keras.layers import Reshape, Lambda, merge
<ide> from keras.models import Model
<ide> from keras.layers.recurrent import GRU
<ide> from keras.optimizers import SGD
<del>from keras.utils import np_utils
<ide> from keras.utils.data_utils import get_file
<ide> from keras.preprocessing import image
<ide> import keras.callbacks
<ide> def on_epoch_end(self, epoch, logs={}):
<ide> def train(run_name, start_epoch, stop_epoch, img_w):
<ide> # Input Parameters
<ide> img_h = 64
<del> minibatch_size = 32
<ide> words_per_epoch = 16000
<ide> val_split = 0.2
<ide> val_words = int(words_per_epoch * (val_split))
<ide><path>examples/imdb_bidirectional_lstm.py
<ide>
<ide> from keras.preprocessing import sequence
<ide> from keras.models import Sequential
<del>from keras.layers import Dense, Dropout, Embedding, LSTM, Input, Bidirectional
<add>from keras.layers import Dense, Dropout, Embedding, LSTM, Bidirectional
<ide> from keras.datasets import imdb
<ide>
<ide>
<ide><path>examples/imdb_cnn.py
<ide> from keras.layers import Embedding
<ide> from keras.layers import Convolution1D, GlobalMaxPooling1D
<ide> from keras.datasets import imdb
<del>from keras import backend as K
<ide>
<ide>
<ide> # set parameters:
<ide><path>examples/imdb_lstm.py
<ide> np.random.seed(1337) # for reproducibility
<ide>
<ide> from keras.preprocessing import sequence
<del>from keras.utils import np_utils
<ide> from keras.models import Sequential
<del>from keras.layers import Dense, Dropout, Activation, Embedding
<del>from keras.layers import LSTM, SimpleRNN, GRU
<add>from keras.layers import Dense, Activation, Embedding
<add>from keras.layers import LSTM
<ide> from keras.datasets import imdb
<ide>
<ide> max_features = 20000
<ide><path>examples/lstm_text_generation.py
<ide>
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<del>from keras.layers import Dense, Activation, Dropout
<add>from keras.layers import Dense, Activation
<ide> from keras.layers import LSTM
<ide> from keras.optimizers import RMSprop
<ide> from keras.utils.data_utils import get_file
<ide><path>examples/mnist_hierarchical_rnn.py
<ide> from __future__ import print_function
<ide>
<ide> from keras.datasets import mnist
<del>from keras.models import Sequential, Model
<add>from keras.models import Model
<ide> from keras.layers import Input, Dense, TimeDistributed
<ide> from keras.layers import LSTM
<ide> from keras.utils import np_utils
<ide><path>examples/mnist_mlp.py
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential
<ide> from keras.layers.core import Dense, Dropout, Activation
<del>from keras.optimizers import SGD, Adam, RMSprop
<add>from keras.optimizers import RMSprop
<ide> from keras.utils import np_utils
<ide>
<ide>
<ide><path>examples/mnist_siamese_graph.py
<ide> from keras.datasets import mnist
<ide> from keras.models import Sequential, Model
<ide> from keras.layers import Dense, Dropout, Input, Lambda
<del>from keras.optimizers import SGD, RMSprop
<add>from keras.optimizers import RMSprop
<ide> from keras import backend as K
<ide>
<ide>
<ide><path>examples/neural_doodle.py
<ide> from scipy.misc import imread, imsave
<ide>
<ide> from keras import backend as K
<del>from keras.layers import Input, Convolution2D, MaxPooling2D, AveragePooling2D
<add>from keras.layers import Input, AveragePooling2D
<ide> from keras.models import Model
<ide> from keras.preprocessing.image import load_img, img_to_array
<ide> from keras.applications import vgg19 | 9 |
Python | Python | amqrpc result backend apparently working | 7f933deee0115e03fbd32a65653dfb1184820cc8 | <ide><path>celery/backends/amqp.py
<ide> import threading
<ide> import time
<ide>
<add>from collections import deque
<add>
<ide> from kombu.entity import Exchange, Queue
<ide> from kombu.messaging import Consumer, Producer
<ide>
<ide> def _store_result(self, task_id, result, status, traceback=None):
<ide> """Send task return value and status."""
<ide> with self.mutex:
<ide> with self.app.amqp.producer_pool.acquire(block=True) as pub:
<del> print("PUBLISH TO exchange=%r rkey=%r" % (self.exchange,
<del> self._routing_key(task_id)))
<ide> pub.publish({'task_id': task_id, 'status': status,
<ide> 'result': self.encode_result(result, status),
<ide> 'traceback': traceback,
<ide> def get_task_meta(self, task_id, backlog_limit=1000):
<ide> return {'status': states.PENDING, 'result': None}
<ide> poll = get_task_meta # XXX compat
<ide>
<del> def drain_events(self, connection, consumer, timeout=None, now=time.time):
<del> wait = connection.drain_events
<add> def drain_events(self, connection, consumer, timeout=None, now=time.time,
<add> wait=None):
<add> wait = wait or connection.drain_events
<ide> results = {}
<ide>
<ide> def callback(meta, message):
<ide> if meta['status'] in states.READY_STATES:
<del> uuid = repair_uuid(message.delivery_info['routing_key'])
<del> results[uuid] = meta
<add> results[meta['task_id']] = meta
<ide>
<ide> consumer.callbacks[:] = [callback]
<ide> time_start = now()
<ide> def callback(meta, message):
<ide> return results
<ide>
<ide> def consume(self, task_id, timeout=None):
<add> wait = self.drain_events
<ide> with self.app.pool.acquire_channel(block=True) as (conn, channel):
<ide> binding = self._create_binding(task_id)
<ide> with self.Consumer(channel, binding, no_ack=True) as consumer:
<del> return self.drain_events(conn, consumer, timeout).values()[0]
<add> while 1:
<add> try:
<add> return wait(conn, consumer, timeout)[task_id]
<add> except KeyError:
<add> continue
<add>
<add> def _many_bindings(self, ids):
<add> return [self._create_binding(task_id) for task_id in ids]
<ide>
<del> def get_many(self, task_ids, timeout=None, **kwargs):
<add> def get_many(self, task_ids, timeout=None, now=time.time, **kwargs):
<ide> with self.app.pool.acquire_channel(block=True) as (conn, channel):
<ide> ids = set(task_ids)
<ide> cached_ids = set()
<ide> def get_many(self, task_ids, timeout=None, **kwargs):
<ide> if cached['status'] in states.READY_STATES:
<ide> yield task_id, cached
<ide> cached_ids.add(task_id)
<del> ids ^= cached_ids
<del>
<del> bindings = [self._create_binding(task_id) for task_id in task_ids]
<del> with self.Consumer(channel, bindings, no_ack=True) as consumer:
<add> ids.difference_update(cached_ids)
<add> results = deque()
<add>
<add> def callback(meta, message):
<add> if meta['status'] in states.READY_STATES:
<add> results.append(meta)
<add>
<add> bindings = self._many_bindings(task_id)
<add> with self.Consumer(channel, bindings, callbacks=[callback],
<add> no_ack=True):
<add> wait = conn.drain_events
<add> popleft = results.popleft
<ide> while ids:
<del> r = self.drain_events(conn, consumer, timeout)
<del> ids ^= set(r)
<del> for ready_id, ready_meta in r.iteritems():
<del> yield ready_id, ready_meta
<add> wait(timeout=timeout)
<add> while results:
<add> meta = popleft()
<add> task_id = meta['task_id']
<add> ids.discard(task_id)
<add> self._cache[task_id] = meta
<add> yield task_id, meta
<ide>
<ide> def reload_task_result(self, task_id):
<ide> raise NotImplementedError(
<ide><path>celery/backends/amqrpc.py
<add># -*- coding: utf-8 -*-
<add>"""
<add> celery.backends.amqrpc
<add> ~~~~~~~~~~~~~~~~~~~~~~
<add>
<add> RPC-style result backend, using reply-to and one queue per client.
<add>
<add>"""
<ide> from __future__ import absolute_import
<add>from __future__ import with_statement
<ide>
<add>import kombu
<ide> import os
<ide> import uuid
<ide>
<ide> from threading import local
<ide>
<add>from kombu.common import maybe_declare
<ide> from celery.backends import amqp
<ide>
<ide> try:
<ide> class AMQRPCBackend(amqp.AMQPBackend):
<ide> _tls = local()
<ide>
<add> class Consumer(kombu.Consumer):
<add> auto_declare = False
<add>
<ide> def _create_exchange(self, name, type='direct', persistent=False):
<ide> return self.Exchange('c.amqrpc', type=type, delivery_mode=1,
<ide> durable=False, auto_delete=False)
<ide>
<ide> def on_task_apply(self, task_id):
<ide> with self.app.pool.acquire_channel(block=True) as (conn, channel):
<del> self.binding(channel).declare()
<add> maybe_declare(self.binding(channel), retry=True)
<ide> return {'reply_to': self.oid}
<ide>
<ide> def _create_binding(self, task_id):
<del> print("BINDING: %r" % (self.binding, ))
<ide> return self.binding
<ide>
<add> def _many_bindings(self, ids):
<add> return [self.binding]
<add>
<ide> def _routing_key(self, task_id):
<ide> from celery import current_task
<ide> return current_task.request.reply_to
<ide>
<ide> @property
<ide> def binding(self):
<ide> return self.Queue(self.oid, self.exchange, self.oid,
<del> durable=False, auto_delete=True)
<add> durable=False, auto_delete=False)
<ide>
<ide> @property
<ide> def oid(self):
<ide><path>celery/backends/base.py
<ide> def get_many(self, task_ids, timeout=None, interval=0.5):
<ide> yield bytes_to_str(task_id), cached
<ide> cached_ids.add(task_id)
<ide>
<del> ids ^= cached_ids
<add> ids.difference_update(cached_ids)
<ide> iterations = 0
<ide> while ids:
<ide> keys = list(ids)
<ide> r = self._mget_to_results(self.mget([self.get_key_for_task(k)
<ide> for k in keys]), keys)
<ide> self._cache.update(r)
<del> ids ^= set(map(bytes_to_str, r))
<add> ids.difference_update(set(map(bytes_to_str, r)))
<ide> for key, value in r.iteritems():
<ide> yield bytes_to_str(key), value
<ide> if timeout and iterations * interval >= timeout: | 3 |
Go | Go | use apparmor_parser directly | 5f4bc4f916f433a4ba258980a6c2fbdbd76d64f3 | <ide><path>pkg/libcontainer/apparmor/apparmor.go
<ide> package apparmor
<ide> import "C"
<ide> import (
<ide> "io/ioutil"
<add> "os"
<ide> "unsafe"
<ide> )
<ide>
<ide> func IsEnabled() bool {
<del> buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
<del> return err == nil && len(buf) > 1 && buf[0] == 'Y'
<add> if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil {
<add> buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
<add> return err == nil && len(buf) > 1 && buf[0] == 'Y'
<add> }
<add> return false
<ide> }
<ide>
<ide> func ApplyProfile(pid int, name string) error {
<ide><path>pkg/libcontainer/apparmor/setup.go
<ide> const (
<ide> )
<ide>
<ide> const DefaultProfile = `
<del># AppArmor profile from lxc for containers.
<del>
<ide> #include <tunables/global>
<ide> profile docker-default flags=(attach_disconnected,mediate_deleted) {
<ide> #include <abstractions/base>
<ide> profile docker-default flags=(attach_disconnected,mediate_deleted) {
<ide> file,
<ide> umount,
<ide>
<del> # ignore DENIED message on / remount
<del> deny mount options=(ro, remount) -> /,
<del>
<del> # allow tmpfs mounts everywhere
<ide> mount fstype=tmpfs,
<del>
<del> # allow mqueue mounts everywhere
<ide> mount fstype=mqueue,
<del>
<del> # allow fuse mounts everywhere
<ide> mount fstype=fuse.*,
<del>
<del> # allow bind mount of /lib/init/fstab for lxcguest
<del> mount options=(rw, bind) /lib/init/fstab.lxc/ -> /lib/init/fstab/,
<del>
<del> # deny writes in /proc/sys/fs but allow binfmt_misc to be mounted
<ide> mount fstype=binfmt_misc -> /proc/sys/fs/binfmt_misc/,
<del> deny @{PROC}/sys/fs/** wklx,
<del>
<del> # allow efivars to be mounted, writing to it will be blocked though
<ide> mount fstype=efivarfs -> /sys/firmware/efi/efivars/,
<add> mount fstype=fusectl -> /sys/fs/fuse/connections/,
<add> mount fstype=securityfs -> /sys/kernel/security/,
<add> mount fstype=debugfs -> /sys/kernel/debug/,
<add> mount fstype=proc -> /proc/,
<add> mount fstype=sysfs -> /sys/,
<ide>
<del> # block some other dangerous paths
<add> deny @{PROC}/sys/fs/** wklx,
<ide> deny @{PROC}/sysrq-trigger rwklx,
<ide> deny @{PROC}/mem rwklx,
<ide> deny @{PROC}/kmem rwklx,
<ide> deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx,
<ide> deny @{PROC}/sys/kernel/*/** wklx,
<ide>
<del> # deny writes in /sys except for /sys/fs/cgroup, also allow
<del> # fusectl, securityfs and debugfs to be mounted there (read-only)
<del> mount fstype=fusectl -> /sys/fs/fuse/connections/,
<del> mount fstype=securityfs -> /sys/kernel/security/,
<del> mount fstype=debugfs -> /sys/kernel/debug/,
<add> deny mount options=(ro, remount) -> /,
<ide> deny mount fstype=debugfs -> /var/lib/ureadahead/debugfs/,
<del> mount fstype=proc -> /proc/,
<del> mount fstype=sysfs -> /sys/,
<add> deny mount fstype=devpts,
<add>
<ide> deny /sys/[^f]*/** wklx,
<ide> deny /sys/f[^s]*/** wklx,
<ide> deny /sys/fs/[^c]*/** wklx,
<ide> deny /sys/fs/c[^g]*/** wklx,
<ide> deny /sys/fs/cg[^r]*/** wklx,
<ide> deny /sys/firmware/efi/efivars/** rwklx,
<ide> deny /sys/kernel/security/** rwklx,
<del> mount options=(move) /sys/fs/cgroup/cgmanager/ -> /sys/fs/cgroup/cgmanager.lower/,
<del>
<del> # the container may never be allowed to mount devpts. If it does, it
<del> # will remount the host's devpts. We could allow it to do it with
<del> # the newinstance option (but, right now, we don't).
<del> deny mount fstype=devpts,
<ide> }
<ide> `
<ide>
<ide> func InstallDefaultProfile(backupPath string) error {
<ide> return err
<ide> }
<ide> defer f.Close()
<add>
<ide> src, err := os.Open(DefaultProfilePath)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> defer src.Close()
<add>
<ide> if _, err := io.Copy(f, src); err != nil {
<ide> return err
<ide> }
<ide> func InstallDefaultProfile(backupPath string) error {
<ide> return err
<ide> }
<ide>
<del> output, err := exec.Command("/lib/init/apparmor-profile-load", "docker").CombinedOutput()
<add> // the current functionality of the load script is the exit 0 if the parser does not exist.
<add> // we think we should fail loudly if you have apparmor enabled but not the parser to load
<add> // the profile for use.
<add> output, err := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker").CombinedOutput()
<ide> if err != nil {
<ide> return fmt.Errorf("Error loading docker profile: %s (%s)", err, output)
<ide> } | 2 |
Ruby | Ruby | remove unneeded interning | 0b465032540ef92353e67eabd05eaf5867bfcc31 | <ide><path>actionpack/lib/action_controller/request.rb
<ide> def template_format
<ide> parameter_format = parameters[:format]
<ide>
<ide> if parameter_format
<del> parameter_format.to_sym
<add> parameter_format
<ide> elsif xhr?
<ide> :js
<ide> else
<ide> def template_format
<ide> end
<ide>
<ide> def cache_format
<del> parameter_format = parameters[:format]
<del> parameter_format && parameter_format.to_sym
<add> parameters[:format]
<ide> end
<ide>
<ide> # Returns true if the request's "X-Requested-With" header contains | 1 |
PHP | PHP | add support for broadcastas | 5c77de1cc2ea9ecfbcf77c53643aabc3e1ca6da3 | <ide><path>src/Illuminate/Broadcasting/BroadcastEvent.php
<ide> public function fire(Job $job, array $data)
<ide> {
<ide> $event = unserialize($data['event']);
<ide>
<add> $name = method_exists($event, 'broadcastAs')
<add> ? $event->broadcastAs() : get_class($event);
<add>
<ide> $this->broadcaster->broadcast(
<del> $event->broadcastOn(), get_class($event), $this->getPayloadFromEvent($event)
<add> $event->broadcastOn(), $name, $this->getPayloadFromEvent($event)
<ide> );
<ide>
<ide> $job->delete(); | 1 |
Ruby | Ruby | adjust expectations for 'opt' directory | 8abfee7d9c2c2e479c89d35524843ab2d840e799 | <ide><path>Library/Homebrew/test/test_formula_install.rb
<ide> def test_a_basic_install
<ide> # Test that things make it into the Cellar
<ide> keg=Keg.new f.prefix
<ide> keg.link
<del> assert_equal 2, HOMEBREW_PREFIX.children.length
<add> assert_equal 3, HOMEBREW_PREFIX.children.length
<ide> assert (HOMEBREW_PREFIX+'bin').directory?
<ide> assert_equal 3, (HOMEBREW_PREFIX+'bin').children.length
<ide> end | 1 |
PHP | PHP | call method for making hmvc requests | 60f69659ea3b95b4677d8e150c82d5ac59efe90e | <ide><path>system/router.php
<ide> class Router {
<ide>
<ide> /**
<del> * All of the loaded routes.
<add> * All of the loaded routes keyed by route file.
<ide> *
<ide> * @var array
<ide> */
<del> public static $routes;
<add> private static $routes = array();
<add>
<add> /**
<add> * Simulate a request to a given route. Useful for implementing HMVC.
<add> *
<add> * @param array|string $parameters
<add> * @return Response
<add> */
<add> public static function call($parameters)
<add> {
<add> $route = static::route('GET', (is_array($parameters)) ? implode('/', $parameters) : (string) $parameters);
<add>
<add> if ( ! is_null($route))
<add> {
<add> return $route->call();
<add> }
<add> }
<ide>
<ide> /**
<ide> * Search a set of routes for the route matching a method and URI.
<ide> class Router {
<ide> */
<ide> public static function route($method, $uri)
<ide> {
<del> if (is_null(static::$routes))
<del> {
<del> static::$routes = static::load($uri);
<del> }
<add> $routes = static::load($uri);
<ide>
<ide> // Put the request method and URI in route form.
<ide> // Routes begin with the request method and a forward slash.
<ide> $uri = $method.' /'.trim($uri, '/');
<ide>
<ide> // Is there an exact match for the request?
<del> if (isset(static::$routes[$uri]))
<add> if (isset($routes[$uri]))
<ide> {
<del> return Request::$route = new Route($uri, static::$routes[$uri]);
<add> return Request::$route = new Route($uri, $routes[$uri]);
<ide> }
<ide>
<del> foreach (static::$routes as $keys => $callback)
<add> foreach ($routes as $keys => $callback)
<ide> {
<ide> // Only check routes that have multiple URIs or wildcards.
<ide> // Other routes would have been caught by the check for literal matches.
<ide> public static function route($method, $uri)
<ide> */
<ide> public static function load($uri)
<ide> {
<del> $base = require APP_PATH.'routes'.EXT;
<add> $base = (isset(static::$routes[$path = APP_PATH.'routes'.EXT])) ? static::$routes[$path] : static::$routes[$path] = require $path;
<ide>
<ide> return (is_dir(APP_PATH.'routes') and $uri !== '') ? array_merge(static::load_from_directory($uri), $base) : $base;
<ide> }
<ide> private static function load_from_directory($uri)
<ide> // Iterate backwards through the URI looking for the deepest matching file.
<ide> foreach (array_reverse($segments, true) as $key => $value)
<ide> {
<del> if (file_exists($path = APP_PATH.'routes/'.implode('/', array_slice($segments, 0, $key + 1)).EXT))
<add> if (isset(static::$routes[$path = ROUTE_PATH.implode('/', array_slice($segments, 0, $key + 1)).EXT]))
<add> {
<add> return static::$routes[$path];
<add> }
<add> elseif (file_exists($path))
<ide> {
<del> return require $path;
<add> return static::$routes[$path] = require $path;
<ide> }
<ide> }
<ide> | 1 |
Text | Text | fix docs for next/image upgrade guide | 73c5b77a8484fa94f77a5392dc774ddbd1af6427 | <ide><path>docs/advanced-features/codemods.md
<ide> export default function Page() {
<ide>
<ide> ### `next-image-to-legacy-image`
<ide>
<del>Safely migrates existing Next.js 10, 11, 12 applications importing `next/image` to the renamed `next/legacy/image` import in Next.js 13.
<add>This codemod safely migrates existing Next.js 10, 11, 12 applications importing `next/image` to the renamed `next/legacy/image` import in Next.js 13.
<ide>
<ide> For example:
<ide>
<ide> export default function Home() {
<ide>
<ide> ### `next-image-experimental` (experimental)
<ide>
<del>Dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props.
<add>This codemod dangerously migrates from `next/legacy/image` to the new `next/image` by adding inline styles and removing unused props. Please note this codemod is experimental and only covers static usage (such as `<Image src={img} layout="responsive" />`) but not dynamic usage (such as `<Image {...props} />`).
<ide>
<ide> - Removes `layout` prop and adds `style`
<ide> - Removes `objectFit` prop and adds `style`
<ide><path>docs/upgrading.md
<ide> You can continue using `pages` with new features that work in both directories,
<ide>
<ide> ### `<Image/>` Component
<ide>
<del>Next.js 12 introduced new improvements to the Image Component with a temporary import: `next/future/image`. These improvements included less client-side JavaScript, easier ways to extend and style images, better accessibility, and native browser lazy loading.
<add>Next.js 12 introduced many improvements to the Image Component with a temporary import: `next/future/image`. These improvements included less client-side JavaScript, easier ways to extend and style images, better accessibility, and native browser lazy loading.
<ide>
<del>In version 13, this new behavior is now the default for `next/image`.
<add>Starting in Next.js 13, this new behavior is now the default for `next/image`.
<ide>
<ide> There are two codemods to help you migrate to the new Image Component:
<ide>
<del>- [**`next-image-to-legacy-image` codemod**](/docs/advanced-features/codemods.md#rename-instances-of-nextimage): Safely and automatically renames `next/image` imports to `next/legacy/image`. Existing components will maintain the same behavior.
<del>- [**`next-image-experimental` codemod**](/docs/advanced-features/codemods.md#migrate-next-image-experimental-experimental): Dangerously adds inline styles and removes unused props using the experimental. This will change the behavior of existing components to match the new defaults. To use this codemod, you need to run the `next-image-to-legacy-image` codemod first.
<add>- [next-image-to-legacy-image](/docs/advanced-features/codemods.md#rename-instances-of-nextimage): This codemod will safely and automatically rename `next/image` imports to `next/legacy/image` to maintain the same behavior as Next.js 12. We recommend running this codemod to quickly update to Next.js 13 automatically.
<add>- [next-image-experimental](/docs/advanced-features/codemods.md#next-image-experimental-experimental): After running the previous codemod, you can optionally run this experimental codemod to upgrade `next/legacy/image` to the new `next/image`, which will remove unused props and add inline styles. Please note this codemod is experimental and only covers static usage (such as `<Image src={img} layout="responsive" />`) but not dynamic usage (such as `<Image {...props} />`).
<ide>
<del>Alternatively, you can manually update props by following the [`next/future/image` migration guide](/docs/api-reference/next/image.md#migration). This will change the behavior of existing components to match the new defaults.
<add>Alternatively, you can manually update by following the [migration guide](/docs/advanced-features/codemods.md#next-image-experimental-experimental) and also see the [legacy comparison](/docs/api-reference/next/legacy/image.md#comparison).
<ide>
<ide> ### `<Link>` Component
<ide>
<ide><path>errors/next-image-upgrade-to-13.md
<ide> After running this codemod, you can optionally upgrade `next/legacy/image` to th
<ide> npx @next/codemod next-image-experimental .
<ide> ```
<ide>
<del>Please note this second codemod is experimental and only covers static usage, not dynamic usage (such `<Image {...props} />`).
<add>Please note this second codemod is experimental and only covers static usage (such as `<Image src={img} layout="responsive" />`) but not dynamic usage (such as `<Image {...props} />`).
<ide>
<ide> ### Useful Links
<ide> | 3 |
Mixed | Java | add doonlifecycle to m/s/c | 4257ef563a3bf017e0703c00057daf12b54738ba | <ide><path>docs/Operator-Matrix.md
<ide> Operator | || <sup title='At most one item. Use doOnEvent().'>([45](#notes-45))</sup>| <sup title='At most one item. Use doOnEvent().'>([45](#notes-45))</sup>| <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>|
<ide> <a name='doOnError'></a>`doOnError`||||||
<ide> <a name='doOnEvent'></a>`doOnEvent`| <sup title='Use doOnEach().'>([46](#notes-46))</sup>| <sup title='Use doOnEach().'>([46](#notes-46))</sup>||||
<del><a name='doOnLifecycle'></a>`doOnLifecycle`||||||
<add><a name='doOnLifecycle'></a>`doOnLifecycle`||||||
<ide> <a name='doOnNext'></a>`doOnNext`||| <sup title='Different terminology. Use doOnSuccess().'>([47](#notes-47))</sup>| <sup title='Different terminology. Use doOnSuccess().'>([47](#notes-47))</sup>| <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>|
<ide> <a name='doOnRequest'></a>`doOnRequest`|| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>|
<ide> <a name='doOnSubscribe'></a>`doOnSubscribe`||||||
<ide> Operator | |||||
<ide> <a name='never'></a>`never`||||||
<ide> <a name='observeOn'></a>`observeOn`||||||
<del><a name='ofType'></a>`ofType`||||| <sup title='Always empty thus no items to filter.'>([82](#notes-82))</sup>|
<add><a name='ofType'></a>`ofType`||||| <sup title='Always empty thus no items to filter.'>([82](#notes-82))</sup>|
<ide> <a name='onBackpressureBuffer'></a>`onBackpressureBuffer`|| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>|
<ide> <a name='onBackpressureDrop'></a>`onBackpressureDrop`|| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>|
<ide> <a name='onBackpressureLatest'></a>`onBackpressureLatest`|| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>| <sup title='Backpressure related and not supported outside Flowable.'>([48](#notes-48))</sup>|
<ide> Operator | |||||
<ide> <a name='toCompletionStage'></a>`toCompletionStage`| <sup title='Use firstStage.'>([98](#notes-98))</sup>| <sup title='Use firstStage.'>([98](#notes-98))</sup>||||
<ide> <a name='toFlowable'></a>`toFlowable`| <sup title='Would be no-op.'>([99](#notes-99))</sup>|||||
<del><a name='toFuture'></a>`toFuture`||||||
<add><a name='toFuture'></a>`toFuture`||||||
<ide> <a name='toList'></a>`toList`||| <sup title='At most one element to collect. Use map() to transform into a list/collection.'>([13](#notes-13))</sup>| <sup title='One element to collect. Use map() to transform into a list/collection.'>([14](#notes-14))</sup>| <sup title='Always empty. Use andThen() to bring in a collection.'>([15](#notes-15))</sup>|
<ide> <a name='toMap'></a>`toMap`||| <sup title='At most one element to collect. Use map() to transform into a list/collection.'>([13](#notes-13))</sup>| <sup title='One element to collect. Use map() to transform into a list/collection.'>([14](#notes-14))</sup>| <sup title='Always empty. Use andThen() to bring in a collection.'>([15](#notes-15))</sup>|
<ide> <a name='toMaybe'></a>`toMaybe`| <sup title='Use firstElement.'>([100](#notes-100))</sup>| <sup title='Use firstElement.'>([100](#notes-100))</sup>| <sup title='Would be no-op.'>([99](#notes-99))</sup>|||
<ide> Operator | |||| <sup title='Use merge().'>([108](#notes-108))</sup>|
<ide> <a name='zipArray'></a>`zipArray`||||| <sup title='Use mergeArray().'>([109](#notes-109))</sup>|
<ide> <a name='zipWith'></a>`zipWith`||||| <sup title='Use mergeWith().'>([110](#notes-110))</sup>|
<del><a name='total'></a>**237 operators** | **215** | **209** | **111** | **95** | **76** |
<add><a name='total'></a>**237 operators** | **215** | **209** | **113** | **97** | **78** |
<ide>
<ide> #### Notes
<ide> <a name='notes-1'></a><sup>1</sup> Use [`contains()`](#contains).<br/>
<ide> Operator | 
<ide> 18. Maybe.concatMapSingle()
<ide> 19. Single.concatMapSingle()
<del>20. Maybe.doOnLifecycle()
<del>21. Single.doOnLifecycle()
<del>22. Completable.doOnLifecycle()
<del>23. Single.mergeArray()
<del>24. Single.mergeArrayDelayError()
<del>25. Single.ofType()
<del>26. Completable.onErrorReturn()
<del>27. Completable.onErrorReturnItem()
<del>28. Maybe.safeSubscribe()
<del>29. Single.safeSubscribe()
<del>30. Completable.safeSubscribe()
<del>31. Completable.sequenceEqual()
<del>32. Maybe.startWith()
<del>33. Single.startWith()
<del>34. Maybe.toFuture()
<del>35. Completable.toFuture()
<add>20. Single.mergeArray()
<add>21. Single.mergeArrayDelayError()
<add>22. Completable.onErrorReturn()
<add>23. Completable.onErrorReturnItem()
<add>24. Maybe.safeSubscribe()
<add>25. Single.safeSubscribe()
<add>26. Completable.safeSubscribe()
<add>27. Completable.sequenceEqual()
<add>28. Maybe.startWith()
<add>29. Single.startWith()
<ide><path>src/main/java/io/reactivex/rxjava3/core/Completable.java
<ide> import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.rxjava3.annotations.*;
<add>import io.reactivex.rxjava3.core.Observable;
<ide> import io.reactivex.rxjava3.disposables.Disposable;
<ide> import io.reactivex.rxjava3.exceptions.*;
<ide> import io.reactivex.rxjava3.functions.*;
<ide> public final Completable doOnEvent(@NonNull Consumer<@Nullable ? super Throwable
<ide> return RxJavaPlugins.onAssembly(new CompletableDoOnEvent(this, onEvent));
<ide> }
<ide>
<add> /**
<add> * Calls the appropriate {@code onXXX} method (shared between all {@link CompletableObserver}s) for the lifecycle events of
<add> * the sequence (subscription, disposal).
<add> * <p>
<add> * <img width="640" height="257" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.doOnLifecycle.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnLifecycle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param onSubscribe
<add> * a {@link Consumer} called with the {@link Disposable} sent via {@link CompletableObserver#onSubscribe(Disposable)}
<add> * @param onDispose
<add> * called when the downstream disposes the {@code Disposable} via {@code dispose()}
<add> * @return the new {@code Completable} instance
<add> * @throws NullPointerException if {@code onSubscribe} or {@code onDispose} is {@code null}
<add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public final Completable doOnLifecycle(@NonNull Consumer<? super Disposable> onSubscribe, @NonNull Action onDispose) {
<add> return doOnLifecycle(onSubscribe, Functions.emptyConsumer(),
<add> Functions.EMPTY_ACTION, Functions.EMPTY_ACTION,
<add> Functions.EMPTY_ACTION, onDispose);
<add> }
<add>
<ide> /**
<ide> * Returns a {@code Completable} instance that calls the various callbacks upon the specific
<ide> * lifecycle events.
<ide><path>src/main/java/io/reactivex/rxjava3/core/Maybe.java
<ide> public final Maybe<T> doOnEvent(@NonNull BiConsumer<@Nullable ? super T, @Nullab
<ide> return RxJavaPlugins.onAssembly(new MaybeDoOnEvent<>(this, onEvent));
<ide> }
<ide>
<add> /**
<add> * Calls the appropriate {@code onXXX} method (shared between all {@link MaybeObserver}s) for the lifecycle events of
<add> * the sequence (subscription, disposal).
<add> * <p>
<add> * <img width="640" height="183" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.doOnLifecycle.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnLifecycle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param onSubscribe
<add> * a {@link Consumer} called with the {@link Disposable} sent via {@link MaybeObserver#onSubscribe(Disposable)}
<add> * @param onDispose
<add> * called when the downstream disposes the {@code Disposable} via {@code dispose()}
<add> * @return the new {@code Maybe} instance
<add> * @throws NullPointerException if {@code onSubscribe} or {@code onDispose} is {@code null}
<add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public final Maybe<T> doOnLifecycle(@NonNull Consumer<? super Disposable> onSubscribe, @NonNull Action onDispose) {
<add> Objects.requireNonNull(onSubscribe, "onSubscribe is null");
<add> Objects.requireNonNull(onDispose, "onDispose is null");
<add> return RxJavaPlugins.onAssembly(new MaybeDoOnLifecycle<>(this, onSubscribe, onDispose));
<add> }
<add>
<ide> /**
<ide> * Calls the shared {@link Consumer} with the {@link Disposable} sent through the {@code onSubscribe} for each
<ide> * {@link MaybeObserver} that subscribes to the current {@code Maybe}.
<ide><path>src/main/java/io/reactivex/rxjava3/core/Single.java
<ide> public final Single<T> doFinally(@NonNull Action onFinally) {
<ide> return RxJavaPlugins.onAssembly(new SingleDoFinally<>(this, onFinally));
<ide> }
<ide>
<add> /**
<add> * Calls the appropriate {@code onXXX} method (shared between all {@link SingleObserver}s) for the lifecycle events of
<add> * the sequence (subscription, disposal).
<add> * <p>
<add> * <img width="640" height="232" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnLifecycle.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code doOnLifecycle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param onSubscribe
<add> * a {@link Consumer} called with the {@link Disposable} sent via {@link SingleObserver#onSubscribe(Disposable)}
<add> * @param onDispose
<add> * called when the downstream disposes the {@code Disposable} via {@code dispose()}
<add> * @return the new {@code Single} instance
<add> * @throws NullPointerException if {@code onSubscribe} or {@code onDispose} is {@code null}
<add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a>
<add> * @since 3.0.0
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @NonNull
<add> public final Single<T> doOnLifecycle(@NonNull Consumer<? super Disposable> onSubscribe, @NonNull Action onDispose) {
<add> Objects.requireNonNull(onSubscribe, "onSubscribe is null");
<add> Objects.requireNonNull(onDispose, "onDispose is null");
<add> return RxJavaPlugins.onAssembly(new SingleDoOnLifecycle<>(this, onSubscribe, onDispose));
<add> }
<add>
<ide> /**
<ide> * Calls the shared consumer with the {@link Disposable} sent through the {@code onSubscribe} for each
<ide> * {@link SingleObserver} that subscribes to the current {@code Single}.
<ide> public final Flowable<T> mergeWith(@NonNull SingleSource<? extends T> other) {
<ide> * @return the new {@link Maybe} instance
<ide> * @throws NullPointerException if {@code clazz} is {@code null}
<ide> * @see <a href="http://reactivex.io/documentation/operators/filter.html">ReactiveX operators documentation: Filter</a>
<add> * @since 3.0.0
<ide> */
<ide> @CheckReturnValue
<ide> @NonNull
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDoOnLifecycle.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.rxjava3.internal.operators.maybe;
<add>
<add>import io.reactivex.rxjava3.annotations.NonNull;
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.disposables.Disposable;
<add>import io.reactivex.rxjava3.exceptions.Exceptions;
<add>import io.reactivex.rxjava3.functions.*;
<add>import io.reactivex.rxjava3.internal.disposables.*;
<add>import io.reactivex.rxjava3.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Invokes callbacks upon {@code onSubscribe} from upstream and
<add> * {@code dispose} from downstream.
<add> *
<add> * @param <T> the element type of the flow
<add> * @since 3.0.0
<add> */
<add>public final class MaybeDoOnLifecycle<T> extends AbstractMaybeWithUpstream<T, T> {
<add>
<add> final Consumer<? super Disposable> onSubscribe;
<add>
<add> final Action onDispose;
<add>
<add> public MaybeDoOnLifecycle(Maybe<T> upstream, Consumer<? super Disposable> onSubscribe,
<add> Action onDispose) {
<add> super(upstream);
<add> this.onSubscribe = onSubscribe;
<add> this.onDispose = onDispose;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super T> observer) {
<add> source.subscribe(new MaybeLifecycleObserver<>(observer, onSubscribe, onDispose));
<add> }
<add>
<add> static final class MaybeLifecycleObserver<T> implements MaybeObserver<T>, Disposable {
<add>
<add> final MaybeObserver<? super T> downstream;
<add>
<add> final Consumer<? super Disposable> onSubscribe;
<add>
<add> final Action onDispose;
<add>
<add> Disposable upstream;
<add>
<add> MaybeLifecycleObserver(MaybeObserver<? super T> downstream, Consumer<? super Disposable> onSubscribe, Action onDispose) {
<add> this.downstream = downstream;
<add> this.onSubscribe = onSubscribe;
<add> this.onDispose = onDispose;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(@NonNull Disposable d) {
<add> // this way, multiple calls to onSubscribe can show up in tests that use doOnSubscribe to validate behavior
<add> try {
<add> onSubscribe.accept(d);
<add> } catch (Throwable e) {
<add> Exceptions.throwIfFatal(e);
<add> d.dispose();
<add> this.upstream = DisposableHelper.DISPOSED;
<add> EmptyDisposable.error(e, downstream);
<add> return;
<add> }
<add> if (DisposableHelper.validate(this.upstream, d)) {
<add> this.upstream = d;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(@NonNull T t) {
<add> if (upstream != DisposableHelper.DISPOSED) {
<add> upstream = DisposableHelper.DISPOSED;
<add> downstream.onSuccess(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(@NonNull Throwable e) {
<add> if (upstream != DisposableHelper.DISPOSED) {
<add> upstream = DisposableHelper.DISPOSED;
<add> downstream.onError(e);
<add> } else {
<add> RxJavaPlugins.onError(e);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (upstream != DisposableHelper.DISPOSED) {
<add> upstream = DisposableHelper.DISPOSED;
<add> downstream.onComplete();
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> try {
<add> onDispose.run();
<add> } catch (Throwable e) {
<add> Exceptions.throwIfFatal(e);
<add> RxJavaPlugins.onError(e);
<add> }
<add> upstream.dispose();
<add> upstream = DisposableHelper.DISPOSED;
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return upstream.isDisposed();
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleDoOnLifecycle.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>package io.reactivex.rxjava3.internal.operators.single;
<add>
<add>import io.reactivex.rxjava3.annotations.NonNull;
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.disposables.Disposable;
<add>import io.reactivex.rxjava3.exceptions.Exceptions;
<add>import io.reactivex.rxjava3.functions.*;
<add>import io.reactivex.rxjava3.internal.disposables.*;
<add>import io.reactivex.rxjava3.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Invokes callbacks upon {@code onSubscribe} from upstream and
<add> * {@code dispose} from downstream.
<add> *
<add> * @param <T> the element type of the flow
<add> * @since 3.0.0
<add> */
<add>public final class SingleDoOnLifecycle<T> extends Single<T> {
<add>
<add> final Single<T> source;
<add>
<add> final Consumer<? super Disposable> onSubscribe;
<add>
<add> final Action onDispose;
<add>
<add> public SingleDoOnLifecycle(Single<T> upstream, Consumer<? super Disposable> onSubscribe,
<add> Action onDispose) {
<add> this.source = upstream;
<add> this.onSubscribe = onSubscribe;
<add> this.onDispose = onDispose;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super T> observer) {
<add> source.subscribe(new SingleLifecycleObserver<>(observer, onSubscribe, onDispose));
<add> }
<add>
<add> static final class SingleLifecycleObserver<T> implements SingleObserver<T>, Disposable {
<add>
<add> final SingleObserver<? super T> downstream;
<add>
<add> final Consumer<? super Disposable> onSubscribe;
<add>
<add> final Action onDispose;
<add>
<add> Disposable upstream;
<add>
<add> SingleLifecycleObserver(SingleObserver<? super T> downstream, Consumer<? super Disposable> onSubscribe, Action onDispose) {
<add> this.downstream = downstream;
<add> this.onSubscribe = onSubscribe;
<add> this.onDispose = onDispose;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(@NonNull Disposable d) {
<add> // this way, multiple calls to onSubscribe can show up in tests that use doOnSubscribe to validate behavior
<add> try {
<add> onSubscribe.accept(d);
<add> } catch (Throwable e) {
<add> Exceptions.throwIfFatal(e);
<add> d.dispose();
<add> this.upstream = DisposableHelper.DISPOSED;
<add> EmptyDisposable.error(e, downstream);
<add> return;
<add> }
<add> if (DisposableHelper.validate(this.upstream, d)) {
<add> this.upstream = d;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(@NonNull T t) {
<add> if (upstream != DisposableHelper.DISPOSED) {
<add> upstream = DisposableHelper.DISPOSED;
<add> downstream.onSuccess(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(@NonNull Throwable e) {
<add> if (upstream != DisposableHelper.DISPOSED) {
<add> upstream = DisposableHelper.DISPOSED;
<add> downstream.onError(e);
<add> } else {
<add> RxJavaPlugins.onError(e);
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> try {
<add> onDispose.run();
<add> } catch (Throwable e) {
<add> Exceptions.throwIfFatal(e);
<add> RxJavaPlugins.onError(e);
<add> }
<add> upstream.dispose();
<add> upstream = DisposableHelper.DISPOSED;
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return upstream.isDisposed();
<add> }
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableDoOnLifecycleTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.completable;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.mockito.ArgumentMatchers.any;
<add>import static org.mockito.Mockito.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.disposables.Disposable;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>import io.reactivex.rxjava3.functions.*;
<add>import io.reactivex.rxjava3.observers.TestObserver;
<add>import io.reactivex.rxjava3.subjects.CompletableSubject;
<add>import io.reactivex.rxjava3.testsupport.TestHelper;
<add>
<add>public class CompletableDoOnLifecycleTest extends RxJavaTest {
<add>
<add> @Test
<add> public void empty() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Completable.complete()
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertResult();
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void error() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Completable.error(new TestException())
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void onSubscribeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onSubscribe).accept(any());
<add>
<add> Disposable bs = Disposable.empty();
<add>
<add> new Completable() {
<add> @Override
<add> protected void subscribeActual(CompletableObserver observer) {
<add> observer.onSubscribe(bs);
<add> observer.onError(new TestException("Second"));
<add> observer.onComplete();
<add> }
<add> }
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .to(TestHelper.<Integer>testConsumer())
<add> .assertFailureAndMessage(TestException.class, "First");
<add>
<add> assertTrue(bs.isDisposed());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void onDisposeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onDispose).run();
<add>
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(cs.hasObservers());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "First");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = cs
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(cs.hasObservers());
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> TestHelper.checkDisposed(CompletableSubject.create().doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeCompletable(m -> m.doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDoOnLifecycleTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.maybe;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.disposables.Disposable;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>import io.reactivex.rxjava3.functions.*;
<add>import io.reactivex.rxjava3.observers.TestObserver;
<add>import io.reactivex.rxjava3.subjects.MaybeSubject;
<add>import io.reactivex.rxjava3.testsupport.TestHelper;
<add>
<add>public class MaybeDoOnLifecycleTest extends RxJavaTest {
<add>
<add> @Test
<add> public void success() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Maybe.just(1)
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertResult(1);
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void empty() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Maybe.empty()
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertResult();
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void error() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Maybe.error(new TestException())
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void onSubscribeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onSubscribe).accept(any());
<add>
<add> Disposable bs = Disposable.empty();
<add>
<add> new Maybe<Integer>() {
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super Integer> observer) {
<add> observer.onSubscribe(bs);
<add> observer.onError(new TestException("Second"));
<add> observer.onComplete();
<add> observer.onSuccess(1);
<add> }
<add> }
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .to(TestHelper.<Integer>testConsumer())
<add> .assertFailureAndMessage(TestException.class, "First");
<add>
<add> assertTrue(bs.isDisposed());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void onDisposeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onDispose).run();
<add>
<add> MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> to = ms
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(ms.hasObservers());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "First");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> to = ms
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(ms.hasObservers());
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> TestHelper.checkDisposed(MaybeSubject.create().doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybe(m -> m.doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleDoOnLifecycleTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.rxjava3.internal.operators.single;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.*;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.rxjava3.core.*;
<add>import io.reactivex.rxjava3.disposables.Disposable;
<add>import io.reactivex.rxjava3.exceptions.TestException;
<add>import io.reactivex.rxjava3.functions.*;
<add>import io.reactivex.rxjava3.observers.TestObserver;
<add>import io.reactivex.rxjava3.subjects.SingleSubject;
<add>import io.reactivex.rxjava3.testsupport.TestHelper;
<add>
<add>public class SingleDoOnLifecycleTest extends RxJavaTest {
<add>
<add> @Test
<add> public void success() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Single.just(1)
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertResult(1);
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void error() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> Single.error(new TestException())
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test()
<add> .assertFailure(TestException.class);
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> }
<add>
<add> @Test
<add> public void onSubscribeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onSubscribe).accept(any());
<add>
<add> Disposable bs = Disposable.empty();
<add>
<add> new Single<Integer>() {
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Integer> observer) {
<add> observer.onSubscribe(bs);
<add> observer.onError(new TestException("Second"));
<add> observer.onSuccess(1);
<add> }
<add> }
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .to(TestHelper.<Integer>testConsumer())
<add> .assertFailureAndMessage(TestException.class, "First");
<add>
<add> assertTrue(bs.isDisposed());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "Second");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose, never()).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void onDisposeCrash() throws Throwable {
<add> TestHelper.withErrorTracking(errors -> {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> doThrow(new TestException("First")).when(onDispose).run();
<add>
<add> SingleSubject<Integer> ss = SingleSubject.create();
<add>
<add> TestObserver<Integer> to = ss
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(ss.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(ss.hasObservers());
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "First");
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() throws Throwable {
<add> @SuppressWarnings("unchecked")
<add> Consumer<? super Disposable> onSubscribe = mock(Consumer.class);
<add> Action onDispose = mock(Action.class);
<add>
<add> SingleSubject<Integer> ss = SingleSubject.create();
<add>
<add> TestObserver<Integer> to = ss
<add> .doOnLifecycle(onSubscribe, onDispose)
<add> .test();
<add>
<add> assertTrue(ss.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(ss.hasObservers());
<add>
<add> verify(onSubscribe).accept(any());
<add> verify(onDispose).run();
<add> }
<add>
<add> @Test
<add> public void isDisposed() {
<add> TestHelper.checkDisposed(SingleSubject.create().doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeSingle(m -> m.doOnLifecycle(d -> { }, () -> { }));
<add> }
<add>} | 9 |
Ruby | Ruby | add missing requires | e28c4e5d59c76240e6d3299d6f673cafc283f10f | <ide><path>activejob/test/adapters/delayed_job.rb
<ide> ActiveJob::Base.queue_adapter = :delayed_job
<ide>
<ide> $LOAD_PATH << File.expand_path("../support/delayed_job", __dir__)
<add>require "active_support/core_ext/kernel/reporting"
<ide>
<ide> Delayed::Worker.delay_jobs = false
<ide> Delayed::Worker.backend = :test
<ide><path>activerecord/test/cases/helper.rb
<ide> require "cases/test_case"
<ide> require "active_support/dependencies"
<ide> require "active_support/logger"
<add>require "active_support/core_ext/kernel/reporting"
<ide> require "active_support/core_ext/kernel/singleton_class"
<ide>
<ide> require "support/config" | 2 |
Java | Java | fix typos in tests | f78c21e40b99707827e815efd06de7f92cfc5f70 | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationsScannerTests.java
<ide> class AnnotationsScannerTests {
<ide>
<ide> @Test
<del> void directStrategyOnClassWhenNotAnnoatedScansNone() {
<add> void directStrategyOnClassWhenNotAnnotatedScansNone() {
<ide> Class<?> source = WithNoAnnotations.class;
<ide> assertThat(scan(source, SearchStrategy.DIRECT)).isEmpty();
<ide> }
<ide> void dirextStrategyOnBridgedMethodScansAnnotations() throws Exception {
<ide> @Test
<ide> void typeHierarchyStrategyOnMethodWithIgnorablesScansAnnotations()
<ide> throws Exception {
<del> Method source = methodFrom(Ignoreable.class);
<add> Method source = methodFrom(Ignorable.class);
<ide> assertThat(scan(source, SearchStrategy.TYPE_HIERARCHY)).containsExactly(
<ide> "0:TestAnnotation1");
<ide> }
<ide> public void method(String arg) {
<ide> }
<ide>
<ide> @SuppressWarnings("serial")
<del> static class Ignoreable implements IgnoreableOverrideInterface1, IgnoreableOverrideInterface2, Serializable {
<add> static class Ignorable implements IgnorableOverrideInterface1, IgnorableOverrideInterface2, Serializable {
<ide>
<ide> @Override
<ide> @TestAnnotation1
<ide> public void method() {
<ide> }
<ide> }
<ide>
<del> interface IgnoreableOverrideInterface1 {
<add> interface IgnorableOverrideInterface1 {
<ide>
<ide> @Nullable
<ide> void method();
<ide> }
<ide>
<del> interface IgnoreableOverrideInterface2 {
<add> interface IgnorableOverrideInterface2 {
<ide>
<ide> @Nullable
<ide> void method();
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
<ide> void getWithInheritedAnnotationsAttributesWithConventionBasedComposedAnnotation(
<ide>
<ide> @Test
<ide> void getWithInheritedAnnotationsFromHalfConventionBasedAndHalfAliasedComposedAnnotation1() {
<del> // SPR-13554: convention mapping mixed with AlaisFor annotations
<del> // xmlConfigFiles can be used because it has an AlaisFor annotation
<add> // SPR-13554: convention mapping mixed with AliasFor annotations
<add> // xmlConfigFiles can be used because it has an AliasFor annotation
<ide> MergedAnnotation<?> annotation = MergedAnnotations.from(
<ide> HalfConventionBasedAndHalfAliasedComposedContextConfigurationClass1.class,
<ide> SearchStrategy.INHERITED_ANNOTATIONS).get(ContextConfiguration.class);
<ide> void getWithInheritedAnnotationsFromHalfConventionBasedAndHalfAliasedComposedAnn
<ide>
<ide> @Test
<ide> void withInheritedAnnotationsFromHalfConventionBasedAndHalfAliasedComposedAnnotation2() {
<del> // SPR-13554: convention mapping mixed with AlaisFor annotations
<del> // locations doesn't apply because it has no AlaisFor annotation
<add> // SPR-13554: convention mapping mixed with AliasFor annotations
<add> // locations doesn't apply because it has no AliasFor annotation
<ide> MergedAnnotation<?> annotation = MergedAnnotations.from(
<ide> HalfConventionBasedAndHalfAliasedComposedContextConfigurationClass2.class,
<ide> SearchStrategy.INHERITED_ANNOTATIONS).get(ContextConfiguration.class); | 2 |
PHP | PHP | call container instance directly | 5c129ba119b6fce2a723cbe00e6dece0d4199c6b | <ide><path>src/Illuminate/Notifications/Messages/MailMessage.php
<ide>
<ide> use Traversable;
<ide> use Illuminate\Mail\Markdown;
<add>use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Contracts\Support\Renderable;
<ide>
<ide> protected function arrayOfAddresses($address)
<ide> */
<ide> public function render()
<ide> {
<del> return app(Markdown::class)->render($this->markdown, $this->data());
<add> return Container::getInstance()
<add> ->make(Markdown::class)
<add> ->render($this->markdown, $this->data());
<ide> }
<ide> } | 1 |
PHP | PHP | fix logical error | be7a10d5991cf11b97a2c4c0676f7536dcb9bdb7 | <ide><path>src/Console/ShellDispatcher.php
<ide> public function addShortPluginAliases()
<ide> "command '$shell' in plugin '$plugin' was not aliased, conflicts with '$other'",
<ide> ['shell-dispatcher']
<ide> );
<del> continue;
<ide> }
<add> continue;
<ide> }
<ide>
<ide> if (isset($others[$shell])) { | 1 |
Python | Python | remove un-needed attribute lookup in 1.2 | bd089c209df73d91fb83e44c8c5c5ad9bda64ca1 | <ide><path>numpy/core/defmatrix.py
<ide> def __mul__(self, other):
<ide> if isinstance(other,(N.ndarray, list, tuple)) :
<ide> # This promotes 1-D vectors to row vectors
<ide> return N.dot(self, asmatrix(other))
<del> if N.isscalar(other) or not hasattr(other, '__rmul__') :
<add> if isscalar(other) or not hasattr(other, '__rmul__') :
<ide> return N.dot(self, other)
<ide> return NotImplemented
<ide> | 1 |
Text | Text | post about 0.10.3 | 0f460b03f3143e17cb783186df13a3ad769cfb06 | <ide><path>doc/blog/release/v0.10.3.md
<add>date: Wed Apr 3 11:24:08 PDT 2013
<add>version: 0.10.3
<add>category: release
<add>title: Node v0.10.3 (Stable)
<add>slug: node-v0-10-3-stable
<add>
<add>2013.04.03, Version 0.10.3 (Stable)
<add>
<add>* npm: Upgrade to 1.2.17
<add>
<add>* child_process: acknowledge sent handles (Fedor Indutny)
<add>
<add>* etw: update prototypes to match dtrace provider (Timothy J Fontaine)
<add>
<add>* dtrace: pass more arguments to probes (Dave Pacheco)
<add>
<add>* build: allow building with dtrace on osx (Dave Pacheco)
<add>
<add>* http: Remove legacy ECONNRESET workaround code (isaacs)
<add>
<add>* http: Ensure socket cleanup on client response end (isaacs)
<add>
<add>* tls: Destroy socket when encrypted side closes (isaacs)
<add>
<add>* repl: isSyntaxError() catches "strict mode" errors (Nathan Rajlich)
<add>
<add>* crypto: Pass options to ctor calls (isaacs)
<add>
<add>* src: tie process.versions.uv to uv_version_string() (Ben Noordhuis)
<add>
<add>
<add>Source Code: http://nodejs.org/dist/v0.10.3/node-v0.10.3.tar.gz
<add>
<add>Macintosh Installer (Universal): http://nodejs.org/dist/v0.10.3/node-v0.10.3.pkg
<add>
<add>Windows Installer: http://nodejs.org/dist/v0.10.3/node-v0.10.3-x86.msi
<add>
<add>Windows x64 Installer: http://nodejs.org/dist/v0.10.3/x64/node-v0.10.3-x64.msi
<add>
<add>Windows x64 Files: http://nodejs.org/dist/v0.10.3/x64/
<add>
<add>Linux 32-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-linux-x86.tar.gz
<add>
<add>Linux 64-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-linux-x64.tar.gz
<add>
<add>Solaris 32-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-sunos-x86.tar.gz
<add>
<add>Solaris 64-bit Binary: http://nodejs.org/dist/v0.10.3/node-v0.10.3-sunos-x64.tar.gz
<add>
<add>Other release files: http://nodejs.org/dist/v0.10.3/
<add>
<add>Website: http://nodejs.org/docs/v0.10.3/
<add>
<add>Documentation: http://nodejs.org/docs/v0.10.3/api/
<add>
<add>Shasums:
<add>
<add>```
<add>9b2f0936ee60aa65f6a5053e82440508aa9be0a7 node-v0.10.3-darwin-x64.tar.gz
<add>f0392db831ca58c1f7b2d857d7e8cc601ea8b022 node-v0.10.3-darwin-x86.tar.gz
<add>9a375e77f9994fbd4afd741bae64c548f2a43a64 node-v0.10.3-linux-x64.tar.gz
<add>3323da517271e45a3850b169b10ef3d254a263a9 node-v0.10.3-linux-x86.tar.gz
<add>0026e2453a3940ed16b9569b8187943ccf0aeb45 node-v0.10.3-sunos-x64.tar.gz
<add>af88ad2dc98368b36f1aafc7b79f8378169fc56e node-v0.10.3-sunos-x86.tar.gz
<add>e057c8841ddbe4dc8bc155a28b7e07dbe3d108d1 node-v0.10.3-x86.msi
<add>a37575d47de5696b8abb2e12dc3e9d0cdb5d17f6 node-v0.10.3.pkg
<add>4a1feb4ac18ede9e7193921f59fc181c88b1c7ba node-v0.10.3.tar.gz
<add>9d9266d1e69bfe24837c67ff755f055fd049cd48 node.exe
<add>8762416a5e0d71e285215efde181c7242f3f2c6f node.exp
<add>5c05f332070a77900010f15c1074c4e86e20fa0d node.lib
<add>a8dc61535f6ae5fd13bce9cdca989ffc113a4080 node.pdb
<add>b834751b2e9f18e6ef38cf9fe5331e6073e3cab2 x64/node-v0.10.3-x64.msi
<add>932c30a53f546717f00de063ee09fc8ce603dd2a x64/node.exe
<add>a3e91038e027c91a555116d2c20742eea2e9378f x64/node.exp
<add>d60bb0f9026df9dcc17cff0267964032aaf46712 x64/node.lib
<add>f645a2d63179ae749defe13c653cf1777dd9021a x64/node.pdb
<add>``` | 1 |
Javascript | Javascript | remove check for _wrapperstate.pendingupdate | 57d59ea344e2766bd84952e7df56aea6e29abf4a | <ide><path>src/renderers/dom/client/wrappers/ReactDOMSelect.js
<ide> function _handleChange(event) {
<ide> var props = this._currentElement.props;
<ide> var returnValue = LinkedValueUtils.executeOnChange(props, event);
<ide>
<del> if (this._rootNodeID && !this._wrapperState.pendingUpdate) {
<add> if (this._rootNodeID) {
<ide> this._wrapperState.pendingUpdate = true;
<ide> }
<ide> ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); | 1 |
Ruby | Ruby | add comment and use constants | 761cbd3dabf12eed5b796ccf528f36effc9e58f0 | <ide><path>Library/Homebrew/install.rb
<ide> def text_for_keg_only_formula f
<ide> end
<ide> end
<ide>
<add>ORIGINAL_PATHS = ENV['PATH'].split(':').map{ |p| File.expand_path p }
<add>HOMEBREW_BIN = (HOMEBREW_PREFIX+'bin').to_s
<add>
<ide> def install f
<ide> show_summary_heading = false
<ide>
<del> paths = ENV['PATH'].split(':').map{ |p| File.expand_path p }
<del> rootbin = (HOMEBREW_PREFIX+'bin').to_s
<del> unless paths.include? rootbin
<del> ENV.prepend 'PATH', rootbin, ':'
<del> end
<add> # we must do this or tools like pkg-config won't get found by configure scripts etc.
<add> ENV.prepend 'PATH', HOMEBREW_BIN, ':' unless ORIGINAL_PATHS.include? HOMEBREW_BIN
<ide>
<ide> f.deps.uniq.each do |dep|
<ide> dep = Formula.factory dep
<ide> def install f
<ide> # warn the user if stuff was installed outside of their PATH
<ide> [f.bin, f.sbin].each do |bin|
<ide> if bin.directory?
<del> rootbin = (HOMEBREW_PREFIX/bin.basename).to_s
<ide> bin = File.expand_path bin
<del> unless paths.include? rootbin
<del> opoo "#{rootbin} is not in your PATH"
<add> unless ORIGINAL_PATHS.include? HOMEBREW_BIN
<add> opoo "#{HOMEBREW_BIN} is not in your PATH"
<ide> puts "You can amend this by altering your ~/.bashrc file"
<ide> show_summary_heading = true
<ide> end | 1 |
Text | Text | add c# guide for lists | 40c17b6ba1d34cdf09f836ffcd16523adbcf47da | <ide><path>docs/how-to-setup-freecodecamp-locally.md
<ide> Start by installing these prerequisite software.
<ide>
<ide> | Prerequisite | Version | Notes |
<ide> | ------------------------------------------- | ------- | ----- |
<del>| [MongoDB Community Server](https://docs.mongodb.com/manual/administration/install-community/) | `3.6` | [Release Notes](https://docs.mongodb.com/manual/release-notes/), Note: We currently on `3.6`, an [upgrade is planned](https://github.com/freeCodeCamp/freeCodeCamp/issues/18275).
<del>| [Node.js](http://nodejs.org) | `8.x` | [LTS Schedule](https://github.com/nodejs/Release#release-schedule), Note: We currently on `8.x`, an upgrade is planned to 10.x |
<add>| [MongoDB Community Server](https://docs.mongodb.com/manual/administration/install-community/) | `3.6` | [Release Notes](https://docs.mongodb.com/manual/release-notes/), Note: We are currently on `3.6`, an [upgrade is planned](https://github.com/freeCodeCamp/freeCodeCamp/issues/18275).
<add>| [Node.js](http://nodejs.org) | `8.x` | [LTS Schedule](https://github.com/nodejs/Release#release-schedule), Note: We are currently on `8.x`, an upgrade is planned to 10.x |
<ide> | npm (comes bundled with Node) | `6.x` | Does not have LTS releases, we use the version bundled with Node LTS |
<ide>
<ide> **Important:**
<ide><path>guide/english/csharp/list/index.md
<add>---
<add>title: Lists
<add>---
<add>
<add># Lists
<add>
<add>A list is a data structure that holds variables in a specific order. It can hold any type of variable, and the type is defined when initializing the list.
<add>
<add>A list is similar to an array, but unlike arrays, which must have a fixed size, lists are dynamically sized. This is useful if you do not know the number of variables that will be included, or if additional variables will be added in the future.
<add>
<add>## Initializing a list
<add>Lists are initialized using the following format:
<add>`List<type> = new List<type>();`
<add>
<add>Here are examples of how lists would be initialized for a few different data types:
<add>`List<int> = new List<int>();`
<add>`List<string> = new List<string>();`
<add>`List<MyCustomPoCo> = new List<MyCustomPoCo>();`
<add>
<add>## Adding items to a list
<add>Items can be added to the list using the following syntax.
<add>`List.Add(ItemToAdd)`
<add>
<add>For example:
<add>`List.Add(33)`
<add>`List.Add("I am a string.")`
<add>
<add>It is also possible to use the object initializer format to initialize a list with a set of data.
<add>```
<add>List<int> = new List<Int> { 11, 22, 33, 44, 55, 66 };
<add>```
<add>```
<add>List<MyClass> myClass = new List<MyClass>
<add>{
<add> new MyClass(){ Id = 1, Name = "First" },
<add> new MyClass(){ Id = 2, Name = "Second" },
<add> new MyClass(){ Id = 3, Name = "Third" },
<add>};
<add>```
<ide>\ No newline at end of file | 2 |
Python | Python | copy input for i0 calculation | f8f8ca74391b5681d4e16bccc282ada87a6d0b8d | <ide><path>numpy/lib/function_base.py
<ide> def _i0_2(x):
<ide> return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x)
<ide>
<ide> def i0(x):
<del> x = atleast_1d(x)
<add> x = atleast_1d(x).copy()
<ide> y = empty_like(x)
<ide> ind = (x<0)
<ide> x[ind] = -x[ind] | 1 |
Python | Python | add a layer type for history features | 6aa6a5bc25eeebf1ffea4ee97f7e26d3f09c357a | <ide><path>spacy/_ml.py
<ide> from thinc.api import FeatureExtracter, with_getitem
<ide> from thinc.neural.pooling import Pooling, max_pool, mean_pool, sum_pool
<ide> from thinc.neural._classes.attention import ParametricAttention
<add>from thinc.neural._classes.embed import Embed
<ide> from thinc.linear.linear import LinearModel
<ide> from thinc.api import uniqued, wrap, flatten_add_lengths, noop
<ide>
<ide> def backward(dYp_ids, sgd=None):
<ide> return Yfp, backward
<ide>
<ide>
<add>def HistoryFeatures(nr_class, hist_size=8, nr_dim=8):
<add> '''Wrap a model, adding features representing action history.'''
<add> embed = Embed(nr_dim, nr_dim, nr_class)
<add> ops = embed.ops
<add> def add_history_fwd(vectors_hists, drop=0.):
<add> vectors, hist_ids = vectors_hists
<add> flat_hists, bp_hists = embed.begin_update(hist_ids.flatten(), drop=drop)
<add> hists = flat_hists.reshape((hist_ids.shape[0],
<add> hist_ids.shape[1] * flat_hists.shape[1]))
<add> outputs = ops.xp.hstack((vectors, hists))
<add>
<add> def add_history_bwd(d_outputs, sgd=None):
<add> d_vectors = d_outputs[:, :vectors.shape[1]]
<add> d_hists = d_outputs[:, vectors.shape[1]:]
<add> bp_hists(d_hists.reshape((d_hists.shape[0]*hist_size,
<add> int(d_hists.shape[1]/hist_size))), sgd=sgd)
<add> return embed.ops.xp.ascontiguousarray(d_vectors)
<add> return outputs, add_history_bwd
<add> return wrap(add_history_fwd, embed)
<add>
<add>
<ide> def drop_layer(layer, factor=2.):
<ide> def drop_layer_fwd(X, drop=0.):
<ide> if drop <= 0.: | 1 |
Javascript | Javascript | simplify addinterceptor fn | b9b1aa7797df4a36c902c44e165d6cbcdcaea1c5 | <ide><path>src/ng/parse.js
<ide> function $ParseProvider() {
<ide> }
<ide>
<ide> function addInterceptor(parsedExpression, interceptorFn) {
<del> if (isFunction(interceptorFn)) {
<del> var fn = function interceptedExpression(scope, locals) {
<del> var value = parsedExpression(scope, locals);
<del> var result = interceptorFn(value, scope, locals);
<del> // we only return the interceptor's result if the
<del> // initial value is defined (for bind-once)
<del> return isDefined(value) ? result : value;
<del> };
<del> fn.$$watchDelegate = parsedExpression.$$watchDelegate;
<del> return fn;
<del> } else {
<del> return parsedExpression;
<del> }
<add> if (!interceptorFn) return parsedExpression;
<add>
<add> var fn = function interceptedExpression(scope, locals) {
<add> var value = parsedExpression(scope, locals);
<add> var result = interceptorFn(value, scope, locals);
<add> // we only return the interceptor's result if the
<add> // initial value is defined (for bind-once)
<add> return isDefined(value) ? result : value;
<add> };
<add> fn.$$watchDelegate = parsedExpression.$$watchDelegate;
<add> return fn;
<ide> }
<ide> }];
<ide> } | 1 |
Python | Python | remove python2 workarounds | 823f6819dd86e75f772a3a725996773dd6b688e2 | <ide><path>numpy/core/numerictypes.py
<ide> def issubclass_(arg1, arg2):
<ide> Examples
<ide> --------
<ide> >>> np.issubclass_(np.int32, int)
<del> False # True on Python 2.7
<add> False
<ide> >>> np.issubclass_(np.int32, float)
<ide> False
<add> >>> np.issubclass_(np.float64, float)
<add> True
<ide>
<ide> """
<ide> try:
<ide><path>numpy/core/shape_base.py
<ide> 'stack', 'vstack']
<ide>
<ide> import functools
<add>import itertools
<ide> import operator
<ide> import warnings
<ide>
<ide> def _atleast_nd(a, ndim):
<ide>
<ide>
<ide> def _accumulate(values):
<del> # Helper function because Python 2.7 doesn't have
<del> # itertools.accumulate
<del> value = 0
<del> accumulated = []
<del> for v in values:
<del> value += v
<del> accumulated.append(value)
<del> return accumulated
<add> return list(itertools.accumulate(values))
<ide>
<ide>
<ide> def _concatenate_shapes(shapes, axis):
<ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_matmul_inplace():
<ide> assert_raises(TypeError, a.__imatmul__, b)
<ide> import operator
<ide> assert_raises(TypeError, operator.imatmul, a, b)
<del> # we avoid writing the token `exec` so as not to crash python 2's
<del> # parser
<del> exec_ = getattr(builtins, "exec")
<del> assert_raises(TypeError, exec_, "a @= b", globals(), locals())
<add> assert_raises(TypeError, exec, "a @= b", globals(), locals())
<ide>
<ide> def test_matmul_axes():
<ide> a = np.arange(3*4*5).reshape(3, 4, 5)
<ide><path>numpy/core/tests/test_scalarprint.py
<ide> def test_str(self):
<ide>
<ide> def test_scalar_cutoffs(self):
<ide> # test that both the str and repr of np.float64 behaves
<del> # like python floats in python3. Note that in python2
<del> # the str has truncated digits, but we do not do this
<add> # like python floats in python3.
<ide> def check(v):
<del> # we compare str to repr, to avoid python2 truncation behavior
<add> assert_equal(str(np.float64(v)), str(v))
<ide> assert_equal(str(np.float64(v)), repr(v))
<ide> assert_equal(repr(np.float64(v)), repr(v))
<add> assert_equal(repr(np.float64(v)), str(v))
<ide>
<ide> # check we use the same number of significant digits
<ide> check(1.12345678901234567890)
<ide><path>numpy/lib/tests/test_mixins.py
<ide> def _assert_equal_type_and_value(result, expected, err_msg=None):
<ide> operator.mul,
<ide> operator.truediv,
<ide> operator.floordiv,
<del> # TODO: test div on Python 2, only
<ide> operator.mod,
<ide> divmod,
<ide> pow,
<ide><path>numpy/ma/tests/test_core.py
<ide> def test_eq_for_strings(self, dt, fill):
<ide> assert_equal(test.mask, [True, True])
<ide> assert_(test.fill_value == True)
<ide>
<del> # test = (a[0] == b) # doesn't work in Python2
<add> test = (a[0] == b)
<add> assert_equal(test.data, [False, False])
<add> assert_equal(test.mask, [True, False])
<add> assert_(test.fill_value == True)
<add>
<ide> test = (b == a[0])
<ide> assert_equal(test.data, [False, False])
<ide> assert_equal(test.mask, [True, False])
<ide> def test_ne_for_strings(self, dt, fill):
<ide> assert_equal(test.mask, [True, True])
<ide> assert_(test.fill_value == True)
<ide>
<del> # test = (a[0] != b) # doesn't work in Python2
<add> test = (a[0] != b)
<add> assert_equal(test.data, [True, True])
<add> assert_equal(test.mask, [True, False])
<add> assert_(test.fill_value == True)
<add>
<ide> test = (b != a[0])
<ide> assert_equal(test.data, [True, True])
<ide> assert_equal(test.mask, [True, False])
<ide> def test_eq_for_numeric(self, dt1, dt2, fill):
<ide> assert_equal(test.mask, [True, True])
<ide> assert_(test.fill_value == True)
<ide>
<del> # test = (a[0] == b) # doesn't work in Python2
<add> test = (a[0] == b)
<add> assert_equal(test.data, [False, False])
<add> assert_equal(test.mask, [True, False])
<add> assert_(test.fill_value == True)
<add>
<ide> test = (b == a[0])
<ide> assert_equal(test.data, [False, False])
<ide> assert_equal(test.mask, [True, False])
<ide> def test_ne_for_numeric(self, dt1, dt2, fill):
<ide> assert_equal(test.mask, [True, True])
<ide> assert_(test.fill_value == True)
<ide>
<del> # test = (a[0] != b) # doesn't work in Python2
<add> test = (a[0] != b)
<add> assert_equal(test.data, [True, True])
<add> assert_equal(test.mask, [True, False])
<add> assert_(test.fill_value == True)
<add>
<ide> test = (b != a[0])
<ide> assert_equal(test.data, [True, True])
<ide> assert_equal(test.mask, [True, False])
<ide><path>numpy/polynomial/_polybase.py
<ide> def __mul__(self, other):
<ide> return NotImplemented
<ide> return self.__class__(coef, self.domain, self.window)
<ide>
<del> def __div__(self, other):
<del> # this can be removed when python 2 support is dropped.
<del> return self.__floordiv__(other)
<del>
<ide> def __truediv__(self, other):
<ide> # there is no true divide if the rhs is not a Number, although it
<ide> # could return the first n elements of an infinite series.
<ide><path>numpy/testing/_private/parameterized.py
<ide> def detect_runner():
<ide> if module in _test_runners:
<ide> _test_runner_guess = module
<ide> break
<del> if record[1].endswith("python2.6/unittest.py"):
<del> _test_runner_guess = "unittest"
<del> break
<ide> else:
<ide> _test_runner_guess = None
<ide> return _test_runner_guess | 8 |
Javascript | Javascript | upgrade other template plugins | 25c135aa827e29c673f92bb11ff0f6b833068fc7 | <ide><path>lib/AmdMainTemplatePlugin.js
<ide> class AmdMainTemplatePlugin {
<ide> apply(compilation) {
<ide> const mainTemplate = compilation.mainTemplate;
<ide>
<del> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
<add> compilation.tapMainAndChunkTemplates("AmdMainTemplatePlugin", "renderWithEntry", (source, chunk, hash) => {
<ide> const externals = chunk.getModules().filter((m) => m.external);
<ide> const externalsDepsArray = JSON.stringify(externals.map((m) =>
<ide> typeof m.request === "object" ? m.request.amd : m.request
<ide> class AmdMainTemplatePlugin {
<ide> }
<ide> });
<ide>
<del> mainTemplate.plugin("global-hash-paths", (paths) => {
<add> mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => {
<ide> if(this.name) paths.push(this.name);
<ide> return paths;
<ide> });
<ide>
<del> mainTemplate.plugin("hash", (hash) => {
<add> mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => {
<ide> hash.update("exports amd");
<ide> hash.update(this.name);
<ide> });
<ide><path>lib/Compilation.js
<ide> class Compilation extends Tapable {
<ide> this.chunkTemplate.plugin(name, fn);
<ide> }
<ide>
<add> tapMainAndChunkTemplates(pluginName, hookName, fn) {
<add> this.mainTemplate.hooks[hookName].tap(pluginName, fn);
<add> this.chunkTemplate.hooks[hookName].tap(pluginName, fn);
<add> }
<add>
<ide> addModule(module, cacheGroup) {
<ide> const identifier = module.identifier();
<ide> if(this._modules.get(identifier)) {
<ide><path>lib/ExportPropertyMainTemplatePlugin.js
<ide> class ExportPropertyMainTemplatePlugin {
<ide>
<ide> apply(compilation) {
<ide> const mainTemplate = compilation.mainTemplate;
<del> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
<add> compilation.tapMainAndChunkTemplates("ExportPropertyMainTemplatePlugin", "renderWithEntry", (source, chunk, hash) => {
<ide> const postfix = `${accessorToObjectAccess([].concat(this.property))}`;
<ide> return new ConcatSource(source, postfix);
<ide> });
<del> mainTemplate.plugin("hash", hash => {
<add> mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => {
<ide> hash.update("export property");
<ide> hash.update(`${this.property}`);
<ide> });
<ide><path>lib/SetVarMainTemplatePlugin.js
<ide> class SetVarMainTemplatePlugin {
<ide>
<ide> apply(compilation) {
<ide> const mainTemplate = compilation.mainTemplate;
<del> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
<add> compilation.tapMainAndChunkTemplates("SetVarMainTemplatePlugin", "renderWithEntry", (source, chunk, hash) => {
<ide> const varExpression = mainTemplate.getAssetPath(this.varExpression, {
<ide> hash,
<ide> chunk
<ide> class SetVarMainTemplatePlugin {
<ide> return new ConcatSource(prefix, source);
<ide> }
<ide> });
<del> mainTemplate.plugin("global-hash-paths", (paths) => {
<add> mainTemplate.hooks.globalHashPaths.tap("SetVarMainTemplatePlugin", paths => {
<ide> if(this.varExpression) paths.push(this.varExpression);
<ide> return paths;
<ide> });
<del> mainTemplate.plugin("hash", hash => {
<add> mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => {
<ide> hash.update("set var");
<ide> hash.update(`${this.varExpression}`);
<ide> hash.update(`${this.copyObject}`);
<ide><path>lib/UmdMainTemplatePlugin.js
<ide> class UmdMainTemplatePlugin {
<ide>
<ide> apply(compilation) {
<ide> const mainTemplate = compilation.mainTemplate;
<del> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
<add> compilation.tapMainAndChunkTemplates("UmdMainTemplatePlugin", "renderWithEntry", (source, chunk, hash) => {
<ide> let externals = chunk.getModules().filter(m => m.external && (m.externalType === "umd" || m.externalType === "umd2"));
<ide> const optionalExternals = [];
<ide> let requiredExternals = [];
<ide> class UmdMainTemplatePlugin {
<ide> ) +
<ide> "})(typeof self !== 'undefined' ? self : this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
<ide> });
<del> mainTemplate.plugin("global-hash-paths", (paths) => {
<add> mainTemplate.hooks.globalHasPaths.tap("UmdMainTemplatePlugin", (paths) => {
<ide> if(this.names.root) paths = paths.concat(this.names.root);
<ide> if(this.names.amd) paths = paths.concat(this.names.amd);
<ide> if(this.names.commonjs) paths = paths.concat(this.names.commonjs);
<ide> return paths;
<ide> });
<del> mainTemplate.plugin("hash", (hash) => {
<add> mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", (hash) => {
<ide> hash.update("umd");
<ide> hash.update(`${this.names.root}`);
<ide> hash.update(`${this.names.amd}`);
<ide><path>lib/web/JsonpExportMainTemplatePlugin.js
<ide> class JsonpExportMainTemplatePlugin {
<ide> apply(compilation) {
<ide> const mainTemplate = compilation.mainTemplate;
<ide>
<del> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
<add> compilation.tapMainAndChunkTemplates("JsonpExportMainTemplatePlugin", "renderWithEntry", (source, chunk, hash) => {
<ide> const name = mainTemplate.getAssetPath(this.name || "", {
<del> hash: hash,
<del> chunk: chunk
<add> hash,
<add> chunk
<ide> });
<ide> return new ConcatSource(`${name}(`, source, ");");
<ide> });
<ide>
<del> mainTemplate.plugin("global-hash-paths", paths => {
<add> mainTemplate.hooks.globalHashPaths.tap("JsonpExportMainTemplatePlugin", paths => {
<ide> if(this.name) paths.push(this.name);
<ide> return paths;
<ide> });
<ide>
<del> mainTemplate.plugin("hash", hash => {
<add> mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => {
<ide> hash.update("jsonp export");
<ide> hash.update(`${this.name}`);
<ide> }); | 6 |
Ruby | Ruby | parenthesize the arguments with splat | 32b9cefb637741ac7158085790cda56360a229f2 | <ide><path>railties/lib/rails/engine.rb
<ide> def load_seed
<ide> end
<ide>
<ide> initializer :append_assets_path do |app|
<del> app.config.assets.paths.unshift *paths["vendor/assets"].existent
<del> app.config.assets.paths.unshift *paths["lib/assets"].existent
<del> app.config.assets.paths.unshift *paths["app/assets"].existent
<add> app.config.assets.paths.unshift(*paths["vendor/assets"].existent)
<add> app.config.assets.paths.unshift(*paths["lib/assets"].existent)
<add> app.config.assets.paths.unshift(*paths["app/assets"].existent)
<ide> end
<ide>
<ide> initializer :prepend_helpers_path do |app|
<ide><path>railties/lib/rails/generators/actions.rb
<ide> def log(*args)
<ide> say args.first.to_s unless options.quiet?
<ide> else
<ide> args << (self.behavior == :invoke ? :green : :red)
<del> say_status *args
<add> say_status(*args)
<ide> end
<ide> end
<ide> | 2 |
PHP | PHP | add test for savemany aftersavecommit | 7cd3c528c33611bbe4d758a845d87495066eb83f | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSaveManyArray()
<ide> new Entity(['name' => 'dakota']),
<ide> ];
<ide>
<del> $table = $this->getTableLocator()->get('authors');
<add> $timesCalled = 0;
<add> $listener = function ($e, $entity, $options) use (&$timesCalled) {
<add> $timesCalled++;
<add> };
<add> $table = $this->getTableLocator()
<add> ->get('authors');
<add>
<add> $table->getEventManager()
<add> ->on('Model.afterSaveCommit', $listener);
<add>
<ide> $result = $table->saveMany($entities);
<ide>
<ide> $this->assertSame($entities, $result);
<ide> $this->assertTrue(isset($result[0]->id));
<ide> foreach ($entities as $entity) {
<ide> $this->assertFalse($entity->isNew());
<ide> }
<add> $this->assertSame(2, $timesCalled);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add code explanations to algorithm | 342d8657a591ad97d87b40d4cc7ff71ccb97c43d | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities/index.md
<ide> title: Convert HTML Entities
<ide> ```
<ide> ### Code Explanation:
<ide>
<del>Explain solution here and add any relevant links
<add>* Assign **temp** to `str.split('')`, which creates an array containing each individual character in the passed in string.
<add>* Pass each character in the newly created array into a `switch()` statement.
<add>* Replace the HTML entities with their corresponding HTML entity string (i.e. `'&'` becomes `'&'` in line 51)
<add>* `temp.join('')` converts the array of characters into a string to be returned.
<ide>
<ide> #### Relevant Links
<ide>
<ide> Explain solution here and add any relevant links
<ide>
<ide> ### Code Explanation:
<ide>
<del>Explain solution here and add any relevant links
<add>* **str** is assigned to a new version of **str** that will contain the original string with all HTML entities converted
<add>* The **first parameters** in `replace()` contains a regular expression that matches all instances of each HTML entity in **str**
<add>* Replace all those instances with the corresponding HTML strings given in the **second parameter** of `replace()`
<add>* Finally, the new **str** is returned
<ide>
<ide> #### Relevant Links
<ide> | 1 |
Javascript | Javascript | add test for svg.area.radial | f12352c6f43b98c99ced54dd4f3f8a7c746c4110 | <ide><path>test/env-assert.js
<ide> assert.hslEqual = function(actual, h, s, l, message) {
<ide>
<ide> assert.pathEqual = function(actual, expected, message) {
<ide> if (!pathEqual(actual, expected)) {
<del> assert.fail(actual, expected, message || "expected {expected}, got {actual}", null, assert.pathEqual);
<add> assert.fail(formatPath(actual), formatPath(expected), message || "expected {expected}, got {actual}", null, assert.pathEqual);
<ide> }
<ide> };
<ide>
<ide> function pathEqual(a, b) {
<ide> return true;
<ide> }
<ide>
<add>var reNumber = /[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g;
<add>
<ide> function parsePath(path) {
<del> var re = /[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g, parts = [];
<del> for (var i = 0, s0 = 0, s1, m; m = re.exec(path); ++i) {
<add> var parts = [];
<add> reNumber.lastIndex = 0;
<add> for (var i = 0, s0 = 0, s1, m; m = reNumber.exec(path); ++i) {
<ide> if (m.index) {
<ide> var part = path.substring(s0, s1 = m.index);
<ide> if (!/^[, ]$/.test(part)) parts.push(part);
<ide> }
<ide> parts.push(parseFloat(m[0]));
<del> s0 = re.lastIndex;
<add> s0 = reNumber.lastIndex;
<ide> }
<ide> if (s0 < path.length) parts.push(path.substring(s0));
<ide> return parts;
<ide> }
<add>
<add>function formatPath(path) {
<add> return path.replace(reNumber, function(s) {
<add> return Math.abs((s = +s) - Math.floor(s)) < 1e-6 ? Math.floor(s) : s.toFixed(6);
<add> });
<add>}
<ide><path>test/svg/area-radial-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("d3.svg.area.radial");
<add>
<add>suite.addBatch({
<add> "area.radial": {
<add> topic: function() {
<add> return d3.svg.area.radial;
<add> },
<add>
<add> "radius is an alias for setting innerRadius and outerRadius": function(area) {
<add> var a = area().radius(f);
<add> function f() {}
<add> assert.equal(a.radius(), f);
<add> assert.equal(a.innerRadius(), f);
<add> assert.equal(a.outerRadius(), f);
<add> },
<add> "radius is an alias for getting outerRadius": function(area) {
<add> var a = area().outerRadius(f);
<add> function f() {}
<add> assert.equal(a.radius(), f);
<add> },
<add>
<add> "angle is an alias for setting startAngle and endAngle": function(area) {
<add> var a = area().angle(f);
<add> function f() {}
<add> assert.equal(a.angle(), f);
<add> assert.equal(a.startAngle(), f);
<add> assert.equal(a.endAngle(), f);
<add> },
<add> "angle is an alias for getting endAngle": function(area) {
<add> var a = area().endAngle(f);
<add> function f() {}
<add> assert.equal(a.angle(), f);
<add> },
<add>
<add> "innerRadius defaults to a function accessor": function(area) {
<add> var a = area();
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.typeOf(a.innerRadius(), "function");
<add> },
<add> "innerRadius can be defined as a constant": function(area) {
<add> var a = area().innerRadius(30);
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-30L0,-30L0,-30L0,-30Z");
<add> assert.equal(a.innerRadius(), 30);
<add> },
<add> "innerRadius can be defined as a function": function(area) {
<add> var a = area().innerRadius(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return 30; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-30L0,-30L0,-30L0,-30Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add>
<add> "outerRadius defaults to a function accessor": function(area) {
<add> var a = area();
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.typeOf(a.outerRadius(), "function");
<add> },
<add> "outerRadius can be defined as a constant": function(area) {
<add> var a = area().outerRadius(30);
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-30L25.244130,-16.209069L27.278923,12.484405L4.233600,29.699775L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.equal(a.outerRadius(), 30);
<add> },
<add> "outerRadius can be defined as a function": function(area) {
<add> var a = area().outerRadius(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return 30; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-30L25.244130,-16.209069L27.278923,12.484405L4.233600,29.699775L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add>
<add> "startAngle defaults to zero": function(area) {
<add> var a = area();
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.equal(a.startAngle(), 0);
<add> },
<add> "startAngle can be defined as a constant": function(area) {
<add> var a = area().startAngle(Math.PI / 2);
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L10,0L20,0L20,0L10,0Z");
<add> assert.equal(a.startAngle(), Math.PI / 2);
<add> },
<add> "startAngle can be defined as a function": function(area) {
<add> var a = area().startAngle(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return Math.PI / 2; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L10,0L20,0L20,0L10,0Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add>
<add> "endAngle defaults to a function accessor": function(area) {
<add> var a = area();
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-10L16.829420,-10.806046L18.185949,8.322937L1.411200,9.899925L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.typeOf(a.endAngle(), "function");
<add> },
<add> "endAngle can be defined as a constant": function(area) {
<add> var a = area().endAngle(Math.PI / 2);
<add> assert.pathEqual(a([[10, 0], [20, 1], [20, 2], [10, 3]]), "M10,0L20,0L20,0L10,0L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.equal(a.endAngle(), Math.PI / 2);
<add> },
<add> "endAngle can be defined as a function": function(area) {
<add> var a = area().endAngle(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return Math.PI / 2; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M10,0L20,0L20,0L10,0L0,-10L0,-20L0,-20L0,-10Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add>
<add> "if innerRadius === outerRadius, radius is only evaluated once per point": function(area) {
<add> var a = area().radius(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return 30; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M0,-30L25.244130,-16.209069L27.278923,12.484405L4.233600,29.699775L0,-30L0,-30L0,-30L0,-30Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add> "if startAngle === endAngle, angle is only evaluated once per point": function(area) {
<add> var a = area().angle(f), t = {}, dd = [], ii = [], tt = [];
<add> function f(d, i) { dd.push(d); ii.push(i); tt.push(this); return Math.PI / 2; }
<add> assert.pathEqual(a.call(t, [[10, 0], [20, 1], [20, 2], [10, 3]]), "M10,0L20,0L20,0L10,0L10,0L20,0L20,0L10,0Z");
<add> assert.deepEqual(dd, [[10, 0], [20, 1], [20, 2], [10, 3]], "expected data, got {actual}");
<add> assert.deepEqual(ii, [0, 1, 2, 3], "expected index, got {actual}");
<add> assert.deepEqual(tt, [t, t, t, t], "expected this, got {actual}");
<add> },
<add>
<add> "interpolate defaults to linear": function(area) {
<add> assert.equal(area().interpolate(), "linear");
<add> },
<add> "interpolate can be defined as a constant": function(area) {
<add> var a = area().interpolate("step-before");
<add> assert.pathEqual(a([[0, 0], [1, 1]]), "M0,0V-0.540302H0.841471L0,-1V0H0Z");
<add> assert.equal(a.interpolate(), "step-before");
<add> },
<add>
<add> "tension defaults to .7": function(area) {
<add> assert.equal(area().tension(), .7);
<add> },
<add> "tension can be specified as a constant": function(area) {
<add> var a = area().tension(.5);
<add> assert.equal(a.tension(), .5);
<add> },
<add>
<add> "returns null if input points array is empty": function(area) {
<add> assert.isNull(area()([]));
<add> },
<add>
<add> "interpolate(linear)": {
<add> "supports linear interpolation": testInterpolation("linear")
<add> },
<add>
<add> "interpolate(step)": {
<add> "supports step-before interpolation": testInterpolation("step-before"),
<add> "supports step-after interpolation": testInterpolation("step-after")
<add> },
<add>
<add> "interpolate(basis)": {
<add> "supports basis interpolation": testInterpolation("basis"),
<add> "supports basis-open interpolation": testInterpolation("basis-open")
<add> },
<add>
<add> "interpolate(cardinal)": {
<add> "supports cardinal interpolation": testInterpolation("cardinal"),
<add> "supports cardinal-open interpolation": testInterpolation("cardinal-open")
<add> },
<add>
<add> "interpolate(monotone)": {
<add> "supports monotone interpolation": testInterpolation("monotone")
<add> }
<add> }
<add>});
<add>
<add>// A radial area is just a transformation of a Cartesian line.
<add>function testInterpolation(interpolate) {
<add> var data = [[10, 0], [20, 1], [20, 2], [10, 3]];
<add>
<add> var radial = d3.svg.area.radial()
<add> .innerRadius(function(d) { return d[0]; })
<add> .outerRadius(function(d) { return d[0] * 2; })
<add> .angle(function(d) { return d[1]; });
<add>
<add> var cartesian = d3.svg.area()
<add> .x0(function(d) { return d[0] * Math.cos(d[1] - Math.PI / 2); })
<add> .x1(function(d) { return 2 * d[0] * Math.cos(d[1] - Math.PI / 2); })
<add> .y0(function(d) { return d[0] * Math.sin(d[1] - Math.PI / 2); })
<add> .y1(function(d) { return 2 * d[0] * Math.sin(d[1] - Math.PI / 2); });
<add>
<add> return function() {
<add> assert.pathEqual(radial.interpolate(interpolate)(data), cartesian.interpolate(interpolate)(data));
<add> };
<add>}
<add>
<add>suite.export(module);
<ide><path>test/svg/area-test.js
<ide> suite.addBatch({
<ide> assert.equal(area().interpolate(), "linear");
<ide> },
<ide> "interpolate can be defined as a constant": function(area) {
<del> var l = area().interpolate("step-before");
<del> assert.pathEqual(l([[0, 0], [1, 1]]), "M0,0V1H1L1,0V0H0Z");
<del> assert.equal(l.interpolate(), "step-before");
<add> var a = area().interpolate("step-before");
<add> assert.pathEqual(a([[0, 0], [1, 1]]), "M0,0V1H1L1,0V0H0Z");
<add> assert.equal(a.interpolate(), "step-before");
<ide> },
<ide>
<ide> "tension defaults to .7": function(area) {
<ide> assert.equal(area().tension(), .7);
<ide> },
<ide> "tension can be specified as a constant": function(area) {
<del> var l = area().tension(.5);
<del> assert.equal(l.tension(), .5);
<add> var a = area().tension(.5);
<add> assert.equal(a.tension(), .5);
<ide> },
<ide>
<ide> "returns null if input points array is empty": function(area) {
<ide><path>test/svg/line-radial-test.js
<ide> suite.addBatch({
<ide> function testInterpolation(interpolate) {
<ide> var data = [[10, 0], [20, 1], [20, 2], [10, 3]];
<ide>
<add> var radial = d3.svg.line.radial();
<add>
<ide> var cartesian = d3.svg.line()
<ide> .x(function(d) { return d[0] * Math.cos(d[1] - Math.PI / 2); })
<ide> .y(function(d) { return d[0] * Math.sin(d[1] - Math.PI / 2); });
<ide>
<del> return function(line) {
<del> assert.pathEqual(line().interpolate(interpolate)(data), cartesian.interpolate(interpolate)(data));
<add> return function() {
<add> assert.pathEqual(radial.interpolate(interpolate)(data), cartesian.interpolate(interpolate)(data));
<ide> };
<ide> }
<ide> | 4 |
Text | Text | add option for developer tools inside browsers | b925911f2e7d02cc0fab3bf0709f6df57b0ad4e0 | <ide><path>guide/portuguese/developer-tools/index.md
<ide> Alguns exemplos dessas ferramentas:
<ide> * Sistemas de controle de versão
<ide> * Ferramentas DevOps
<ide> * Construir ferramentas
<del>* Gerenciadores de pacotes
<ide>\ No newline at end of file
<add>* Gerenciadores de pacotes
<add>* Ferramentas de desenvolvedor em navegadores | 1 |
Javascript | Javascript | shim two private apis on treesitterlanguagemode | b51f13cc90df049382feb6b8e671854081f46261 | <ide><path>src/tree-sitter-language-mode.js
<ide> const {Document} = require('tree-sitter')
<del>const {Point, Range, Emitter} = require('atom')
<add>const {Point, Range} = require('text-buffer')
<add>const {Emitter, Disposable} = require('event-kit')
<ide> const ScopeDescriptor = require('./scope-descriptor')
<ide> const TokenizedLine = require('./tokenized-line')
<ide> const TextMateLanguageMode = require('./text-mate-language-mode')
<ide> class TreeSitterLanguageMode {
<ide> if (node) return new Range(node.startPosition, node.endPosition)
<ide> }
<ide>
<add> bufferRangeForScopeAtPosition (position) {
<add> return this.getRangeForSyntaxNodeContainingRange(new Range(position, position))
<add> }
<add>
<ide> /*
<ide> Section - Backward compatibility shims
<ide> */
<ide>
<add> onDidTokenize (callback) { return new Disposable(() => {}) }
<add>
<ide> tokenizedLineForRow (row) {
<ide> return new TokenizedLine({
<ide> openScopes: [], | 1 |
Text | Text | fix typo in maintaining-openssl guide | be2f36a51a3c11b2001bd74e03a77cf3ee920aa0 | <ide><path>doc/guides/maintaining-openssl.md
<ide> The commit message can be (with the openssl version set to the relevant value):
<ide> deps: update archs files for OpenSSL-1.1.0
<ide>
<ide> After an OpenSSL source update, all the config files need to be regenerated and
<del> comitted by:
<add> committed by:
<ide> $ cd deps/openssl/config
<ide> $ make
<ide> $ git add deps/openssl/config/archs | 1 |
PHP | PHP | use new method | 1505f7a123354bf62db700e5646ea62b72d9fd62 | <ide><path>src/ORM/ResultSet.php
<ide> protected function _getTypes($table, $fields)
<ide> {
<ide> $types = [];
<ide> $schema = $table->getSchema();
<del> $map = array_keys(Type::map() + ['string' => 1, 'text' => 1, 'boolean' => 1]);
<add> $map = array_keys(Type::getMap() + ['string' => 1, 'text' => 1, 'boolean' => 1]);
<ide> $typeMap = array_combine(
<ide> $map,
<ide> array_map(['Cake\Database\Type', 'build'], $map) | 1 |
Ruby | Ruby | skip an audit for mongodb | ebcf8be7892568f2cfba9880d2995cc0499eb092 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_line(line)
<ide> problem "No double 'without': Use `build.without? '#{$1}'` to check for \"--without-#{$1}\""
<ide> end
<ide>
<del> if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/
<del> problem "Use build instead of ARGV to check options"
<add> unless f.name == 'mongodb' # Mongo writes out a Ruby script that uses ARGV
<add> if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/
<add> problem "Use build instead of ARGV to check options"
<add> end
<ide> end
<ide>
<ide> if line =~ /def options/ | 1 |
Javascript | Javascript | handle non-string return value in .inspect() | e85927119cd76dfa6541beb7954196c56d98a776 | <ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> value.inspect !== exports.inspect &&
<ide> // Also filter out any prototype objects using the circular check.
<ide> !(value.constructor && value.constructor.prototype === value)) {
<del> return value.inspect(recurseTimes);
<add> return String(value.inspect(recurseTimes));
<ide> }
<ide>
<ide> // Primitive types cannot have properties
<ide><path>test/simple/test-util-inspect.js
<ide> assert.doesNotThrow(function() {
<ide> util.inspect(r);
<ide> });
<ide>
<add>// bug with user-supplied inspect function returns non-string
<add>assert.doesNotThrow(function() {
<add> util.inspect([{
<add> inspect: function() { return 123; }
<add> }]);
<add>});
<add>
<ide> // GH-2225
<ide> var x = { inspect: util.inspect };
<ide> assert.ok(util.inspect(x).indexOf('inspect') != -1); | 2 |
Python | Python | squeeze corner case | 1be850b0782a1dcbb3da22fb9d5c74c3ce367936 | <ide><path>numpy/core/fromnumeric.py
<ide> def squeeze(a, axis=None):
<ide> try:
<ide> squeeze = a.squeeze
<ide> except AttributeError:
<del> return _wrapit(a, 'squeeze')
<add> return _wrapit(a, 'squeeze', axis=axis)
<ide> if axis is None:
<ide> return squeeze()
<ide> else:
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_size(self):
<ide>
<ide> def test_squeeze(self):
<ide> A = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]
<del> assert_(np.squeeze(A).shape == (3, 3))
<add> assert_equal(np.squeeze(A).shape, (3, 3))
<add> assert_equal(np.squeeze(np.zeros((1, 3, 1))).shape, (3,))
<add> assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=0).shape, (3, 1))
<add> assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=-1).shape, (1, 3))
<add> assert_equal(np.squeeze(np.zeros((1, 3, 1)), axis=2).shape, (1, 3))
<add> assert_equal(np.squeeze([np.zeros((3, 1))]).shape, (3,))
<add> assert_equal(np.squeeze([np.zeros((3, 1))], axis=0).shape, (3, 1))
<add> assert_equal(np.squeeze([np.zeros((3, 1))], axis=2).shape, (1, 3))
<add> assert_equal(np.squeeze([np.zeros((3, 1))], axis=-1).shape, (1, 3))
<ide>
<ide> def test_std(self):
<ide> A = [[1, 2, 3], [4, 5, 6]] | 2 |
Text | Text | update docs about supported native animation props | 280ed810b0ee645df0c82c58ce5d0076f5b4dc5a | <ide><path>docs/Animations.md
<ide> You can also take a look at the [source code](https://github.com/facebook/react-
<ide>
<ide> Not everything you can do with `Animated` is currently supported by the native driver.
<ide> The main limitation is that you can only animate non-layout properties:
<del>things like `transform`, `opacity` and `backgroundColor` will work, but flexbox and position properties will not.
<add>things like `transform` and `opacity` will work, but flexbox and position properties will not.
<ide> When using `Animated.event`, it will only work with direct events and not bubbling events.
<ide> This means it does not work with `PanResponder` but does work with things like `ScrollView#onScroll`.
<ide>
<ide> option](http://facebook.github.io/react-native/blog/2017/02/14/using-native-driv
<ide> You may also want to defer any computationally intensive work until after
<ide> animations are complete, using the
<ide> [InteractionManager](docs/interactionmanager.html). You can monitor the
<del>frame rate by using the In-App Developer Menu "FPS Monitor" tool.
<ide>\ No newline at end of file
<add>frame rate by using the In-App Developer Menu "FPS Monitor" tool. | 1 |
PHP | PHP | fix return type in docblock | 19cfe40fd1d72bb554274fa1cfd8620a3dde4554 | <ide><path>lib/Cake/Model/Datasource/DataSource.php
<ide> public function update(Model $model, $fields = null, $values = null, $conditions
<ide> *
<ide> * @param Model $model The model class having record(s) deleted
<ide> * @param mixed $conditions The conditions to use for deleting.
<del> * @return void
<add> * @return boolean Success
<ide> */
<ide> public function delete(Model $model, $id = null) {
<ide> return false; | 1 |
Text | Text | remove markdown syntax from code block | 154dee5937cdc022f951da394e75182678caf7e0 | <ide><path>docs/recipes/UsingImmutableJS.md
<ide> import { Iterable } from 'immutable';
<ide> export const toJS = (WrappedComponent) =>
<ide> (wrappedComponentProps) => {
<ide> const KEY = 0;
<del> const **VALUE = 1;
<add> const VALUE = 1;
<ide>
<ide> const propsJS = Object.entries(wrappedComponentProps)
<ide> .reduce((newProps, wrappedComponentProp) => { | 1 |
Python | Python | add more filtering options for ti's in the ui | bdaa7d5a9c637258deb964de85e3ee0dfe20af8c | <ide><path>airflow/www/views.py
<ide> class TaskInstanceModelView(AirflowPrivilegeVerifierModelView):
<ide> 'task_id',
<ide> 'run_id',
<ide> 'execution_date',
<del> 'hostname',
<del> 'queue',
<del> 'pool',
<ide> 'operator',
<ide> 'start_date',
<ide> 'end_date',
<add> 'hostname',
<add> 'priority_weight',
<add> 'queue',
<ide> 'queued_dttm',
<add> 'try_number',
<add> 'pool',
<add> 'queued_by_job_id',
<ide> ]
<ide>
<ide> edit_columns = [ | 1 |
Mixed | Python | fix factorial issues | c0acfd46cbd6b29847d9e0e226431ab6004b8e9b | <ide><path>DIRECTORY.md
<ide> * [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
<ide> * [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
<ide> * [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
<add> * [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
<ide> * [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
<ide> * [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
<ide> * [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
<ide> * [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
<ide> * [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
<ide> * [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
<del> * [Factorial Python](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.py)
<ide> * [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
<ide> * [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
<ide> * [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
<ide>
<ide> ## Other
<ide> * [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
<add> * [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
<ide> * [Date To Weekday](https://github.com/TheAlgorithms/Python/blob/master/other/date_to_weekday.py)
<ide> * [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
<ide> * [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
<ide> * [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
<ide> * [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
<ide> * [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
<add> * [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
<ide> * [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
<ide> * [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
<ide> * [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
<ide><path>maths/factorial_iterative.py
<del># factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
<add>"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
<add>"""
<ide>
<ide>
<del>def factorial(n: int) -> int:
<add>def factorial(number: int) -> int:
<ide> """
<add> Calculate the factorial of specified number (n!).
<add>
<ide> >>> import math
<ide> >>> all(factorial(i) == math.factorial(i) for i in range(20))
<ide> True
<ide> def factorial(n: int) -> int:
<ide> Traceback (most recent call last):
<ide> ...
<ide> ValueError: factorial() not defined for negative values
<add> >>> factorial(1)
<add> 1
<add> >>> factorial(6)
<add> 720
<add> >>> factorial(0)
<add> 1
<ide> """
<del> if n != int(n):
<add> if number != int(number):
<ide> raise ValueError("factorial() only accepts integral values")
<del> if n < 0:
<add> if number < 0:
<ide> raise ValueError("factorial() not defined for negative values")
<ide> value = 1
<del> for i in range(1, n + 1):
<add> for i in range(1, number + 1):
<ide> value *= i
<ide> return value
<ide>
<ide>
<ide> if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod()
<add>
<ide> n = int(input("Enter a positive integer: ").strip() or 0)
<ide> print(f"factorial{n} is {factorial(n)}")
<ide><path>maths/factorial_python.py
<del>def factorial(input_number: int) -> int:
<del> """
<del> Calculate the factorial of specified number
<del>
<del> >>> factorial(1)
<del> 1
<del> >>> factorial(6)
<del> 720
<del> >>> factorial(0)
<del> 1
<del> >>> factorial(-1)
<del> Traceback (most recent call last):
<del> ...
<del> ValueError: factorial() not defined for negative values
<del> >>> factorial(0.1)
<del> Traceback (most recent call last):
<del> ...
<del> ValueError: factorial() only accepts integral values
<del> """
<del>
<del> if input_number < 0:
<del> raise ValueError("factorial() not defined for negative values")
<del> if not isinstance(input_number, int):
<del> raise ValueError("factorial() only accepts integral values")
<del> result = 1
<del> for i in range(1, input_number):
<del> result = result * (i + 1)
<del> return result
<del>
<del>
<del>if __name__ == "__main__":
<del> import doctest
<del>
<del> doctest.testmod()
<ide><path>project_euler/problem_015/sol1.py
<ide> def solution(n: int = 20) -> int:
<ide> """
<ide> n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
<ide> # 2, 3,...
<del> k = n / 2
<add> k = n // 2
<ide>
<ide> return int(factorial(n) / (factorial(k) * factorial(n - k)))
<ide> | 4 |
PHP | PHP | fix a risky test | 7c53e1a2f0a8e73ddca5504e0c659121843f369e | <ide><path>tests/TestCase/Network/ResponseTest.php
<ide> public function testFileWithUnknownFileNoDownload()
<ide> */
<ide> public function testGetFile()
<ide> {
<del> ob_start();
<ide> $response = new Response();
<ide> $this->assertNull($response->getFile(), 'No file to get');
<ide> | 1 |
Ruby | Ruby | make mocha setup explcitly minitest-specific | 30735ab7261db54209a7dca3410236abfbc997e0 | <ide><path>actioncable/test/test_helper.rb
<ide> require "active_support/testing/autorun"
<ide>
<ide> require "puma"
<del>require "mocha/setup"
<add>require "mocha/minitest"
<ide> require "rack/mock"
<ide>
<ide> begin
<ide><path>activerecord/test/cases/helper.rb
<ide> def in_time_zone(zone)
<ide> end
<ide> end
<ide>
<del>require "mocha/setup" # FIXME: stop using mocha
<add>require "mocha/minitest" # FIXME: stop using mocha | 2 |
Python | Python | set version to 2.0.13 | 9cfab5933a098939033c77fe8b969a3692872f0e | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy'
<del>__version__ = '2.0.13.dev4'
<add>__version__ = '2.0.13'
<ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Explosion AI'
<ide> __email__ = 'contact@explosion.ai'
<ide> __license__ = 'MIT'
<del>__release__ = False
<add>__release__ = True
<ide>
<ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
<ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json' | 1 |
PHP | PHP | use env superglobal | 071a05bd76ee7eca0ea15ea107b49bcbad9af925 | <ide><path>bootstrap/app.php
<ide> */
<ide>
<ide> $app = new Illuminate\Foundation\Application(
<del> dirname(__DIR__)
<add> $_ENV['LARAVEL_BASE_PATH'] ?? dirname(__DIR__)
<ide> );
<ide>
<ide> /* | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.