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 | move event things around | 125d1a19a211c51d5ee52ec0c1cc1f538eb44d5c | <ide><path>packages/react-dom/src/client/ReactDOMComponent.js
<ide> import {
<ide> listenToReactEvent,
<ide> mediaEventTypes,
<ide> listenToNonDelegatedEvent,
<del>} from '../events/DOMModernPluginEventSystem';
<add>} from '../events/DOMPluginEventSystem';
<ide> import {getEventListenerMap} from './ReactDOMComponentTree';
<ide> import {
<ide> TOP_LOAD,
<ide><path>packages/react-dom/src/client/ReactDOMEventHandle.js
<ide> import {ELEMENT_NODE, COMMENT_NODE} from '../shared/HTMLNodeType';
<ide> import {
<ide> listenToNativeEvent,
<ide> addEventTypeToDispatchConfig,
<del>} from '../events/DOMModernPluginEventSystem';
<add>} from '../events/DOMPluginEventSystem';
<ide>
<ide> import {HostRoot, HostPortal} from 'react-reconciler/src/ReactWorkTags';
<ide> import {
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> import {
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags';
<ide> import {TOP_BEFORE_BLUR, TOP_AFTER_BLUR} from '../events/DOMTopLevelEventTypes';
<del>import {listenToReactEvent} from '../events/DOMModernPluginEventSystem';
<add>import {listenToReactEvent} from '../events/DOMPluginEventSystem';
<ide>
<ide> export type Type = string;
<ide> export type Props = {
<add><path>packages/react-dom/src/events/DOMPluginEventSystem.js
<del><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import {
<ide> } from './EventListener';
<ide> import {removeTrappedEventListener} from './DeprecatedDOMEventResponderSystem';
<ide> import {topLevelEventsToReactNames} from './DOMEventProperties';
<del>import * as ModernBeforeInputEventPlugin from './plugins/ModernBeforeInputEventPlugin';
<del>import * as ModernChangeEventPlugin from './plugins/ModernChangeEventPlugin';
<del>import * as ModernEnterLeaveEventPlugin from './plugins/ModernEnterLeaveEventPlugin';
<del>import * as ModernSelectEventPlugin from './plugins/ModernSelectEventPlugin';
<del>import * as ModernSimpleEventPlugin from './plugins/ModernSimpleEventPlugin';
<add>import * as BeforeInputEventPlugin from './plugins/BeforeInputEventPlugin';
<add>import * as ChangeEventPlugin from './plugins/ChangeEventPlugin';
<add>import * as EnterLeaveEventPlugin from './plugins/EnterLeaveEventPlugin';
<add>import * as SelectEventPlugin from './plugins/SelectEventPlugin';
<add>import * as SimpleEventPlugin from './plugins/SimpleEventPlugin';
<ide>
<ide> type DispatchListener = {|
<ide> instance: null | Fiber,
<ide> type DispatchEntry = {|
<ide> export type DispatchQueue = Array<DispatchEntry>;
<ide>
<ide> // TODO: remove top-level side effect.
<del>ModernSimpleEventPlugin.registerEvents();
<del>ModernEnterLeaveEventPlugin.registerEvents();
<del>ModernChangeEventPlugin.registerEvents();
<del>ModernSelectEventPlugin.registerEvents();
<del>ModernBeforeInputEventPlugin.registerEvents();
<add>SimpleEventPlugin.registerEvents();
<add>EnterLeaveEventPlugin.registerEvents();
<add>ChangeEventPlugin.registerEvents();
<add>SelectEventPlugin.registerEvents();
<add>BeforeInputEventPlugin.registerEvents();
<ide>
<ide> function extractEvents(
<ide> dispatchQueue: DispatchQueue,
<ide> function extractEvents(
<ide> // should probably be inlined somewhere and have its logic
<ide> // be core the to event system. This would potentially allow
<ide> // us to ship builds of React without the polyfilled plugins below.
<del> ModernSimpleEventPlugin.extractEvents(
<add> SimpleEventPlugin.extractEvents(
<ide> dispatchQueue,
<ide> topLevelType,
<ide> targetInst,
<ide> function extractEvents(
<ide> // that might cause other unknown side-effects that we
<ide> // can't forsee right now.
<ide> if (shouldProcessPolyfillPlugins) {
<del> ModernEnterLeaveEventPlugin.extractEvents(
<add> EnterLeaveEventPlugin.extractEvents(
<ide> dispatchQueue,
<ide> topLevelType,
<ide> targetInst,
<ide> function extractEvents(
<ide> eventSystemFlags,
<ide> targetContainer,
<ide> );
<del> ModernChangeEventPlugin.extractEvents(
<add> ChangeEventPlugin.extractEvents(
<ide> dispatchQueue,
<ide> topLevelType,
<ide> targetInst,
<ide> function extractEvents(
<ide> eventSystemFlags,
<ide> targetContainer,
<ide> );
<del> ModernSelectEventPlugin.extractEvents(
<add> SelectEventPlugin.extractEvents(
<ide> dispatchQueue,
<ide> topLevelType,
<ide> targetInst,
<ide> function extractEvents(
<ide> eventSystemFlags,
<ide> targetContainer,
<ide> );
<del> ModernBeforeInputEventPlugin.extractEvents(
<add> BeforeInputEventPlugin.extractEvents(
<ide> dispatchQueue,
<ide> topLevelType,
<ide> targetInst,
<ide> export function processDispatchQueue(
<ide> for (let i = 0; i < dispatchQueue.length; i++) {
<ide> const {event, listeners} = dispatchQueue[i];
<ide> processDispatchQueueItemsInOrder(event, listeners, inCapturePhase);
<del> // Modern event system doesn't use pooling.
<add> // event system doesn't use pooling.
<ide> }
<ide> // This would be a good time to rethrow if any of the event handlers threw.
<ide> rethrowCaughtError();
<ide> export function accumulateSinglePhaseListeners(
<ide> }
<ide>
<ide> // We should only use this function for:
<del>// - ModernBeforeInputEventPlugin
<del>// - ModernChangeEventPlugin
<del>// - ModernSelectEventPlugin
<add>// - BeforeInputEventPlugin
<add>// - ChangeEventPlugin
<add>// - SelectEventPlugin
<ide> // This is because we only process these plugins
<ide> // in the bubble phase, so we need to accumulate two
<ide> // phase event listeners (via emulation).
<ide> function accumulateEnterLeaveListenersForEvent(
<ide> }
<ide>
<ide> // We should only use this function for:
<del>// - ModernEnterLeaveEventPlugin
<add>// - EnterLeaveEventPlugin
<ide> // This is because we only process this plugin
<ide> // in the bubble phase, so we need to accumulate two
<ide> // phase event listeners.
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> import {
<ide> DiscreteEvent,
<ide> } from 'shared/ReactTypes';
<ide> import {getEventPriorityForPluginSystem} from './DOMEventProperties';
<del>import {dispatchEventForPluginEventSystem} from './DOMModernPluginEventSystem';
<add>import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem';
<ide> import {
<ide> flushDiscreteUpdatesIfNeeded,
<ide> discreteUpdates,
<ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js
<ide> import {
<ide> TOP_FOCUS_OUT,
<ide> } from './DOMTopLevelEventTypes';
<ide> import {IS_REPLAYED} from './EventSystemFlags';
<del>import {listenToNativeEvent} from './DOMModernPluginEventSystem';
<add>import {listenToNativeEvent} from './DOMPluginEventSystem';
<ide> import {addResponderEventSystemEvent} from './DeprecatedDOMEventResponderSystem';
<ide>
<ide> type QueuedReplayableEvent = {|
<ide><path>packages/react-dom/src/events/SyntheticAnimationEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>/**
<del> * @interface Event
<del> * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
<del> * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
<del> */
<del>const SyntheticAnimationEvent = SyntheticEvent.extend({
<del> animationName: null,
<del> elapsedTime: null,
<del> pseudoElement: null,
<del>});
<del>
<del>export default SyntheticAnimationEvent;
<ide><path>packages/react-dom/src/events/SyntheticClipboardEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>/**
<del> * @interface Event
<del> * @see http://www.w3.org/TR/clipboard-apis/
<del> */
<del>const SyntheticClipboardEvent = SyntheticEvent.extend({
<del> clipboardData: function(event) {
<del> return 'clipboardData' in event
<del> ? event.clipboardData
<del> : window.clipboardData;
<del> },
<del>});
<del>
<del>export default SyntheticClipboardEvent;
<ide><path>packages/react-dom/src/events/SyntheticCompositionEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>/**
<del> * @interface Event
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
<del> */
<del>const SyntheticCompositionEvent = SyntheticEvent.extend({
<del> data: null,
<del>});
<del>
<del>export default SyntheticCompositionEvent;
<ide><path>packages/react-dom/src/events/SyntheticDragEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticMouseEvent from './SyntheticMouseEvent';
<del>
<del>/**
<del> * @interface DragEvent
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<del> */
<del>const SyntheticDragEvent = SyntheticMouseEvent.extend({
<del> dataTransfer: null,
<del>});
<del>
<del>export default SyntheticDragEvent;
<ide><path>packages/react-dom/src/events/SyntheticEvent.js
<ide>
<ide> /* eslint valid-typeof: 0 */
<ide>
<add>import getEventCharCode from './getEventCharCode';
<add>
<ide> /**
<ide> * @interface Event
<ide> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<ide> function functionThatReturnsFalse() {
<ide> * normalizing browser quirks. Subclasses do not necessarily have to implement a
<ide> * DOM interface; custom application-specific events can also subclass this.
<ide> */
<del>function SyntheticEvent(reactName, targetInst, nativeEvent, nativeEventTarget) {
<add>export function SyntheticEvent(
<add> reactName,
<add> targetInst,
<add> nativeEvent,
<add> nativeEventTarget,
<add>) {
<ide> this._reactName = reactName;
<ide> this._targetInst = targetInst;
<ide> this.nativeEvent = nativeEvent;
<ide> SyntheticEvent.extend = function(Interface) {
<ide> return Class;
<ide> };
<ide>
<del>export default SyntheticEvent;
<add>export const SyntheticUIEvent = SyntheticEvent.extend({
<add> view: null,
<add> detail: null,
<add>});
<add>
<add>let previousScreenX = 0;
<add>let previousScreenY = 0;
<add>// Use flags to signal movementX/Y has already been set
<add>let isMovementXSet = false;
<add>let isMovementYSet = false;
<add>
<add>/**
<add> * @interface MouseEvent
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<add> */
<add>export const SyntheticMouseEvent = SyntheticUIEvent.extend({
<add> screenX: null,
<add> screenY: null,
<add> clientX: null,
<add> clientY: null,
<add> pageX: null,
<add> pageY: null,
<add> ctrlKey: null,
<add> shiftKey: null,
<add> altKey: null,
<add> metaKey: null,
<add> getModifierState: getEventModifierState,
<add> button: null,
<add> buttons: null,
<add> relatedTarget: function(event) {
<add> return (
<add> event.relatedTarget ||
<add> (event.fromElement === event.srcElement
<add> ? event.toElement
<add> : event.fromElement)
<add> );
<add> },
<add> movementX: function(event) {
<add> if ('movementX' in event) {
<add> return event.movementX;
<add> }
<add>
<add> const screenX = previousScreenX;
<add> previousScreenX = event.screenX;
<add>
<add> if (!isMovementXSet) {
<add> isMovementXSet = true;
<add> return 0;
<add> }
<add>
<add> return event.type === 'mousemove' ? event.screenX - screenX : 0;
<add> },
<add> movementY: function(event) {
<add> if ('movementY' in event) {
<add> return event.movementY;
<add> }
<add>
<add> const screenY = previousScreenY;
<add> previousScreenY = event.screenY;
<add>
<add> if (!isMovementYSet) {
<add> isMovementYSet = true;
<add> return 0;
<add> }
<add>
<add> return event.type === 'mousemove' ? event.screenY - screenY : 0;
<add> },
<add>});
<add>
<add>/**
<add> * @interface DragEvent
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<add> */
<add>export const SyntheticDragEvent = SyntheticMouseEvent.extend({
<add> dataTransfer: null,
<add>});
<add>
<add>/**
<add> * @interface FocusEvent
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<add> */
<add>export const SyntheticFocusEvent = SyntheticUIEvent.extend({
<add> relatedTarget: null,
<add>});
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
<add> * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
<add> */
<add>export const SyntheticAnimationEvent = SyntheticEvent.extend({
<add> animationName: null,
<add> elapsedTime: null,
<add> pseudoElement: null,
<add>});
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/clipboard-apis/
<add> */
<add>export const SyntheticClipboardEvent = SyntheticEvent.extend({
<add> clipboardData: function(event) {
<add> return 'clipboardData' in event
<add> ? event.clipboardData
<add> : window.clipboardData;
<add> },
<add>});
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
<add> */
<add>export const SyntheticCompositionEvent = SyntheticEvent.extend({
<add> data: null,
<add>});
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
<add> * /#events-inputevents
<add> */
<add>export const SyntheticInputEvent = SyntheticEvent.extend({
<add> data: null,
<add>});
<add>
<add>/**
<add> * Normalization of deprecated HTML5 `key` values
<add> * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
<add> */
<add>const normalizeKey = {
<add> Esc: 'Escape',
<add> Spacebar: ' ',
<add> Left: 'ArrowLeft',
<add> Up: 'ArrowUp',
<add> Right: 'ArrowRight',
<add> Down: 'ArrowDown',
<add> Del: 'Delete',
<add> Win: 'OS',
<add> Menu: 'ContextMenu',
<add> Apps: 'ContextMenu',
<add> Scroll: 'ScrollLock',
<add> MozPrintableKey: 'Unidentified',
<add>};
<add>
<add>/**
<add> * Translation from legacy `keyCode` to HTML5 `key`
<add> * Only special keys supported, all others depend on keyboard layout or browser
<add> * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
<add> */
<add>const translateToKey = {
<add> '8': 'Backspace',
<add> '9': 'Tab',
<add> '12': 'Clear',
<add> '13': 'Enter',
<add> '16': 'Shift',
<add> '17': 'Control',
<add> '18': 'Alt',
<add> '19': 'Pause',
<add> '20': 'CapsLock',
<add> '27': 'Escape',
<add> '32': ' ',
<add> '33': 'PageUp',
<add> '34': 'PageDown',
<add> '35': 'End',
<add> '36': 'Home',
<add> '37': 'ArrowLeft',
<add> '38': 'ArrowUp',
<add> '39': 'ArrowRight',
<add> '40': 'ArrowDown',
<add> '45': 'Insert',
<add> '46': 'Delete',
<add> '112': 'F1',
<add> '113': 'F2',
<add> '114': 'F3',
<add> '115': 'F4',
<add> '116': 'F5',
<add> '117': 'F6',
<add> '118': 'F7',
<add> '119': 'F8',
<add> '120': 'F9',
<add> '121': 'F10',
<add> '122': 'F11',
<add> '123': 'F12',
<add> '144': 'NumLock',
<add> '145': 'ScrollLock',
<add> '224': 'Meta',
<add>};
<add>
<add>/**
<add> * @param {object} nativeEvent Native browser event.
<add> * @return {string} Normalized `key` property.
<add> */
<add>function getEventKey(nativeEvent) {
<add> if (nativeEvent.key) {
<add> // Normalize inconsistent values reported by browsers due to
<add> // implementations of a working draft specification.
<add>
<add> // FireFox implements `key` but returns `MozPrintableKey` for all
<add> // printable characters (normalized to `Unidentified`), ignore it.
<add> const key = normalizeKey[nativeEvent.key] || nativeEvent.key;
<add> if (key !== 'Unidentified') {
<add> return key;
<add> }
<add> }
<add>
<add> // Browser does not implement `key`, polyfill as much of it as we can.
<add> if (nativeEvent.type === 'keypress') {
<add> const charCode = getEventCharCode(nativeEvent);
<add>
<add> // The enter-key is technically both printable and non-printable and can
<add> // thus be captured by `keypress`, no other non-printable key should.
<add> return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
<add> }
<add> if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
<add> // While user keyboard layout determines the actual meaning of each
<add> // `keyCode` value, almost all function keys have a universal value.
<add> return translateToKey[nativeEvent.keyCode] || 'Unidentified';
<add> }
<add> return '';
<add>}
<add>
<add>/**
<add> * Translation from modifier key to the associated property in the event.
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
<add> */
<add>const modifierKeyToProp = {
<add> Alt: 'altKey',
<add> Control: 'ctrlKey',
<add> Meta: 'metaKey',
<add> Shift: 'shiftKey',
<add>};
<add>
<add>// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
<add>// getModifierState. If getModifierState is not supported, we map it to a set of
<add>// modifier keys exposed by the event. In this case, Lock-keys are not supported.
<add>function modifierStateGetter(keyArg) {
<add> const syntheticEvent = this;
<add> const nativeEvent = syntheticEvent.nativeEvent;
<add> if (nativeEvent.getModifierState) {
<add> return nativeEvent.getModifierState(keyArg);
<add> }
<add> const keyProp = modifierKeyToProp[keyArg];
<add> return keyProp ? !!nativeEvent[keyProp] : false;
<add>}
<add>
<add>function getEventModifierState(nativeEvent) {
<add> return modifierStateGetter;
<add>}
<add>
<add>/**
<add> * @interface KeyboardEvent
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<add> */
<add>export const SyntheticKeyboardEvent = SyntheticUIEvent.extend({
<add> key: getEventKey,
<add> code: null,
<add> location: null,
<add> ctrlKey: null,
<add> shiftKey: null,
<add> altKey: null,
<add> metaKey: null,
<add> repeat: null,
<add> locale: null,
<add> getModifierState: getEventModifierState,
<add> // Legacy Interface
<add> charCode: function(event) {
<add> // `charCode` is the result of a KeyPress event and represents the value of
<add> // the actual printable character.
<add>
<add> // KeyPress is deprecated, but its replacement is not yet final and not
<add> // implemented in any major browser. Only KeyPress has charCode.
<add> if (event.type === 'keypress') {
<add> return getEventCharCode(event);
<add> }
<add> return 0;
<add> },
<add> keyCode: function(event) {
<add> // `keyCode` is the result of a KeyDown/Up event and represents the value of
<add> // physical keyboard key.
<add>
<add> // The actual meaning of the value depends on the users' keyboard layout
<add> // which cannot be detected. Assuming that it is a US keyboard layout
<add> // provides a surprisingly accurate mapping for US and European users.
<add> // Due to this, it is left to the user to implement at this time.
<add> if (event.type === 'keydown' || event.type === 'keyup') {
<add> return event.keyCode;
<add> }
<add> return 0;
<add> },
<add> which: function(event) {
<add> // `which` is an alias for either `keyCode` or `charCode` depending on the
<add> // type of the event.
<add> if (event.type === 'keypress') {
<add> return getEventCharCode(event);
<add> }
<add> if (event.type === 'keydown' || event.type === 'keyup') {
<add> return event.keyCode;
<add> }
<add> return 0;
<add> },
<add>});
<add>
<add>/**
<add> * @interface PointerEvent
<add> * @see http://www.w3.org/TR/pointerevents/
<add> */
<add>export const SyntheticPointerEvent = SyntheticMouseEvent.extend({
<add> pointerId: null,
<add> width: null,
<add> height: null,
<add> pressure: null,
<add> tangentialPressure: null,
<add> tiltX: null,
<add> tiltY: null,
<add> twist: null,
<add> pointerType: null,
<add> isPrimary: null,
<add>});
<add>
<add>/**
<add> * @interface TouchEvent
<add> * @see http://www.w3.org/TR/touch-events/
<add> */
<add>export const SyntheticTouchEvent = SyntheticUIEvent.extend({
<add> touches: null,
<add> targetTouches: null,
<add> changedTouches: null,
<add> altKey: null,
<add> metaKey: null,
<add> ctrlKey: null,
<add> shiftKey: null,
<add> getModifierState: getEventModifierState,
<add>});
<add>
<add>/**
<add> * @interface Event
<add> * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
<add> * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
<add> */
<add>export const SyntheticTransitionEvent = SyntheticEvent.extend({
<add> propertyName: null,
<add> elapsedTime: null,
<add> pseudoElement: null,
<add>});
<add>
<add>/**
<add> * @interface WheelEvent
<add> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<add> */
<add>export const SyntheticWheelEvent = SyntheticMouseEvent.extend({
<add> deltaX(event) {
<add> return 'deltaX' in event
<add> ? event.deltaX
<add> : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
<add> 'wheelDeltaX' in event
<add> ? -event.wheelDeltaX
<add> : 0;
<add> },
<add> deltaY(event) {
<add> return 'deltaY' in event
<add> ? event.deltaY
<add> : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
<add> 'wheelDeltaY' in event
<add> ? -event.wheelDeltaY
<add> : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
<add> 'wheelDelta' in event
<add> ? -event.wheelDelta
<add> : 0;
<add> },
<add> deltaZ: null,
<add>
<add> // Browsers without "deltaMode" is reporting in raw wheel delta where one
<add> // notch on the scroll is always +/- 120, roughly equivalent to pixels.
<add> // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
<add> // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
<add> deltaMode: null,
<add>});
<ide><path>packages/react-dom/src/events/SyntheticFocusEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticUIEvent from './SyntheticUIEvent';
<del>
<del>/**
<del> * @interface FocusEvent
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<del> */
<del>const SyntheticFocusEvent = SyntheticUIEvent.extend({
<del> relatedTarget: null,
<del>});
<del>
<del>export default SyntheticFocusEvent;
<ide><path>packages/react-dom/src/events/SyntheticInputEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>/**
<del> * @interface Event
<del> * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
<del> * /#events-inputevents
<del> */
<del>const SyntheticInputEvent = SyntheticEvent.extend({
<del> data: null,
<del>});
<del>
<del>export default SyntheticInputEvent;
<ide><path>packages/react-dom/src/events/SyntheticKeyboardEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticUIEvent from './SyntheticUIEvent';
<del>import getEventCharCode from './getEventCharCode';
<del>import getEventKey from './getEventKey';
<del>import getEventModifierState from './getEventModifierState';
<del>
<del>/**
<del> * @interface KeyboardEvent
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<del> */
<del>const SyntheticKeyboardEvent = SyntheticUIEvent.extend({
<del> key: getEventKey,
<del> code: null,
<del> location: null,
<del> ctrlKey: null,
<del> shiftKey: null,
<del> altKey: null,
<del> metaKey: null,
<del> repeat: null,
<del> locale: null,
<del> getModifierState: getEventModifierState,
<del> // Legacy Interface
<del> charCode: function(event) {
<del> // `charCode` is the result of a KeyPress event and represents the value of
<del> // the actual printable character.
<del>
<del> // KeyPress is deprecated, but its replacement is not yet final and not
<del> // implemented in any major browser. Only KeyPress has charCode.
<del> if (event.type === 'keypress') {
<del> return getEventCharCode(event);
<del> }
<del> return 0;
<del> },
<del> keyCode: function(event) {
<del> // `keyCode` is the result of a KeyDown/Up event and represents the value of
<del> // physical keyboard key.
<del>
<del> // The actual meaning of the value depends on the users' keyboard layout
<del> // which cannot be detected. Assuming that it is a US keyboard layout
<del> // provides a surprisingly accurate mapping for US and European users.
<del> // Due to this, it is left to the user to implement at this time.
<del> if (event.type === 'keydown' || event.type === 'keyup') {
<del> return event.keyCode;
<del> }
<del> return 0;
<del> },
<del> which: function(event) {
<del> // `which` is an alias for either `keyCode` or `charCode` depending on the
<del> // type of the event.
<del> if (event.type === 'keypress') {
<del> return getEventCharCode(event);
<del> }
<del> if (event.type === 'keydown' || event.type === 'keyup') {
<del> return event.keyCode;
<del> }
<del> return 0;
<del> },
<del>});
<del>
<del>export default SyntheticKeyboardEvent;
<ide><path>packages/react-dom/src/events/SyntheticMouseEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticUIEvent from './SyntheticUIEvent';
<del>import getEventModifierState from './getEventModifierState';
<del>
<del>let previousScreenX = 0;
<del>let previousScreenY = 0;
<del>// Use flags to signal movementX/Y has already been set
<del>let isMovementXSet = false;
<del>let isMovementYSet = false;
<del>
<del>/**
<del> * @interface MouseEvent
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<del> */
<del>const SyntheticMouseEvent = SyntheticUIEvent.extend({
<del> screenX: null,
<del> screenY: null,
<del> clientX: null,
<del> clientY: null,
<del> pageX: null,
<del> pageY: null,
<del> ctrlKey: null,
<del> shiftKey: null,
<del> altKey: null,
<del> metaKey: null,
<del> getModifierState: getEventModifierState,
<del> button: null,
<del> buttons: null,
<del> relatedTarget: function(event) {
<del> return (
<del> event.relatedTarget ||
<del> (event.fromElement === event.srcElement
<del> ? event.toElement
<del> : event.fromElement)
<del> );
<del> },
<del> movementX: function(event) {
<del> if ('movementX' in event) {
<del> return event.movementX;
<del> }
<del>
<del> const screenX = previousScreenX;
<del> previousScreenX = event.screenX;
<del>
<del> if (!isMovementXSet) {
<del> isMovementXSet = true;
<del> return 0;
<del> }
<del>
<del> return event.type === 'mousemove' ? event.screenX - screenX : 0;
<del> },
<del> movementY: function(event) {
<del> if ('movementY' in event) {
<del> return event.movementY;
<del> }
<del>
<del> const screenY = previousScreenY;
<del> previousScreenY = event.screenY;
<del>
<del> if (!isMovementYSet) {
<del> isMovementYSet = true;
<del> return 0;
<del> }
<del>
<del> return event.type === 'mousemove' ? event.screenY - screenY : 0;
<del> },
<del>});
<del>
<del>export default SyntheticMouseEvent;
<ide><path>packages/react-dom/src/events/SyntheticPointerEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticMouseEvent from './SyntheticMouseEvent';
<del>
<del>/**
<del> * @interface PointerEvent
<del> * @see http://www.w3.org/TR/pointerevents/
<del> */
<del>const SyntheticPointerEvent = SyntheticMouseEvent.extend({
<del> pointerId: null,
<del> width: null,
<del> height: null,
<del> pressure: null,
<del> tangentialPressure: null,
<del> tiltX: null,
<del> tiltY: null,
<del> twist: null,
<del> pointerType: null,
<del> isPrimary: null,
<del>});
<del>
<del>export default SyntheticPointerEvent;
<ide><path>packages/react-dom/src/events/SyntheticTouchEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticUIEvent from './SyntheticUIEvent';
<del>import getEventModifierState from './getEventModifierState';
<del>
<del>/**
<del> * @interface TouchEvent
<del> * @see http://www.w3.org/TR/touch-events/
<del> */
<del>const SyntheticTouchEvent = SyntheticUIEvent.extend({
<del> touches: null,
<del> targetTouches: null,
<del> changedTouches: null,
<del> altKey: null,
<del> metaKey: null,
<del> ctrlKey: null,
<del> shiftKey: null,
<del> getModifierState: getEventModifierState,
<del>});
<del>
<del>export default SyntheticTouchEvent;
<ide><path>packages/react-dom/src/events/SyntheticTransitionEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>/**
<del> * @interface Event
<del> * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
<del> * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
<del> */
<del>const SyntheticTransitionEvent = SyntheticEvent.extend({
<del> propertyName: null,
<del> elapsedTime: null,
<del> pseudoElement: null,
<del>});
<del>
<del>export default SyntheticTransitionEvent;
<ide><path>packages/react-dom/src/events/SyntheticUIEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticEvent from '../events/SyntheticEvent';
<del>
<del>const SyntheticUIEvent = SyntheticEvent.extend({
<del> view: null,
<del> detail: null,
<del>});
<del>
<del>export default SyntheticUIEvent;
<ide><path>packages/react-dom/src/events/SyntheticWheelEvent.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> */
<del>
<del>import SyntheticMouseEvent from './SyntheticMouseEvent';
<del>
<del>/**
<del> * @interface WheelEvent
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/
<del> */
<del>const SyntheticWheelEvent = SyntheticMouseEvent.extend({
<del> deltaX(event) {
<del> return 'deltaX' in event
<del> ? event.deltaX
<del> : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
<del> 'wheelDeltaX' in event
<del> ? -event.wheelDeltaX
<del> : 0;
<del> },
<del> deltaY(event) {
<del> return 'deltaY' in event
<del> ? event.deltaY
<del> : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
<del> 'wheelDeltaY' in event
<del> ? -event.wheelDeltaY
<del> : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
<del> 'wheelDelta' in event
<del> ? -event.wheelDelta
<del> : 0;
<del> },
<del> deltaZ: null,
<del>
<del> // Browsers without "deltaMode" is reporting in raw wheel delta where one
<del> // notch on the scroll is always +/- 120, roughly equivalent to pixels.
<del> // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
<del> // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
<del> deltaMode: null,
<del>});
<del>
<del>export default SyntheticWheelEvent;
<add><path>packages/react-dom/src/events/__tests__/DOMPluginEventSystem-test.internal.js
<del><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js
<ide> function endNativeEventListenerClearDown() {
<ide> });
<ide> }
<ide>
<del>describe('DOMModernPluginEventSystem', () => {
<add>describe('DOMPluginEventSystem', () => {
<ide> let container;
<ide>
<ide> function withEnableLegacyFBSupport(enableLegacyFBSupport) {
<ide><path>packages/react-dom/src/events/getEventKey.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow
<del> */
<del>
<del>import getEventCharCode from './getEventCharCode';
<del>
<del>/**
<del> * Normalization of deprecated HTML5 `key` values
<del> * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
<del> */
<del>const normalizeKey = {
<del> Esc: 'Escape',
<del> Spacebar: ' ',
<del> Left: 'ArrowLeft',
<del> Up: 'ArrowUp',
<del> Right: 'ArrowRight',
<del> Down: 'ArrowDown',
<del> Del: 'Delete',
<del> Win: 'OS',
<del> Menu: 'ContextMenu',
<del> Apps: 'ContextMenu',
<del> Scroll: 'ScrollLock',
<del> MozPrintableKey: 'Unidentified',
<del>};
<del>
<del>/**
<del> * Translation from legacy `keyCode` to HTML5 `key`
<del> * Only special keys supported, all others depend on keyboard layout or browser
<del> * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
<del> */
<del>const translateToKey = {
<del> '8': 'Backspace',
<del> '9': 'Tab',
<del> '12': 'Clear',
<del> '13': 'Enter',
<del> '16': 'Shift',
<del> '17': 'Control',
<del> '18': 'Alt',
<del> '19': 'Pause',
<del> '20': 'CapsLock',
<del> '27': 'Escape',
<del> '32': ' ',
<del> '33': 'PageUp',
<del> '34': 'PageDown',
<del> '35': 'End',
<del> '36': 'Home',
<del> '37': 'ArrowLeft',
<del> '38': 'ArrowUp',
<del> '39': 'ArrowRight',
<del> '40': 'ArrowDown',
<del> '45': 'Insert',
<del> '46': 'Delete',
<del> '112': 'F1',
<del> '113': 'F2',
<del> '114': 'F3',
<del> '115': 'F4',
<del> '116': 'F5',
<del> '117': 'F6',
<del> '118': 'F7',
<del> '119': 'F8',
<del> '120': 'F9',
<del> '121': 'F10',
<del> '122': 'F11',
<del> '123': 'F12',
<del> '144': 'NumLock',
<del> '145': 'ScrollLock',
<del> '224': 'Meta',
<del>};
<del>
<del>/**
<del> * @param {object} nativeEvent Native browser event.
<del> * @return {string} Normalized `key` property.
<del> */
<del>function getEventKey(nativeEvent: KeyboardEvent): string {
<del> if (nativeEvent.key) {
<del> // Normalize inconsistent values reported by browsers due to
<del> // implementations of a working draft specification.
<del>
<del> // FireFox implements `key` but returns `MozPrintableKey` for all
<del> // printable characters (normalized to `Unidentified`), ignore it.
<del> const key = normalizeKey[nativeEvent.key] || nativeEvent.key;
<del> if (key !== 'Unidentified') {
<del> return key;
<del> }
<del> }
<del>
<del> // Browser does not implement `key`, polyfill as much of it as we can.
<del> if (nativeEvent.type === 'keypress') {
<del> const charCode = getEventCharCode(nativeEvent);
<del>
<del> // The enter-key is technically both printable and non-printable and can
<del> // thus be captured by `keypress`, no other non-printable key should.
<del> return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
<del> }
<del> if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
<del> // While user keyboard layout determines the actual meaning of each
<del> // `keyCode` value, almost all function keys have a universal value.
<del> return translateToKey[nativeEvent.keyCode] || 'Unidentified';
<del> }
<del> return '';
<del>}
<del>
<del>export default getEventKey;
<ide><path>packages/react-dom/src/events/getEventModifierState.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @flow
<del> */
<del>
<del>/**
<del> * Translation from modifier key to the associated property in the event.
<del> * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
<del> */
<del>
<del>import type {AnyNativeEvent} from '../events/PluginModuleType';
<del>
<del>const modifierKeyToProp = {
<del> Alt: 'altKey',
<del> Control: 'ctrlKey',
<del> Meta: 'metaKey',
<del> Shift: 'shiftKey',
<del>};
<del>
<del>// Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
<del>// getModifierState. If getModifierState is not supported, we map it to a set of
<del>// modifier keys exposed by the event. In this case, Lock-keys are not supported.
<del>function modifierStateGetter(keyArg: string): boolean {
<del> const syntheticEvent = this;
<del> const nativeEvent = syntheticEvent.nativeEvent;
<del> if (nativeEvent.getModifierState) {
<del> return nativeEvent.getModifierState(keyArg);
<del> }
<del> const keyProp = modifierKeyToProp[keyArg];
<del> return keyProp ? !!nativeEvent[keyProp] : false;
<del>}
<del>
<del>function getEventModifierState(
<del> nativeEvent: AnyNativeEvent,
<del>): (keyArg: string) => boolean {
<del> return modifierStateGetter;
<del>}
<del>
<del>export default getEventModifierState;
<add><path>packages/react-dom/src/events/plugins/BeforeInputEventPlugin.js
<del><path>packages/react-dom/src/events/plugins/ModernBeforeInputEventPlugin.js
<ide> import {
<ide> initialize as FallbackCompositionStateInitialize,
<ide> reset as FallbackCompositionStateReset,
<ide> } from '../FallbackCompositionState';
<del>import SyntheticCompositionEvent from '../SyntheticCompositionEvent';
<del>import SyntheticInputEvent from '../SyntheticInputEvent';
<del>import {accumulateTwoPhaseListeners} from '../DOMModernPluginEventSystem';
<add>import {
<add> SyntheticCompositionEvent,
<add> SyntheticInputEvent,
<add>} from '../SyntheticEvent';
<add>import {accumulateTwoPhaseListeners} from '../DOMPluginEventSystem';
<ide>
<ide> const END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
<ide> const START_KEYCODE = 229;
<add><path>packages/react-dom/src/events/plugins/ChangeEventPlugin.js
<del><path>packages/react-dom/src/events/plugins/ModernChangeEventPlugin.js
<ide> */
<ide> import type {AnyNativeEvent} from '../PluginModuleType';
<ide> import type {TopLevelType} from '../TopLevelEventTypes';
<del>import type {DispatchQueue} from '../DOMModernPluginEventSystem';
<add>import type {DispatchQueue} from '../DOMPluginEventSystem';
<ide> import type {EventSystemFlags} from '../EventSystemFlags';
<ide>
<ide> import {registerTwoPhaseEvent} from '../EventRegistry';
<del>import SyntheticEvent from '../SyntheticEvent';
<add>import {SyntheticEvent} from '../SyntheticEvent';
<ide> import isTextInputElement from '../isTextInputElement';
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<ide>
<ide> import {batchedUpdates} from '../ReactDOMUpdateBatching';
<ide> import {
<ide> processDispatchQueue,
<ide> accumulateTwoPhaseListeners,
<del>} from '../DOMModernPluginEventSystem';
<add>} from '../DOMPluginEventSystem';
<ide>
<ide> function registerEvents() {
<ide> registerTwoPhaseEvent('onChange', [
<add><path>packages/react-dom/src/events/plugins/EnterLeaveEventPlugin.js
<del><path>packages/react-dom/src/events/plugins/ModernEnterLeaveEventPlugin.js
<ide> import {
<ide> TOP_POINTER_OVER,
<ide> } from '../DOMTopLevelEventTypes';
<ide> import {IS_REPLAYED} from 'react-dom/src/events/EventSystemFlags';
<del>import SyntheticMouseEvent from '../SyntheticMouseEvent';
<del>import SyntheticPointerEvent from '../SyntheticPointerEvent';
<add>import {SyntheticMouseEvent, SyntheticPointerEvent} from '../SyntheticEvent';
<ide> import {
<ide> getClosestInstanceFromNode,
<ide> getNodeFromInstance,
<ide> } from '../../client/ReactDOMComponentTree';
<del>import {accumulateEnterLeaveTwoPhaseListeners} from '../DOMModernPluginEventSystem';
<add>import {accumulateEnterLeaveTwoPhaseListeners} from '../DOMPluginEventSystem';
<ide>
<ide> import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags';
<ide> import {getNearestMountedFiber} from 'react-reconciler/src/ReactFiberTreeReflection';
<add><path>packages/react-dom/src/events/plugins/SelectEventPlugin.js
<del><path>packages/react-dom/src/events/plugins/ModernSelectEventPlugin.js
<ide> */
<ide>
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<del>import SyntheticEvent from '../../events/SyntheticEvent';
<add>import {SyntheticEvent} from '../../events/SyntheticEvent';
<ide> import isTextInputElement from '../isTextInputElement';
<ide> import shallowEqual from 'shared/shallowEqual';
<ide>
<ide> import {
<ide> } from '../../client/ReactDOMComponentTree';
<ide> import {hasSelectionCapabilities} from '../../client/ReactInputSelection';
<ide> import {DOCUMENT_NODE} from '../../shared/HTMLNodeType';
<del>import {accumulateTwoPhaseListeners} from '../DOMModernPluginEventSystem';
<add>import {accumulateTwoPhaseListeners} from '../DOMPluginEventSystem';
<ide>
<ide> const skipSelectionChangeEvent =
<ide> canUseDOM && 'documentMode' in document && document.documentMode <= 11;
<add><path>packages/react-dom/src/events/plugins/SimpleEventPlugin.js
<del><path>packages/react-dom/src/events/plugins/ModernSimpleEventPlugin.js
<ide> import type {TopLevelType} from '../../events/TopLevelEventTypes';
<ide> import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
<ide> import type {AnyNativeEvent} from '../../events/PluginModuleType';
<del>import type {DispatchQueue} from '../DOMModernPluginEventSystem';
<add>import type {DispatchQueue} from '../DOMPluginEventSystem';
<ide> import type {EventSystemFlags} from '../EventSystemFlags';
<ide>
<del>import SyntheticEvent from '../../events/SyntheticEvent';
<add>import {
<add> SyntheticEvent,
<add> SyntheticAnimationEvent,
<add> SyntheticClipboardEvent,
<add> SyntheticFocusEvent,
<add> SyntheticKeyboardEvent,
<add> SyntheticMouseEvent,
<add> SyntheticPointerEvent,
<add> SyntheticDragEvent,
<add> SyntheticTouchEvent,
<add> SyntheticTransitionEvent,
<add> SyntheticUIEvent,
<add> SyntheticWheelEvent,
<add>} from '../../events/SyntheticEvent';
<ide>
<ide> import * as DOMTopLevelEventTypes from '../DOMTopLevelEventTypes';
<ide> import {
<ide> import {
<ide> import {
<ide> accumulateSinglePhaseListeners,
<ide> accumulateEventHandleNonManagedNodeListeners,
<del>} from '../DOMModernPluginEventSystem';
<add>} from '../DOMPluginEventSystem';
<ide> import {IS_EVENT_HANDLE_NON_MANAGED_NODE} from '../EventSystemFlags';
<del>import SyntheticAnimationEvent from '../SyntheticAnimationEvent';
<del>import SyntheticClipboardEvent from '../SyntheticClipboardEvent';
<del>import SyntheticFocusEvent from '../SyntheticFocusEvent';
<del>import SyntheticKeyboardEvent from '../SyntheticKeyboardEvent';
<del>import SyntheticMouseEvent from '../SyntheticMouseEvent';
<del>import SyntheticPointerEvent from '../SyntheticPointerEvent';
<del>import SyntheticDragEvent from '../SyntheticDragEvent';
<del>import SyntheticTouchEvent from '../SyntheticTouchEvent';
<del>import SyntheticTransitionEvent from '../SyntheticTransitionEvent';
<del>import SyntheticUIEvent from '../SyntheticUIEvent';
<del>import SyntheticWheelEvent from '../SyntheticWheelEvent';
<add>
<ide> import getEventCharCode from '../getEventCharCode';
<ide> import {IS_CAPTURE_PHASE} from '../EventSystemFlags';
<ide>
<ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> import {
<ide> HostComponent,
<ide> HostText,
<ide> } from 'react-reconciler/src/ReactWorkTags';
<del>import SyntheticEvent from '../events/SyntheticEvent';
<add>import {SyntheticEvent} from '../events/SyntheticEvent';
<ide> import invariant from 'shared/invariant';
<ide> import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<ide> import act from './ReactTestUtilsAct'; | 29 |
Java | Java | fix issue with failing test from previous commit | 5a365074c2bddb3e4517ec5eceb39d4e6ca85b56 | <ide><path>spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
<ide> protected void doFilterInternal(
<ide> closeSession(sessionHolder.getSession(), sessionFactory);
<ide> }
<ide> else {
<del> if (!chain.pop()) {
<add> if (chain.isAsyncStarted()) {
<ide> throw new IllegalStateException("Deferred close is not supported with async requests.");
<ide> }
<ide> // deferred close mode | 1 |
Ruby | Ruby | remove unnecessary comment | bd9953f11e8e72f8a8a507182d7328f3c8802e27 | <ide><path>railties/test/generators/assets_generator_test.rb
<ide> require 'generators/generators_test_helper'
<ide> require 'rails/generators/rails/assets/assets_generator'
<ide>
<del># FIXME: Silence the 'Could not find task "using_coffee?"' message in tests due to the public stub
<ide> class AssetsGeneratorTest < Rails::Generators::TestCase
<ide> include GeneratorsTestHelper
<ide> arguments %w(posts) | 1 |
Javascript | Javascript | add type checking to makecallback() | 1f40b2a63616efe0e4c0744a1f630161526e4236 | <ide><path>lib/fs.js
<ide> function maybeCallback(cb) {
<ide> // for callbacks that are passed to the binding layer, callbacks that are
<ide> // invoked from JS already run in the proper scope.
<ide> function makeCallback(cb) {
<del> if (typeof cb !== 'function') {
<add> if (cb === undefined) {
<ide> return rethrow();
<ide> }
<ide>
<add> if (typeof cb !== 'function') {
<add> throw new TypeError('callback must be a function');
<add> }
<add>
<ide> return function() {
<ide> return cb.apply(null, arguments);
<ide> };
<ide><path>test/parallel/test-fs-make-callback.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var fs = require('fs');
<add>
<add>function test(cb) {
<add> return function() {
<add> // fs.stat() calls makeCallback() on its second argument
<add> fs.stat(__filename, cb);
<add> };
<add>}
<add>
<add>// Verify the case where a callback function is provided
<add>assert.doesNotThrow(test(function() {}));
<add>
<add>// Passing undefined calls rethrow() internally, which is fine
<add>assert.doesNotThrow(test(undefined));
<add>
<add>// Anything else should throw
<add>assert.throws(test(null));
<add>assert.throws(test(true));
<add>assert.throws(test(false));
<add>assert.throws(test(1));
<add>assert.throws(test(0));
<add>assert.throws(test('foo'));
<add>assert.throws(test(/foo/));
<add>assert.throws(test([]));
<add>assert.throws(test({})); | 2 |
Text | Text | remove gpt2 in readme | 886cb59ae7cf106f8cb5314df21593a2c8631ff5 | <ide><path>official/nlp/README.md
<ide> model weights, usage scripts and conversion utilities for the following models:
<ide>
<ide> * [XLNet](xlnet)
<ide>
<del>* GPT2 (comming soon)
<del>
<ide> * [Transformer for translation](../transformer) | 1 |
Javascript | Javascript | restore apply as a fallback | 9f32ac807b0e32f242d8960df80dadc77f65ab96 | <ide><path>packages/ember-metal/lib/logger.js
<ide> function consoleMethod(name) {
<ide> logToConsole = method.bind(consoleObj);
<ide> logToConsole.displayName = 'console.' + name;
<ide> return logToConsole;
<add> } else if (typeof method.apply === 'function') {
<add> logToConsole = function() {
<add> method.apply(consoleObj, arguments);
<add> };
<add> logToConsole.displayName = 'console.' + name;
<add> return logToConsole;
<ide> } else {
<ide> return function() {
<ide> var message = Array.prototype.join.call(arguments, ', '); | 1 |
Java | Java | fix failing tests | ce69855274e93b436c378e808f746f0d1cc2e538 | <ide><path>spring-web/src/main/java/org/springframework/web/method/annotation/ExceptionHandlerMethodResolver.java
<ide> public boolean hasExceptionMappings() {
<ide> * @return a Method to handle the exception, or {@code null} if none found
<ide> */
<ide> public Method resolveMethod(Exception exception) {
<del> return resolveMethod(exception);
<add> return resolveMethodByThrowable(exception);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | use a separate class for gnu compiler failures | 4580d86809095a236839d1de55e47e5dc98b7987 | <ide><path>Library/Homebrew/compilers.rb
<ide> def major_version
<ide> end
<ide>
<ide> class CompilerFailure
<del> attr_reader :name, :major_version
<add> attr_reader :name
<ide> attr_rw :cause, :version
<ide>
<ide> # Allows Apple compiler `fails_with` statements to keep using `build`
<ide> def self.create(spec, &block)
<ide> name = "gcc-#{major_version}"
<ide> # so fails_with :gcc => '4.8' simply marks all 4.8 releases incompatible
<ide> version = "#{major_version}.999"
<add> GnuCompilerFailure.new(name, major_version, version, &block)
<ide> else
<ide> name = spec
<ide> version = 9999
<del> major_version = nil
<add> new(name, version, &block)
<ide> end
<del>
<del> new(name, version, major_version, &block)
<ide> end
<ide>
<del> def initialize(name, version, major_version, &block)
<add> def initialize(name, version, &block)
<ide> @name = name
<ide> @version = version
<del> @major_version = major_version
<ide> instance_eval(&block) if block_given?
<ide> end
<ide>
<ide> def ===(compiler)
<del> name == compiler.name &&
<del> major_version == compiler.major_version &&
<del> version >= (compiler.version || 0)
<add> name == compiler.name && version >= (compiler.version || 0)
<add> end
<add>
<add> class GnuCompilerFailure < CompilerFailure
<add> attr_reader :major_version
<add>
<add> def initialize(name, major_version, version, &block)
<add> @major_version = major_version
<add> super(name, version, &block)
<add> end
<add>
<add> def ===(compiler)
<add> super && major_version == compiler.major_version
<add> end
<ide> end
<ide>
<ide> MESSAGES = { | 1 |
Text | Text | add credit to committer of pull request | a774354dfea6dfe9b0caff2ab1df52a1f73716be | <ide><path>activemodel/CHANGELOG.md
<ide>
<ide> * Trim down Active Model API by removing `valid?` and `errors.full_messages` *José Valim*
<ide>
<del>* When `^` or `$` are used in the regular expression provided to `validates_format_of` and the :multiline option is not set to true, an exception will be raised. This is to prevent security vulnerabilities when using `validates_format_of`. The problem is described in detail in the Rails security guide.
<add>* When `^` or `$` are used in the regular expression provided to `validates_format_of` and the :multiline option is not set to true, an exception will be raised. This is to prevent security vulnerabilities when using `validates_format_of`. The problem is described in detail in the Rails security guide *Jan Berdajs + Egor Homakov*
<ide>
<ide> Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activemodel/CHANGELOG.md) for previous changes. | 1 |
Python | Python | set version to v3.0.4 | 3b911ee5ef2240919b66a0ce55a5d387ceb6f904 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "3.0.3"
<add>__version__ = "3.0.4"
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
<ide> __projects__ = "https://github.com/explosion/projects" | 1 |
Python | Python | add ent_id and norm to docbin strings | fe3a4aa846dcfde51eb3343cd04560da2b5ba705 | <ide><path>spacy/tests/serialize/test_serialize_doc.py
<ide> def test_serialize_doc_span_groups(en_vocab):
<ide>
<ide>
<ide> def test_serialize_doc_bin():
<del> doc_bin = DocBin(attrs=["LEMMA", "ENT_IOB", "ENT_TYPE"], store_user_data=True)
<add> doc_bin = DocBin(attrs=["LEMMA", "ENT_IOB", "ENT_TYPE", "NORM", "ENT_ID"], store_user_data=True)
<ide> texts = ["Some text", "Lots of texts...", "..."]
<ide> cats = {"A": 0.5}
<ide> nlp = English()
<ide> for doc in nlp.pipe(texts):
<ide> doc.cats = cats
<ide> doc.spans["start"] = [doc[0:2]]
<add> doc[0].norm_ = "UNUSUAL_TOKEN_NORM"
<add> doc[0].ent_id_ = "UNUSUAL_TOKEN_ENT_ID"
<ide> doc_bin.add(doc)
<ide> bytes_data = doc_bin.to_bytes()
<ide>
<ide> def test_serialize_doc_bin():
<ide> assert doc.text == texts[i]
<ide> assert doc.cats == cats
<ide> assert len(doc.spans) == 1
<add> assert doc[0].norm_ == "UNUSUAL_TOKEN_NORM"
<add> assert doc[0].ent_id_ == "UNUSUAL_TOKEN_ENT_ID"
<ide>
<ide>
<ide> def test_serialize_doc_bin_unknown_spaces(en_vocab):
<ide><path>spacy/tokens/_serialize.py
<ide> def add(self, doc: Doc) -> None:
<ide> self.strings.add(token.text)
<ide> self.strings.add(token.tag_)
<ide> self.strings.add(token.lemma_)
<add> self.strings.add(token.norm_)
<ide> self.strings.add(str(token.morph))
<ide> self.strings.add(token.dep_)
<ide> self.strings.add(token.ent_type_)
<ide> self.strings.add(token.ent_kb_id_)
<add> self.strings.add(token.ent_id_)
<ide> self.cats.append(doc.cats)
<ide> self.user_data.append(srsly.msgpack_dumps(doc.user_data))
<ide> self.span_groups.append(doc.spans.to_bytes()) | 2 |
PHP | PHP | apply fixes from styleci | fcbc27782447c2baf938b808bc4bc49b5e45ccd3 | <ide><path>src/Illuminate/Foundation/Console/Presets/Preset.php
<ide> protected static function updatePackages()
<ide>
<ide> file_put_contents(
<ide> base_path('package.json'),
<del> json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL
<add> json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
<ide> );
<ide> }
<ide> | 1 |
PHP | PHP | update message for phpunit3.6 | 99caa98df3beeec080654ef31eee7d363e9e7018 | <ide><path>lib/Cake/Console/Command/TestsuiteShell.php
<ide> public function getOptionParser() {
<ide> ))->addOption('fixture', array(
<ide> 'help' => __d('cake_console', 'Choose a custom fixture manager.'),
<ide> ))->addOption('debug', array(
<del> 'help' => __d('cake_console', 'More verbose output.'),
<add> 'help' => __d('cake_console', 'Enable full output of testsuite. (supported in PHPUnit 3.6.0 and greater)'),
<ide> ));
<ide>
<ide> return $parser; | 1 |
Ruby | Ruby | fix legacy fallback for parameterized mailers | 5d6578d15bb5d3bfe3751a6493b9e3fe99618408 | <ide><path>actionmailer/lib/action_mailer/parameterized.rb
<ide> def enqueue_delivery(delivery_method, options = {})
<ide> if processed?
<ide> super
<ide> else
<del> job = @mailer_class.delivery_job
<add> job = delivery_job_class
<ide> args = arguments_for(job, delivery_method)
<ide> job.set(options).perform_later(*args)
<ide> end
<ide> end
<ide>
<add> def delivery_job_class
<add> if @mailer_class.delivery_job <= MailDeliveryJob
<add> @mailer_class.delivery_job
<add> else
<add> Parameterized::DeliveryJob
<add> end
<add> end
<add>
<ide> def arguments_for(delivery_job, delivery_method)
<ide> if delivery_job <= MailDeliveryJob
<ide> [@mailer_class.name, @action.to_s, delivery_method.to_s, params: @params, args: @args]
<ide><path>actionmailer/test/abstract_unit.rb
<ide> def self.root
<ide> FIXTURE_LOAD_PATH = File.expand_path("fixtures", __dir__)
<ide> ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH
<ide>
<add>ActionMailer::Base.delivery_job = ActionMailer::MailDeliveryJob
<add>
<ide> class ActiveSupport::TestCase
<ide> include ActiveSupport::Testing::MethodCallAssertions
<ide>
<ide><path>actionmailer/test/legacy_delivery_job_test.rb
<ide> class LegacyDeliveryJobTest < ActiveSupport::TestCase
<ide> class LegacyDeliveryJob < ActionMailer::DeliveryJob
<ide> end
<ide>
<del> class LegacyParmeterizedDeliveryJob < ActionMailer::Parameterized::DeliveryJob
<del> end
<del>
<ide> setup do
<ide> @previous_logger = ActiveJob::Base.logger
<ide> ActiveJob::Base.logger = Logger.new(nil)
<ide> class LegacyParmeterizedDeliveryJob < ActionMailer::Parameterized::DeliveryJob
<ide> { inviter: "david@basecamp.com", invitee: "jason@basecamp.com" },
<ide> ]
<ide>
<del> with_delivery_job(LegacyParmeterizedDeliveryJob) do
<add> with_delivery_job(LegacyDeliveryJob) do
<ide> assert_deprecated do
<del> assert_performed_with(job: LegacyParmeterizedDeliveryJob, args: args) do
<add> assert_performed_with(job: ActionMailer::Parameterized::DeliveryJob, args: args) do
<ide> mail.deliver_later
<ide> end
<ide> end | 3 |
Ruby | Ruby | add record class to error message | 5c03aff4fc9905a5e3134492a62bdda741f19390 | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def verify_readonly_attribute(name)
<ide>
<ide> def _raise_record_not_destroyed
<ide> @_association_destroy_exception ||= nil
<del> raise @_association_destroy_exception || RecordNotDestroyed.new("Failed to destroy the record", self)
<add> raise @_association_destroy_exception || RecordNotDestroyed.new("Failed to destroy the #{self.class} record", self)
<ide> ensure
<ide> @_association_destroy_exception = nil
<ide> end
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_association_with_rewhere_doesnt_set_inverse_instance_key
<ide> end
<ide>
<ide> assert_equal [original_child], car.reload.failed_bulbs
<del> assert_equal "Failed to destroy the record", error.message
<add> assert_equal "Failed to destroy the FailedBulb record", error.message
<ide> end
<ide>
<ide> test "updates counter cache when default scope is given" do | 2 |
Javascript | Javascript | prevent unnecessary re-renders | b0f18cacc78a027b3411ed36d12a7991c4f5cc9c | <ide><path>client/src/templates/Challenges/classic/Editor.js
<ide> class Editor extends Component {
<ide>
<ide> // TODO: tabs should be dynamically created from the challengeFiles
<ide> // TODO: a11y fixes.
<add> // TODO: is the key necessary? Try switching themes without it.
<ide> return (
<ide> <Suspense fallback={<Loader timeout={600} />}>
<ide> <span className='notranslate'>
<ide> class Editor extends Component {
<ide> <MonacoEditor
<ide> editorDidMount={this.editorDidMount}
<ide> editorWillMount={this.editorWillMount}
<del> key={`${editorTheme}-${this.currentFileKey}`}
<add> key={`${editorTheme}`}
<ide> onChange={this.onChange}
<ide> options={this.options}
<ide> theme={editorTheme} | 1 |
Text | Text | add changelogs for zlib | adcd0bd9b457668930e0d5105426929a9b1b8fbd | <ide><path>doc/api/zlib.md
<ide> Compression strategy.
<ide> ## Class Options
<ide> <!-- YAML
<ide> added: v0.11.1
<add>changes:
<add> - version: v5.11.0
<add> pr-url: https://github.com/nodejs/node/pull/6069
<add> description: The `finishFlush` option is supported now.
<ide> -->
<ide>
<ide> <!--type=misc-->
<ide> Compress data using deflate, and do not append a `zlib` header.
<ide> ## Class: zlib.Gunzip
<ide> <!-- YAML
<ide> added: v0.5.8
<add>changes:
<add> - version: v6.0.0
<add> pr-url: https://github.com/nodejs/node/pull/5883
<add> description: Trailing garbage at the end of the input stream will now
<add> result in an `error` event.
<add> - version: v5.9.0
<add> pr-url: https://github.com/nodejs/node/pull/5120
<add> description: Multiple concatenated gzip file members are supported now.
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2595
<add> description: A truncated input stream will now result in an `error` event.
<ide> -->
<ide>
<ide> Decompress a gzip stream.
<ide> Compress data using gzip.
<ide> ## Class: zlib.Inflate
<ide> <!-- YAML
<ide> added: v0.5.8
<add>changes:
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2595
<add> description: A truncated input stream will now result in an `error` event.
<ide> -->
<ide>
<ide> Decompress a deflate stream.
<ide>
<ide> ## Class: zlib.InflateRaw
<ide> <!-- YAML
<ide> added: v0.5.8
<add>changes:
<add> - version: v6.8.0
<add> pr-url: https://github.com/nodejs/node/pull/8512
<add> description: Custom dictionaries are now supported by `InflateRaw`.
<add> - version: v5.0.0
<add> pr-url: https://github.com/nodejs/node/pull/2595
<add> description: A truncated input stream will now result in an `error` event.
<ide> -->
<ide>
<ide> Decompress a raw deflate stream. | 1 |
Javascript | Javascript | move free socket error handling to agent | 2bf02285a39550ef85bb5f3d7fe13655ff44dcf1 | <ide><path>lib/_http_agent.js
<ide> class ReusedHandle {
<ide> }
<ide> }
<ide>
<add>function freeSocketErrorListener(err) {
<add> const socket = this;
<add> debug('SOCKET ERROR on FREE socket:', err.message, err.stack);
<add> socket.destroy();
<add> socket.emit('agentRemove');
<add>}
<add>
<ide> function Agent(options) {
<ide> if (!(this instanceof Agent))
<ide> return new Agent(options);
<ide> function Agent(options) {
<ide> const name = this.getName(options);
<ide> debug('agent.on(free)', name);
<ide>
<add> // TODO(ronag): socket.destroy(err) might have been called
<add> // before coming here and have an 'error' scheduled. In the
<add> // case of socket.destroy() below this 'error' has no handler
<add> // and could cause unhandled exception.
<add>
<ide> if (socket.writable &&
<ide> this.requests[name] && this.requests[name].length) {
<ide> const req = this.requests[name].shift();
<ide> function Agent(options) {
<ide> socket.setTimeout(agentTimeout);
<ide> }
<ide>
<add> socket.once('error', freeSocketErrorListener);
<ide> freeSockets.push(socket);
<ide> } else {
<ide> // Implementation doesn't want to keep socket alive
<ide> Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
<ide>
<ide> Agent.prototype.reuseSocket = function reuseSocket(socket, req) {
<ide> debug('have free socket');
<add> socket.removeListener('error', freeSocketErrorListener);
<ide> req.reusedSocket = true;
<ide> socket.ref();
<ide> };
<ide><path>lib/_http_client.js
<ide> function socketErrorListener(err) {
<ide> socket.destroy();
<ide> }
<ide>
<del>function freeSocketErrorListener(err) {
<del> const socket = this;
<del> debug('SOCKET ERROR on FREE socket:', err.message, err.stack);
<del> socket.destroy();
<del> socket.emit('agentRemove');
<del>}
<del>
<ide> function socketOnEnd() {
<ide> const socket = this;
<ide> const req = this._httpMessage;
<ide> function responseKeepAlive(req) {
<ide> socket.removeListener('error', socketErrorListener);
<ide> socket.removeListener('data', socketOnData);
<ide> socket.removeListener('end', socketOnEnd);
<del> socket.once('error', freeSocketErrorListener);
<del> // There are cases where _handle === null. Avoid those. Passing null to
<add>
<add> // TODO(ronag): Between here and emitFreeNT the socket
<add> // has no 'error' handler.
<add>
<add> // There are cases where _handle === null. Avoid those. Passing undefined to
<ide> // nextTick() will call getDefaultTriggerAsyncId() to retrieve the id.
<ide> const asyncId = socket._handle ? socket._handle.getAsyncId() : undefined;
<ide> // Mark this socket as available, AFTER user-added end
<ide> function tickOnSocket(req, socket) {
<ide> }
<ide>
<ide> parser.onIncoming = parserOnIncomingClient;
<del> socket.removeListener('error', freeSocketErrorListener);
<ide> socket.on('error', socketErrorListener);
<ide> socket.on('data', socketOnData);
<ide> socket.on('end', socketOnEnd);
<ide> function listenSocketTimeout(req) {
<ide> }
<ide>
<ide> ClientRequest.prototype.onSocket = function onSocket(socket) {
<add> // TODO(ronag): Between here and onSocketNT the socket
<add> // has no 'error' handler.
<ide> process.nextTick(onSocketNT, this, socket);
<ide> };
<ide> | 2 |
Ruby | Ruby | show casks in install not found output | a481729ade5f3c2be9980a3b4259bdc61d37e275 | <ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> # formula was found, but there's a problem with its implementation).
<ide> $stderr.puts e.backtrace if Homebrew::EnvConfig.developer?
<ide> ofail e.message
<del> rescue FormulaOrCaskUnavailableError => e
<del> if e.name == "updog"
<add> rescue FormulaOrCaskUnavailableError, Cask::CaskUnavailableError => e
<add> # formula name or cask token
<add> name = e.try(:name) || e.token
<add>
<add> if name == "updog"
<ide> ofail "What's updog?"
<ide> return
<ide> end
<ide>
<ide> opoo e
<del> ohai "Searching for similarly named formulae..."
<del> formulae_search_results = search_formulae(e.name)
<del> case formulae_search_results.length
<del> when 0
<del> ofail "No similarly named formulae found."
<del> when 1
<del> puts "This similarly named formula was found:"
<del> puts formulae_search_results
<del> puts "To install it, run:\n brew install #{formulae_search_results.first}"
<del> else
<del> puts "These similarly named formulae were found:"
<del> puts Formatter.columns(formulae_search_results)
<del> puts "To install one of them, run (for example):\n brew install #{formulae_search_results.first}"
<del> end
<add> ohai "Searching for similarly named formulae and casks..."
<ide>
<del> if (reason = MissingFormula.reason(e.name))
<del> $stderr.puts reason
<del> return
<del> end
<add> # Don't treat formula/cask name as a regex
<add> query = string_or_regex = name
<add> if search_names(query, string_or_regex, args)
<add> puts <<~EOL
<ide>
<del> # Do not search taps if the formula name is qualified
<del> return if e.name.include?("/")
<del>
<del> taps_search_results = search_taps(e.name)[:formulae]
<del> case taps_search_results.length
<del> when 0
<del> ofail "No formulae found in taps."
<del> when 1
<del> puts "This formula was found in a tap:"
<del> puts taps_search_results
<del> puts "To install it, run:\n brew install #{taps_search_results.first}"
<del> else
<del> puts "These formulae were found in taps:"
<del> puts Formatter.columns(taps_search_results)
<del> puts "To install one of them, run (for example):\n brew install #{taps_search_results.first}"
<add> To install one of them, run:
<add> brew install 'package_name'
<add> EOL
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cmd/search.rb
<ide> def search_pull_requests(query, args)
<ide>
<ide> GitHub.print_pull_requests_matching(query, only)
<ide> end
<del>
<del> def search_names(query, string_or_regex, args)
<del> remote_results = search_taps(query, silent: true)
<del>
<del> local_formulae = search_formulae(string_or_regex)
<del> remote_formulae = remote_results[:formulae]
<del> all_formulae = local_formulae + remote_formulae
<del>
<del> local_casks = search_casks(string_or_regex)
<del> remote_casks = remote_results[:casks]
<del> all_casks = local_casks + remote_casks
<del>
<del> print_formulae = args.formula?
<del> print_casks = args.cask?
<del> print_formulae = print_casks = true if !print_formulae && !print_casks
<del> print_formulae &&= all_formulae.any?
<del> print_casks &&= all_casks.any?
<del>
<del> if print_formulae
<del> if $stdout.tty?
<del> ohai "Formulae", Formatter.columns(all_formulae)
<del> else
<del> puts all_formulae
<del> end
<del> end
<del> puts if print_formulae && print_casks
<del> if print_casks
<del> if $stdout.tty?
<del> ohai "Casks", Formatter.columns(all_casks)
<del> else
<del> puts all_casks
<del> end
<del> end
<del>
<del> count = all_formulae.count + all_casks.count
<del>
<del> print_missing_formula_help(query, count.positive?) if local_casks.exclude?(query)
<del>
<del> odie "No formulae or casks found for #{query.inspect}." if count.zero?
<del> end
<del>
<del> def print_missing_formula_help(query, found_matches)
<del> return unless $stdout.tty?
<del>
<del> reason = MissingFormula.reason(query, silent: true)
<del> return if reason.nil?
<del>
<del> if found_matches
<del> puts
<del> puts "If you meant #{query.inspect} specifically:"
<del> end
<del> puts reason
<del> end
<ide> end
<ide><path>Library/Homebrew/search.rb
<ide> def search_formulae(string_or_regex)
<ide> def search_casks(_string_or_regex)
<ide> []
<ide> end
<add>
<add> def search_names(query, string_or_regex, args)
<add> remote_results = search_taps(query, silent: true)
<add>
<add> local_formulae = search_formulae(string_or_regex)
<add> remote_formulae = remote_results[:formulae]
<add> all_formulae = local_formulae + remote_formulae
<add>
<add> local_casks = search_casks(string_or_regex)
<add> remote_casks = remote_results[:casks]
<add> all_casks = local_casks + remote_casks
<add>
<add> print_formulae = args.formula?
<add> print_casks = args.cask?
<add> print_formulae = print_casks = true if !print_formulae && !print_casks
<add> print_formulae &&= all_formulae.any?
<add> print_casks &&= all_casks.any?
<add>
<add> count = 0
<add> if print_formulae
<add> if $stdout.tty?
<add> ohai "Formulae", Formatter.columns(all_formulae)
<add> else
<add> puts all_formulae
<add> end
<add> count += all_formulae.count
<add> end
<add> puts if print_formulae && print_casks
<add> if print_casks
<add> if $stdout.tty?
<add> ohai "Casks", Formatter.columns(all_casks)
<add> else
<add> puts all_casks
<add> end
<add> count += all_casks.count
<add> end
<add>
<add> print_missing_formula_help(query, count.positive?) if local_casks.exclude?(query)
<add>
<add> odie "No formulae or casks found for #{query.inspect}." if count.zero?
<add> !count.zero?
<add> end
<add>
<add> def print_missing_formula_help(query, found_matches)
<add> return unless $stdout.tty?
<add>
<add> reason = MissingFormula.reason(query, silent: true)
<add> return if reason.nil?
<add>
<add> if found_matches
<add> puts
<add> puts "If you meant #{query.inspect} specifically:"
<add> end
<add> puts reason
<add> end
<ide> end
<ide> end
<ide> | 3 |
Javascript | Javascript | resolve promise in test | 33e63fe64f238227481b83fc401a1a2371013995 | <ide><path>test/addons-napi/test_promise/test.js
<ide> common.crashOnUnhandledRejection();
<ide> test_promise.concludeCurrentPromise(Promise.resolve('chained answer'), true);
<ide> }
<ide>
<del>assert.strictEqual(test_promise.isPromise(test_promise.createPromise()), true);
<add>const promiseTypeTestPromise = test_promise.createPromise();
<add>assert.strictEqual(test_promise.isPromise(promiseTypeTestPromise), true);
<add>test_promise.concludeCurrentPromise(undefined, true);
<ide>
<ide> const rejectPromise = Promise.reject(-1);
<ide> const expected_reason = -1; | 1 |
PHP | PHP | update pluralizer.php | 769ccaebc520a84f59ba62d8639b75f5081c03cf | <ide><path>src/Illuminate/Support/Pluralizer.php
<ide> class Pluralizer
<ide> 'emoji',
<ide> 'equipment',
<ide> 'fish',
<add> 'furniture',
<ide> 'gold',
<ide> 'information',
<ide> 'knowledge',
<ide> class Pluralizer
<ide> 'species',
<ide> 'swine',
<ide> 'traffic',
<add> 'wheat',
<ide> ];
<ide>
<ide> /** | 1 |
PHP | PHP | add missing parent calls | 72c3059d94702e51555a10cad8c0707f85488b4a | <ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> class BasicsTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> App::build(array(
<ide> 'Locale' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Locale' . DS)
<ide> ));
<del> $this->_language = Configure::read('Config.language');
<del> }
<del>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> App::build();
<del> Configure::write('Config.language', $this->_language);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Cache/CacheTest.php
<ide> class CacheTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> Configure::write('Cache.disable', false);
<ide>
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::config('default', $this->_defaultCacheConfig['settings']);
<ide> }
<ide><path>lib/Cake/Test/Case/Cache/Engine/ApcEngineTest.php
<ide> class ApcEngineTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->skipIf(!function_exists('apc_store'), 'Apc is not installed or configured properly.');
<ide>
<ide> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::drop('apc');
<ide> Cache::config('default');
<ide><path>lib/Cake/Test/Case/Cache/Engine/MemcacheEngineTest.php
<ide> class MemcacheEngineTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->skipIf(!class_exists('Memcache'), 'Memcache is not installed or configured properly.');
<ide>
<ide> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::drop('memcache');
<ide> Cache::config('default');
<ide><path>lib/Cake/Test/Case/Cache/Engine/WincacheEngineTest.php
<ide> class WincacheEngineTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->skipIf(!function_exists('wincache_ucache_set'), 'Wincache is not installed or configured properly.');
<ide> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> Configure::write('Cache.disable', false);
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Cache::drop('wincache');
<ide> Cache::config('default');
<ide><path>lib/Cake/Test/Case/Cache/Engine/XcacheEngineTest.php
<ide> class XcacheEngineTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> if (!function_exists('xcache_set')) {
<ide> $this->markTestSkipped('Xcache is not installed or configured properly');
<ide> }
<del> $this->_cacheDisable = Configure::read('Cache.disable');
<ide> Configure::write('Cache.disable', false);
<ide> Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_'));
<ide> }
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> Configure::write('Cache.disable', $this->_cacheDisable);
<del> Cache::config('default');
<add> parent::tearDown();
<add> Cache::drop('xcache');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Console/Command/TestShellTest.php
<ide> class TestShellTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $out = $this->getMock('ConsoleOutput', array(), array(), '', false);
<ide> $in = $this->getMock('ConsoleInput', array(), array(), '', false);
<ide>
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> unset($this->Dispatch, $this->Shell);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Console/ConsoleOutputTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> unset($this->output);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Controller/Component/Acl/IniAclTest.php
<del><?php
<add><?
<ide> /**
<ide> * IniAclTest file.
<ide> *
<ide><path>lib/Cake/Test/Case/Controller/Component/Acl/PhpAclTest.php
<ide> class_exists('AclComponent');
<ide> class PhpAclTest extends CakeTestCase {
<ide>
<ide> public function setUp() {
<add> parent::setUp();
<ide> Configure::write('Acl.classname', 'PhpAcl');
<ide> $Collection = new ComponentCollection();
<ide> $this->PhpAcl = new PhpAcl();
<ide><path>lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php
<ide> public function setUp() {
<ide> $password = Security::hash('password', null, true);
<ide> $User = ClassRegistry::init('User');
<ide> $User->updateAll(array('password' => $User->getDataSource()->value($password)));
<del> $this->server = $_SERVER;
<ide> $this->response = $this->getMock('CakeResponse');
<ide> }
<ide>
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> $_SERVER = $this->server;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Controller/Component/Auth/CrudAuthorizeTest.php
<ide> class CrudAuthorizeTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<del> Configure::write('Routing.prefixes', array());
<del>
<ide> parent::setUp();
<add> Configure::write('Routing.prefixes', array());
<ide>
<ide> $this->Acl = $this->getMock('AclComponent', array(), array(), '', false);
<ide> $this->Components = $this->getMock('ComponentCollection');
<ide><path>lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php
<ide> class AuthComponentTest extends CakeTestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<del> $this->_server = $_SERVER;
<del> $this->_env = $_ENV;
<del>
<ide> Configure::write('Security.salt', 'YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
<ide> Configure::write('Security.cipherSeed', 770011223369876);
<ide>
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> $_SERVER = $this->_server;
<del> $_ENV = $this->_env;
<ide>
<ide> TestAuthComponent::clearUser();
<ide> $this->Auth->Session->delete('Auth');
<ide><path>lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php
<ide> class EmailComponentTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<del> $this->_appEncoding = Configure::read('App.encoding');
<add> parent::setUp();
<add>
<ide> Configure::write('App.encoding', 'UTF-8');
<ide>
<ide> $this->Controller = new EmailTestController();
<del>
<ide> $this->Controller->Components->init($this->Controller);
<del>
<ide> $this->Controller->EmailTest->initialize($this->Controller, array());
<ide>
<ide> self::$sentDate = date(DATE_RFC2822);
<ide> public function setUp() {
<ide> ));
<ide> }
<ide>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> Configure::write('App.encoding', $this->_appEncoding);
<del> App::build();
<del> ClassRegistry::flush();
<del> }
<del>
<ide> /**
<ide> * testSendFormats method
<ide> *
<ide><path>lib/Cake/Test/Case/Controller/Component/RequestHandlerComponentTest.php
<ide> class RequestHandlerComponentTest extends CakeTestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<del> $this->_server = $_SERVER;
<ide> $this->_init();
<ide> }
<ide>
<ide> public function tearDown() {
<ide> if (!headers_sent()) {
<ide> header('Content-type: text/html'); //reset content type.
<ide> }
<del> $_SERVER = $this->_server;
<ide> call_user_func_array('Router::parseExtensions', $this->_extensions);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Controller/ComponentCollectionTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> unset($this->Components);
<ide> parent::tearDown();
<add> unset($this->Components);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Controller/ComponentTest.php
<ide> class ComponentTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->_pluginPaths = App::path('plugins');
<ide> App::build(array(
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<ide> ));
<ide> }
<ide>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> App::build();
<del> ClassRegistry::flush();
<del> }
<del>
<ide> /**
<ide> * test accessing inner components.
<ide> *
<ide><path>lib/Cake/Test/Case/Controller/ControllerTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> CakePlugin::unload();
<del> App::build();
<ide> parent::tearDown();
<add> CakePlugin::unload();
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Core/AppTest.php
<ide> class AppTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> CakePlugin::unload();
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Core/CakePluginTest.php
<ide> class CakePluginTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> App::build(array(
<ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
<ide> ), App::RESET);
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> App::build();
<add> parent::tearDown();
<ide> CakePlugin::unload();
<del> Configure::delete('CakePluginTest');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Core/ConfigureTest.php
<ide> class ConfigureTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<del> $this->_cacheDisable = Configure::read('Cache.disable');
<del> $this->_debug = Configure::read('debug');
<del>
<add> parent::setUp();
<ide> Configure::write('Cache.disable', true);
<ide> App::build();
<ide> App::objects('plugin', null, true);
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths')) {
<ide> unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths');
<ide> }
<ide> public function tearDown() {
<ide> if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.php')) {
<ide> unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.php');
<ide> }
<del> Configure::write('debug', $this->_debug);
<del> Configure::write('Cache.disable', $this->_cacheDisable);
<ide> Configure::drop('test');
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Core/ObjectTest.php
<ide> class ObjectTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> $this->object = new TestObject();
<ide> }
<ide>
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> App::build();
<add> parent::tearDown();
<ide> CakePlugin::unload();
<ide> unset($this->object);
<ide> }
<ide><path>lib/Cake/Test/Case/Error/ErrorHandlerTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> if ($this->_restoreError) {
<ide> restore_error_handler();
<ide> }
<del> parent::tearDown();
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Error/ExceptionRendererTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<add> parent::tearDown();
<ide> if ($this->_restoreError) {
<ide> restore_error_handler();
<ide> }
<del> parent::tearDown();
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Model/Behavior/AclBehaviorTest.php
<ide> class AclBehaviorTest extends CakeTestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> parent::setUp();
<ide> Configure::write('Acl.database', 'test');
<ide>
<ide> $this->Aco = new Aco();
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> ClassRegistry::flush();
<add> parent::tearDown();
<ide> unset($this->Aro, $this->Aco);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php
<ide> class TranslateBehaviorTest extends CakeTestCase {
<ide> 'core.translate_with_prefix'
<ide> );
<ide>
<del>/**
<del> * tearDown method
<del> *
<del> * @return void
<del> */
<del> public function tearDown() {
<del> ClassRegistry::flush();
<del> }
<del>
<ide> /**
<ide> * Test that count queries with conditions get the correct joins
<ide> *
<ide><path>lib/Cake/Test/Case/Utility/ObjectCollectionTest.php
<ide> public function setUp() {
<ide> * @return void
<ide> */
<ide> public function tearDown() {
<del> unset($this->Objects);
<ide> parent::tearDown();
<add> unset($this->Objects);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/TestSuite/CakeTestCase.php
<ide> public function setUp() {
<ide> if (empty($this->_configure)) {
<ide> $this->_configure = Configure::read();
<ide> }
<add> if (empty($this->_configure['App'])) {
<add> fwrite(STDERR, get_class($this) . '::' . $this->getName() . " did not have any configure vars\n");
<add> }
<ide> if (empty($this->_pathRestore)) {
<ide> $this->_pathRestore = App::paths();
<ide> }
<ide> public function tearDown() {
<ide> if (class_exists('ClassRegistry', false)) {
<ide> ClassRegistry::flush();
<ide> }
<del> Configure::clear();
<del> Configure::write($this->_configure);
<add> if (!empty($this->_configure)) {
<add> Configure::clear();
<add> Configure::write($this->_configure);
<add> }
<ide> if (isset($_GET['debug']) && $_GET['debug']) {
<ide> ob_flush();
<ide> } | 28 |
Javascript | Javascript | remove unused callback argument | d2ea4cf0ed82ff2ecc42f67e286249e9ec8fe049 | <ide><path>test/sequential/test-http-max-http-headers.js
<ide> const test2 = common.mustCall(() => {
<ide> client.resume();
<ide> });
<ide>
<del> finished(client, common.mustCall((err) => {
<add> finished(client, common.mustCall(() => {
<ide> server.close(test3);
<ide> }));
<ide> })); | 1 |
Text | Text | use https for codesniffer shield | fd4f8fc7d5009dfa5b0f366797cb2d2282449d8e | <ide><path>README.md
<ide> [](LICENSE.txt)
<ide> [](https://travis-ci.org/cakephp/cakephp)
<ide> [](https://coveralls.io/r/cakephp/cakephp?branch=master)
<del>[](http://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/)
<add>[](http://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/)
<ide> [](https://packagist.org/packages/cakephp/cakephp)
<ide> [](https://packagist.org/packages/cakephp/cakephp)
<ide> [](https://packagist.org/packages/cakephp/cakephp) | 1 |
PHP | PHP | add constants to check the type of association | f3b4fdef1a60cb471cebb15facc5835db942a400 | <ide><path>Cake/ORM/Association.php
<ide> abstract class Association {
<ide> */
<ide> const STRATEGY_SELECT = 'select';
<ide>
<add> const ONE_TO_ONE = 'oneToOne';
<add>
<add> const ONE_TO_MANY = 'oneToMany';
<add>
<add> const MANY_TO_MANY = 'manyToMany';
<add>
<ide> /**
<ide> * Name given to the association, it usually represents the alias
<ide> * assigned to the target associated table
<ide> public function transformRow($row) {
<ide> return $row;
<ide> }
<ide>
<add>/**
<add> * Get the relationship type.
<add> *
<add> * @return string Constant of either ONE_TO_ONE, MANY_TO_ONE, or MANY_TO_MANY.
<add> */
<add> public function type() {
<add> return self::ONE_TO_ONE;
<add> }
<add>
<ide> /**
<ide> * Returns a single or multiple conditions to be appended to the generated join
<ide> * clause for getting the results on the target table. If false is returned then
<ide><path>Cake/ORM/Association/BelongsToMany.php
<ide> public function attachTo(Query $query, array $options = []) {
<ide> ->attachTo($query, $options);
<ide> }
<ide>
<add>/**
<add> * Get the relationship type.
<add> *
<add> * @return string MANY_TO_ONE
<add> */
<add> public function type() {
<add> return self::MANY_TO_MANY;
<add> }
<add>
<ide> /**
<ide> * Return false as join conditions are defined in the junction table
<ide> *
<ide><path>Cake/ORM/Association/HasMany.php
<ide> public function save(Entity $entity, $options = []) {
<ide> return $entity;
<ide> }
<ide>
<add>/**
<add> * Get the relationship type.
<add> *
<add> * @return string MANY_TO_ONE
<add> */
<add> public function type() {
<add> return self::ONE_TO_MANY;
<add> }
<add>
<ide> } | 3 |
Python | Python | replace assignment with augmented assignment | 9f36d12693475031e9875256d6a9810dcd952889 | <ide><path>glances/plugins/glances_wifi.py
<ide> def msg_curse(self, args=None, max_width=None):
<ide> hotspotname = i['ssid']
<ide> # Add the encryption type (if it is available)
<ide> if i['encrypted']:
<del> hotspotname = hotspotname + ' {}'.format(i['encryption_type'])
<add> hotspotname += ' {}'.format(i['encryption_type'])
<ide> # Cut hotspotname if it is too long
<ide> if len(hotspotname) > ifname_max_width:
<ide> hotspotname = '_' + hotspotname[-ifname_max_width + 1:] | 1 |
Go | Go | remove collections package | 31f0a61a3dfabe363d08d4ff55e8a1efb29d84eb | <ide><path>pkg/collections/orderedintset.go
<del>package collections
<del>
<del>import (
<del> "sort"
<del> "sync"
<del>)
<del>
<del>// OrderedIntSet is a thread-safe sorted set and a stack.
<del>type OrderedIntSet struct {
<del> sync.Mutex
<del> set []int
<del>}
<del>
<del>// NewOrderedSet returns an initialized OrderedSet
<del>func NewOrderedIntSet() *OrderedIntSet {
<del> return &OrderedIntSet{}
<del>}
<del>
<del>// Push takes an int and adds it to the set. If the elem aready exists, it has no effect.
<del>func (s *OrderedIntSet) Push(elem int) {
<del> s.Lock()
<del> if len(s.set) == 0 {
<del> s.set = append(s.set, elem)
<del> s.Unlock()
<del> return
<del> }
<del>
<del> // Make sure the list is always sorted
<del> i := sort.SearchInts(s.set, elem)
<del> if i < len(s.set) && s.set[i] == elem {
<del> s.Unlock()
<del> return
<del> }
<del> s.set = append(s.set[:i], append([]int{elem}, s.set[i:]...)...)
<del> s.Unlock()
<del>}
<del>
<del>// Pop is an alias to PopFront()
<del>func (s *OrderedIntSet) Pop() int {
<del> return s.PopFront()
<del>}
<del>
<del>// Pop returns the first element from the list and removes it.
<del>// If the list is empty, it returns 0
<del>func (s *OrderedIntSet) PopFront() int {
<del> s.Lock()
<del> if len(s.set) == 0 {
<del> s.Unlock()
<del> return 0
<del> }
<del> ret := s.set[0]
<del> s.set = s.set[1:]
<del> s.Unlock()
<del> return ret
<del>}
<del>
<del>// PullBack retrieve the last element of the list.
<del>// The element is not removed.
<del>// If the list is empty, an empty element is returned.
<del>func (s *OrderedIntSet) PullBack() int {
<del> s.Lock()
<del> defer s.Unlock()
<del> if len(s.set) == 0 {
<del> return 0
<del> }
<del> return s.set[len(s.set)-1]
<del>}
<del>
<del>// Exists checks if the given element present in the list.
<del>func (s *OrderedIntSet) Exists(elem int) bool {
<del> s.Lock()
<del> if len(s.set) == 0 {
<del> s.Unlock()
<del> return false
<del> }
<del> i := sort.SearchInts(s.set, elem)
<del> res := i < len(s.set) && s.set[i] == elem
<del> s.Unlock()
<del> return res
<del>}
<del>
<del>// Remove removes an element from the list.
<del>// If the element is not found, it has no effect.
<del>func (s *OrderedIntSet) Remove(elem int) {
<del> s.Lock()
<del> if len(s.set) == 0 {
<del> s.Unlock()
<del> return
<del> }
<del> i := sort.SearchInts(s.set, elem)
<del> if i < len(s.set) && s.set[i] == elem {
<del> s.set = append(s.set[:i], s.set[i+1:]...)
<del> }
<del> s.Unlock()
<del>}
<ide><path>pkg/collections/orderedintset_test.go
<del>package collections
<del>
<del>import (
<del> "math/rand"
<del> "testing"
<del>)
<del>
<del>func BenchmarkPush(b *testing.B) {
<del> var testSet []int
<del> for i := 0; i < 1000; i++ {
<del> testSet = append(testSet, rand.Int())
<del> }
<del> s := NewOrderedIntSet()
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> for _, elem := range testSet {
<del> s.Push(elem)
<del> }
<del> }
<del>}
<del>
<del>func BenchmarkPop(b *testing.B) {
<del> var testSet []int
<del> for i := 0; i < 1000; i++ {
<del> testSet = append(testSet, rand.Int())
<del> }
<del> s := NewOrderedIntSet()
<del> for _, elem := range testSet {
<del> s.Push(elem)
<del> }
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> for j := 0; j < 1000; j++ {
<del> s.Pop()
<del> }
<del> }
<del>}
<del>
<del>func BenchmarkExist(b *testing.B) {
<del> var testSet []int
<del> for i := 0; i < 1000; i++ {
<del> testSet = append(testSet, rand.Intn(2000))
<del> }
<del> s := NewOrderedIntSet()
<del> for _, elem := range testSet {
<del> s.Push(elem)
<del> }
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> for j := 0; j < 1000; j++ {
<del> s.Exists(j)
<del> }
<del> }
<del>}
<del>
<del>func BenchmarkRemove(b *testing.B) {
<del> var testSet []int
<del> for i := 0; i < 1000; i++ {
<del> testSet = append(testSet, rand.Intn(2000))
<del> }
<del> s := NewOrderedIntSet()
<del> for _, elem := range testSet {
<del> s.Push(elem)
<del> }
<del> b.ResetTimer()
<del> for i := 0; i < b.N; i++ {
<del> for j := 0; j < 1000; j++ {
<del> s.Remove(j)
<del> }
<del> }
<del>} | 2 |
PHP | PHP | remove option that no longer works | 378a10673362eb36c3f392f0baea9c55fa1d988a | <ide><path>src/View/Helper/FormHelper.php
<ide> public function inputs($fields = null, $blacklist = null, $options = array()) {
<ide> *
<ide> * - `type` - Force the type of widget you want. e.g. `type => 'select'`
<ide> * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
<del> * - `div` - Either `false` to disable the div, or an array of options for the div.
<ide> * - `options` - For widgets that take options e.g. radio, select.
<ide> * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
<ide> * error and error messages). | 1 |
Ruby | Ruby | fix flakey tests in insert_all_test.rb | d890142dd9d2d5ed89c12eff027091ee80b581fd | <ide><path>activerecord/test/cases/insert_all_test.rb
<ide> def test_upsert_all_respects_updated_at_precision_when_touched_implicitly
<ide> skip unless supports_insert_on_duplicate_update? && supports_datetime_with_precision?
<ide>
<ide> Book.insert_all [{ id: 101, name: "Out of the Silent Planet", published_on: Date.new(1938, 4, 1), updated_at: 5.years.ago, updated_on: 5.years.ago }]
<del> Book.upsert_all [{ id: 101, name: "Out of the Silent Planet", published_on: Date.new(1938, 4, 8) }]
<ide>
<del> assert_not_predicate Book.find(101).updated_at.usec, :zero?, "updated_at should have sub-second precision"
<add> # A single upsert can occur exactly at the seconds boundary (when usec is naturally zero), so try multiple times.
<add> has_subsecond_precision = (1..100).any? do |i|
<add> Book.upsert_all [{ id: 101, name: "Out of the Silent Planet (Edition #{i})" }]
<add> Book.find(101).updated_at.usec > 0
<add> end
<add>
<add> assert has_subsecond_precision, "updated_at should have sub-second precision"
<ide> end
<ide>
<ide> def test_upsert_all_uses_given_updated_at_over_implicit_updated_at
<ide> def test_upsert_all_implicitly_sets_timestamps_on_create_when_model_record_times
<ide> def test_upsert_all_respects_created_at_precision_when_touched_implicitly
<ide> skip unless supports_insert_on_duplicate_update? && supports_datetime_with_precision?
<ide>
<del> Book.upsert_all [{ id: 101, name: "Out of the Silent Planet", published_on: Date.new(1938, 4, 8) }]
<add> # A single upsert can occur exactly at the seconds boundary (when usec is naturally zero), so try multiple times.
<add> has_subsecond_precision = (1..100).any? do |i|
<add> Book.upsert_all [{ id: 101 + i, name: "Out of the Silent Planet", published_on: Date.new(1938, 4, 1) }]
<add> Book.find(101 + i).created_at.usec > 0
<add> end
<ide>
<del> assert_not_predicate Book.find(101).created_at.usec, :zero?, "created_at should have sub-second precision"
<add> assert has_subsecond_precision, "created_at should have sub-second precision"
<ide> end
<ide>
<ide> def test_upsert_all_implicitly_sets_timestamps_on_update_when_model_record_timestamps_is_true | 1 |
Javascript | Javascript | improve yellowbox output format | eae4fe810f43266ee54a3bb89558621324d7a326 | <ide><path>Libraries/ReactNative/YellowBox.js
<ide> function sprintf(format, ...args) {
<ide> return format.replace(/%s/g, match => args[index++]);
<ide> }
<ide>
<del>function updateWarningMap(format, ...args): void {
<add>function updateWarningMap(...args): void {
<ide> if (console.disableYellowBox) {
<ide> return;
<ide> }
<ide>
<del> format = String(format);
<del> const argCount = (format.match(/%s/g) || []).length;
<del> const warning = [
<del> sprintf(format, ...args.slice(0, argCount)),
<del> ...args.slice(argCount).map(stringifySafe),
<del> ].join(' ');
<add> let warning;
<add> if (typeof args[0] === 'string') {
<add> const [format, ...formatArgs] = args;
<add> const argCount = (format.match(/%s/g) || []).length;
<add> warning = [
<add> sprintf(format, ...formatArgs.slice(0, argCount).map(stringifySafe)),
<add> ...formatArgs.slice(argCount).map(stringifySafe),
<add> ].join(' ');
<add> } else {
<add> warning = args.map(stringifySafe).join(' ');
<add> }
<ide>
<ide> if (warning.startsWith('(ADVICE)')) {
<ide> return; | 1 |
Javascript | Javascript | add meta.fixable to fixable lint rules | ee0b44fd93fa695e902a725cbe3da2f18c032c55 | <ide><path>tools/eslint-rules/async-iife-no-unused-result.js
<ide> const message =
<ide> '(e.g. with `.then(common.mustCall())`)';
<ide>
<ide> module.exports = {
<add> meta: {
<add> fixable: 'code'
<add> },
<ide> create: function(context) {
<ide> let hasCommonModule = false;
<ide> return {
<ide><path>tools/eslint-rules/crypto-check.js
<ide> module.exports = function(context) {
<ide> 'Program:exit': () => reportIfMissingCheck()
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>};
<ide><path>tools/eslint-rules/eslint-check.js
<ide> module.exports = function(context) {
<ide> 'Program:exit': () => reportIfMissing(context)
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>};
<ide><path>tools/eslint-rules/inspector-check.js
<ide> module.exports = function(context) {
<ide> 'Program:exit': () => reportIfMissing(context)
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>};
<ide><path>tools/eslint-rules/lowercase-name-for-primitive.js
<ide> module.exports = function(context) {
<ide> [astSelector]: (node) => checkNamesArgument(node)
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>};
<ide><path>tools/eslint-rules/non-ascii-character.js
<ide> module.exports = (context) => {
<ide> Program: (node) => reportIfError(node, context.getSourceCode())
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>};
<ide><path>tools/eslint-rules/prefer-assert-iferror.js
<ide> const utils = require('./rules-utils.js');
<ide>
<ide> module.exports = {
<add> meta: {
<add> fixable: 'code'
<add> },
<ide> create(context) {
<ide> const sourceCode = context.getSourceCode();
<ide> let assertImported = false;
<ide><path>tools/eslint-rules/prefer-assert-methods.js
<ide> module.exports = function(context) {
<ide> }
<ide> };
<ide> };
<add>
<add>module.exports.meta = {
<add> fixable: 'code'
<add>}; | 8 |
PHP | PHP | build http queries with rfc3986 | ba6535590535a089473a78509d6814cf185682ca | <ide><path>src/Illuminate/Http/Request.php
<ide> public function fullUrlWithQuery(array $query)
<ide> $question = $this->getBaseUrl().$this->getPathInfo() == '/' ? '/?' : '?';
<ide>
<ide> return count($this->query()) > 0
<del> ? $this->url().$question.http_build_query(array_merge($this->query(), $query))
<del> : $this->fullUrl().$question.http_build_query($query);
<add> ? $this->url().$question.http_build_query(array_merge($this->query(), $query), null, '&', PHP_QUERY_RFC3986)
<add> : $this->fullUrl().$question.http_build_query($query, null, '&', PHP_QUERY_RFC3986);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Pagination/AbstractPaginator.php
<ide> public function url($page)
<ide>
<ide> return $this->path
<ide> .(Str::contains($this->path, '?') ? '&' : '?')
<del> .http_build_query($parameters, '', '&')
<add> .http_build_query($parameters, null, '&', PHP_QUERY_RFC3986)
<ide> .$this->buildFragment();
<ide> }
<ide>
<ide><path>src/Illuminate/Redis/Connectors/PhpRedisConnector.php
<ide> protected function buildClusterConnectionString(array $server)
<ide> {
<ide> return $server['host'].':'.$server['port'].'?'.http_build_query(Arr::only($server, [
<ide> 'database', 'password', 'prefix', 'read_timeout',
<del> ]));
<add> ]), null, '&', PHP_QUERY_RFC3986);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/RouteUrlGenerator.php
<ide> protected function getRouteQueryString(array $parameters)
<ide> }
<ide>
<ide> $query = http_build_query(
<del> $keyed = $this->getStringParameters($parameters)
<add> $keyed = $this->getStringParameters($parameters),
<add> null,
<add> '&',
<add> PHP_QUERY_RFC3986
<ide> );
<ide>
<ide> // Lastly, if there are still parameters remaining, we will fetch the numeric
<ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> public function temporarySignedRoute($name, $expiration, $parameters = [])
<ide> public function hasValidSignature(Request $request)
<ide> {
<ide> $original = rtrim($request->url().'?'.http_build_query(
<del> Arr::except($request->query(), 'signature')
<add> Arr::except($request->query(), 'signature'),
<add> null,
<add> '&',
<add> PHP_QUERY_RFC3986
<ide> ), '?');
<ide>
<ide> $expires = Arr::get($request->query(), 'expires');
<ide><path>tests/Http/HttpRequestTest.php
<ide> public function testFullUrlMethod()
<ide>
<ide> $request = Request::create('http://foo.com/foo/bar/?name=taylor', 'GET');
<ide> $this->assertEquals('http://foo.com/foo/bar?name=graham', $request->fullUrlWithQuery(['name' => 'graham']));
<add>
<add> $request = Request::create('https://foo.com', 'GET');
<add> $this->assertEquals('https://foo.com?key=value%20with%20spaces', $request->fullUrlWithQuery(['key' => 'value with spaces']));
<ide> }
<ide>
<ide> public function testIsMethod()
<ide><path>tests/Pagination/LengthAwarePaginatorTest.php
<ide> public function testLengthAwarePaginatorCanGenerateUrlsWithoutTrailingSlashes()
<ide> $this->assertEquals('http://website.com/test?foo=1',
<ide> $this->p->url($this->p->currentPage() - 2));
<ide> }
<add>
<add> public function testLengthAwarePaginatorCorrectlyGenerateUrlsWithQueryAndSpaces()
<add> {
<add> $this->p->setPath('http://website.com?key=value%20with%20spaces');
<add> $this->p->setPageName('foo');
<add>
<add> $this->assertEquals('http://website.com?key=value%20with%20spaces&foo=2',
<add> $this->p->url($this->p->currentPage()));
<add> }
<ide> } | 7 |
Python | Python | fix a bug in evaluating accuracy | fefb70b217af9d9a5de780873db218fffaaf9544 | <ide><path>examples/mnist_siamese_graph.py
<ide> def create_base_network(input_dim):
<ide> def compute_accuracy(predictions, labels):
<ide> '''Compute classification accuracy with a fixed threshold on distances.
<ide> '''
<del> return labels[predictions.ravel() < 0.5].mean()
<add> return np.mean(labels == (predictions.ravel() > 0.5))
<ide>
<ide>
<ide> # the data, shuffled and split between train and test sets | 1 |
Ruby | Ruby | add clt clang for 10.13 | 08cee5a0d5dfb1bcdd71630a43b2218fc11142fe | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide> # on the older supported platform for that Xcode release, i.e there's no
<ide> # CLT package for 10.11 that contains the Clang version from Xcode 8.
<ide> case MacOS.version
<add> when "10.13" then "900.0.22.8"
<ide> when "10.12" then "802.0.42"
<ide> when "10.11" then "800.0.42.1"
<ide> when "10.10" then "700.1.81" | 1 |
Ruby | Ruby | make part of bash error regex optional | 1a32ba3d2bdc43d38d7aaece9ea87947745a4d87 | <ide><path>Library/Homebrew/test/system_command_spec.rb
<ide> it "unsets them" do
<ide> expect {
<ide> command.run!
<del> }.to raise_error(/C: parameter null or not set/)
<add> }.to raise_error(/C: parameter (null or )?not set/)
<ide> end
<ide> end
<ide> | 1 |
Python | Python | resolve line-too-long in models | f0fc6f798937a7a5fdab469c0f16bdde7cfc4ccd | <ide><path>keras/models/cloning.py
<ide> def _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer):
<ide> to build the model upon. If not provided,
<ide> placeholders will be created.
<ide> layer_fn: callable to be applied on non-input layers in the model. By
<del> default it clones the layer. Another example is to preserve the layer
<del> to share the weights. This is required when we create a per-replica
<del> copy of the model with distribution strategy; we want the weights to
<del> be shared but still feed inputs separately so we create new input
<del> layers.
<add> default it clones the layer. Another example is to preserve the
<add> layer to share the weights. This is required when we create a
<add> per-replica copy of the model with distribution strategy; we want
<add> the weights to be shared but still feed inputs separately so we
<add> create new input layers.
<ide>
<ide> Returns:
<ide> An instance of `Model` reproducing the behavior
<ide> def _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer):
<ide> for i, input_tensor in enumerate(input_tensors):
<ide> original_input_layer = model._input_layers[i]
<ide>
<del> # Cache input layer. Create a new layer if the tensor is originally not
<del> # from a Keras layer.
<add> # Cache input layer. Create a new layer if the tensor is originally
<add> # not from a Keras layer.
<ide> if not backend.is_keras_tensor(input_tensor):
<ide> name = original_input_layer.name
<ide> input_tensor = Input(
<ide> def _clone_layers_and_model_config(model, input_layers, layer_fn):
<ide>
<ide> Args:
<ide> model: A Functional model.
<del> input_layers: Dictionary mapping input layers in `model` to new input layers
<add> input_layers: Dictionary mapping input layers in `model` to new input
<add> layers.
<ide> layer_fn: Function used to clone all non-input layers.
<ide>
<ide> Returns:
<ide> def _remove_ancillary_layers(model, layer_map, layers):
<ide> layers: A list of all layers.
<ide>
<ide> Returns:
<del> Two lists of layers: (1) `layers` with the ancillary layers removed, and (2)
<del> the ancillary layers.
<add> Two lists of layers: (1) `layers` with the ancillary layers removed, and
<add> (2) the ancillary layers.
<ide> """
<ide> ancillary_layers = [] # Additional layers for computing losses and metrics.
<ide> if not model._is_graph_network:
<ide> def _clone_sequential_model(model, input_tensors=None, layer_fn=_clone_layer):
<ide> to build the model upon. If not provided,
<ide> placeholders will be created.
<ide> layer_fn: callable to be applied on non-input layers in the model. By
<del> default it clones the layer. Another example is to preserve the layer
<del> to share the weights. This is required when we create a per-replica
<del> copy of the model with distribution strategy; we want the weights to
<del> be shared but still feed inputs separately so we create new input
<del> layers.
<add> default it clones the layer. Another example is to preserve the
<add> layer to share the weights. This is required when we create a
<add> per-replica copy of the model with distribution strategy; we want
<add> the weights to be shared but still feed inputs separately so we
<add> create new input layers.
<ide>
<ide> Returns:
<ide> An instance of `Sequential` reproducing the behavior
<ide> def _clone_sequential_model(model, input_tensors=None, layer_fn=_clone_layer):
<ide> cloned_model = Sequential(layers=layers, name=model.name)
<ide> elif len(generic_utils.to_list(input_tensors)) != 1:
<ide> raise ValueError(
<del> "To clone a `Sequential` model, we expect at most one tensor as part "
<del> f"of `input_tensors`. Received: input_tensors={input_tensors}"
<add> "To clone a `Sequential` model, we expect at most one tensor as "
<add> f"part of `input_tensors`. Received: input_tensors={input_tensors}"
<ide> )
<ide> else:
<ide> # Overwrite the original model's input layer.
<ide> def _clone_sequential_model(model, input_tensors=None, layer_fn=_clone_layer):
<ide> tensor_map = {} # Maps tensors from `model` to those in `cloned_model`.
<ide> for depth, cloned_nodes in cloned_model._nodes_by_depth.items():
<ide> nodes = model._nodes_by_depth[depth]
<del> # This should be safe in a Sequential model. In an arbitrary network, you
<del> # need to sort using the outbound layer of the node as a key.
<add> # This should be safe in a Sequential model. In an arbitrary network,
<add> # you need to sort using the outbound layer of the node as a key.
<ide> for cloned_node, node in zip(cloned_nodes, nodes):
<ide> if isinstance(cloned_node.output_tensors, list):
<ide> for j, output_tensor in enumerate(cloned_node.output_tensors):
<ide> def clone_model(model, input_tensors=None, clone_function=None):
<ide> to build the model upon. If not provided,
<ide> new `Input` objects will be created.
<ide> clone_function: Callable to be used to clone each layer in the target
<del> model (except `InputLayer` instances). It takes as argument the layer
<del> instance to be cloned, and returns the corresponding layer instance to
<del> be used in the model copy. If unspecified, this callable defaults to
<del> the following serialization/deserialization function:
<add> model (except `InputLayer` instances). It takes as argument the
<add> layer instance to be cloned, and returns the corresponding layer
<add> instance to be used in the model copy. If unspecified, this callable
<add> defaults to the following serialization/deserialization function:
<ide> `lambda layer: layer.__class__.from_config(layer.get_config())`.
<ide> By passing a custom callable, you can customize your copy of the
<del> model, e.g. by wrapping certain layers of interest (you might want to
<del> replace all `LSTM` instances with equivalent
<add> model, e.g. by wrapping certain layers of interest (you might want
<add> to replace all `LSTM` instances with equivalent
<ide> `Bidirectional(LSTM(...))` instances, for example).
<ide>
<ide> Returns:
<ide> def clone_model(model, input_tensors=None, clone_function=None):
<ide> def _in_place_subclassed_model_reset(model):
<ide> """Substitute for model cloning that works for subclassed models.
<ide>
<del> Subclassed models cannot be cloned because their topology is not serializable.
<del> To "instantiate" an identical model in a new TF graph, we reuse the original
<del> model object, but we clear its state.
<add> Subclassed models cannot be cloned because their topology is not
<add> serializable. To "instantiate" an identical model in a new TF graph, we
<add> reuse the original model object, but we clear its state.
<ide>
<ide> After calling this function on a model instance, you can use the model
<ide> instance as if it were a model clone (in particular you can use it in a new
<ide> def _in_place_subclassed_model_reset(model):
<ide> "_compile_metric_functions",
<ide> "_output_loss_metrics",
<ide> ):
<del> # Handle case: list/tuple of layers (also tracked by the Network API).
<add> # Handle case: list/tuple of layers (also tracked by the Network
<add> # API).
<ide> if value and all(isinstance(val, Layer) for val in value):
<ide> raise ValueError(
<ide> "We do not support the use of list-of-layers "
<ide> def _in_place_subclassed_model_reset(model):
<ide> for layer in original_layers: # We preserve layer order.
<ide> config = layer.get_config()
<ide> # This will not work for nested subclassed models used as layers.
<del> # This would be theoretically possible to support, but would add complexity.
<del> # Only do it if users complain.
<add> # This would be theoretically possible to support, but would add
<add> # complexity. Only do it if users complain.
<ide> if isinstance(layer, training.Model) and not layer._is_graph_network:
<ide> raise ValueError(
<ide> "We do not support the use of nested subclassed models "
<ide> def _reset_build_compile_trackers(model):
<ide> def in_place_subclassed_model_state_restoration(model):
<ide> """Restores the original state of a model after it was "reset".
<ide>
<del> This undoes this action of `_in_place_subclassed_model_reset`, which is called
<del> in `clone_and_build_model` if `in_place_reset` is set to True.
<add> This undoes this action of `_in_place_subclassed_model_reset`, which is
<add> called in `clone_and_build_model` if `in_place_reset` is set to True.
<ide>
<ide> Args:
<ide> model: Instance of a Keras model created via subclassing, on which
<ide> def in_place_subclassed_model_state_restoration(model):
<ide> hasattr(model, "_original_attributes_cache")
<ide> and model._original_attributes_cache is not None
<ide> ):
<del> # Models have sticky attribute assignment, so we want to be careful to add
<del> # back the previous attributes and track Layers by their original names
<del> # without adding dependencies on "utility" attributes which Models exempt
<del> # when they're constructed.
<add> # Models have sticky attribute assignment, so we want to be careful to
<add> # add back the previous attributes and track Layers by their original
<add> # names without adding dependencies on "utility" attributes which Models
<add> # exempt when they're constructed.
<ide> setattr_tracking = model._setattr_tracking
<ide> model._setattr_tracking = False
<ide> model._self_tracked_trackables = []
<ide> def clone_and_build_model(
<ide> This function can be run in the same graph or in a separate graph from the
<ide> model. When using a separate graph, `in_place_reset` must be `False`.
<ide>
<del> Note that, currently, the clone produced from this function may not work with
<del> TPU DistributionStrategy. Try at your own risk.
<add> Note that, currently, the clone produced from this function may not work
<add> with TPU DistributionStrategy. Try at your own risk.
<ide>
<ide> Args:
<ide> model: `tf.keras.Model` object. Can be Functional, Sequential, or
<ide> sub-classed.
<ide> input_tensors: Optional list or dictionary of input tensors to build the
<ide> model upon. If not provided, placeholders will be created.
<del> target_tensors: Optional list of target tensors for compiling the model. If
<del> not provided, placeholders will be created.
<add> target_tensors: Optional list of target tensors for compiling the model.
<add> If not provided, placeholders will be created.
<ide> custom_objects: Optional dictionary mapping string names to custom classes
<ide> or functions.
<ide> compile_clone: Boolean, whether to compile model clone (default `True`).
<ide> def clone_and_build_model(
<ide> this argument must be set to `True` (default `False`). To restore the
<ide> original model, use the function
<ide> `in_place_subclassed_model_state_restoration(model)`.
<del> optimizer_iterations: An iterations variable that will be incremented by the
<del> optimizer if the clone is compiled. This argument is used when a Keras
<del> model is cloned into an Estimator model function, because Estimators
<del> create their own global step variable.
<add> optimizer_iterations: An iterations variable that will be incremented by
<add> the optimizer if the clone is compiled. This argument is used when a
<add> Keras model is cloned into an Estimator model function, because
<add> Estimators create their own global step variable.
<ide> optimizer_config: Optimizer config dictionary or list of dictionary
<ide> returned from `get_config()`. This argument should be defined if
<ide> `clone_and_build_model` is called in a different graph or session from
<ide> def clone_and_build_model(
<ide> orig_optimizer = model.optimizer
<ide> if compile_clone and not orig_optimizer:
<ide> raise ValueError(
<del> "Error when cloning model: `compile_clone` was set to True, but the "
<del> f"original model has not been compiled. Received: model={model}"
<add> "Error when cloning model: `compile_clone` was set to True, but "
<add> f"the original model has not been compiled. Received: model={model}"
<ide> )
<ide>
<ide> if compile_clone:
<ide> def clone_and_build_model(
<ide> )
<ide> else:
<ide> try:
<del> # Prefer cloning the model if serial/deserial logic is implemented for
<del> # subclassed model.
<add> # Prefer cloning the model if serial/deserial logic is
<add> # implemented for subclassed model.
<ide> clone = model.__class__.from_config(model.get_config())
<ide> except NotImplementedError:
<ide> logging.warning(
<ide> def clone_and_build_model(
<ide> if not in_place_reset:
<ide> raise ValueError(
<ide> f"This model ({model}) is a subclassed model. "
<del> "Such a model cannot be cloned, but there is a workaround where "
<del> "the model is reset in-place. To use this, please set the "
<del> "argument `in_place_reset` to `True`. This will reset the "
<del> "attributes in the original model. To restore the attributes, "
<del> "call `in_place_subclassed_model_state_restoration(model)`."
<add> "Such a model cannot be cloned, but there is a "
<add> "workaround where the model is reset in-place. "
<add> "To use this, please set the "
<add> "argument `in_place_reset` to `True`. This will reset "
<add> "the attributes in the original model. "
<add> "To restore the attributes, call "
<add> "`in_place_subclassed_model_state_restoration(model)`."
<ide> )
<ide> clone = model
<ide> _in_place_subclassed_model_reset(clone)
<ide> def clone_and_build_model(
<ide> orig_optimizer[0].__class__.from_config(optimizer_config)
<ide> ]
<ide> else:
<del> # optimizer config is list of dict, same order as orig_optimizer.
<add> # optimizer config is list of dict, same order as
<add> # orig_optimizer.
<ide> optimizer = [
<ide> opt.__class__.from_config(opt_config)
<ide> for (opt, opt_config) in zip(
<ide><path>keras/models/cloning_test.py
<ide> class TestModel(keras.Model):
<ide> """A model subclass."""
<ide>
<ide> def __init__(self, n_outputs=4, trainable=True):
<del> """A test class with one dense layer and number of outputs as a variable."""
<add> """A test class with one dense layer and number of outputs as a
<add> variable."""
<ide> super().__init__()
<ide> self.layer1 = keras.layers.Dense(n_outputs)
<ide> self.n_outputs = tf.Variable(n_outputs, trainable=trainable)
<ide> def test_clone_sequential_model(
<ide> )[0],
<ide> keras.layers.InputLayer,
<ide> )
<del> # The new models inputs should have the properties of the new input tensor
<add> # The new models inputs should have the properties of the new input
<add> # tensor
<ide> if tf.__internal__.tf2.enabled():
<ide> # In TF1, the new model will be a:0
<ide> self.assertEqual(new_model.input_names[0], input_a.name)
<ide> def test_clone_sequential_model(
<ide> # On top of new, non-Keras tensor -- clone model should always have an
<ide> # InputLayer.
<ide> if not tf.executing_eagerly():
<del> # TODO(b/121277734):Skip Eager contexts, as Input() layers raise an error
<del> # saying they should not be used with EagerTensors
<add> # TODO(b/121277734):Skip Eager contexts, as Input() layers raise an
<add> # error saying they should not be used with EagerTensors
<ide> input_a = keras.backend.variable(val_a)
<ide> new_model = clone_fn(model, input_tensors=input_a)
<ide> self.assertIsInstance(
<ide> def test_clone_functional_model(self, share_weights):
<ide>
<ide> # On top of new, non-Keras tensors
<ide> if not tf.executing_eagerly():
<del> # TODO(b/121277734):Skip Eager contexts, as Input() layers raise an error
<del> # saying they should not be used with EagerTensors
<add> # TODO(b/121277734):Skip Eager contexts, as Input() layers raise an
<add> # error saying they should not be used with EagerTensors
<ide> input_a = keras.backend.variable(val_a)
<ide> input_b = keras.backend.variable(val_b)
<ide> new_model = clone_fn(model, input_tensors=[input_a, input_b])
<ide><path>keras/models/sharpness_aware_minimization.py
<ide> class SharpnessAwareMinimization(Model):
<ide> """Sharpness aware minimization (SAM) training flow.
<ide>
<ide> Sharpness-aware minimization (SAM) is a technique that improves the model
<del> generalization and provides robustness to label noise. Mini-batch splitting is
<del> proven to improve the SAM's performance, so users can control how mini batches
<del> are split via setting the `num_batch_splits` argument.
<add> generalization and provides robustness to label noise. Mini-batch splitting
<add> is proven to improve the SAM's performance, so users can control how mini
<add> batches are split via setting the `num_batch_splits` argument.
<ide>
<ide> Args:
<ide> model: `tf.keras.Model` instance. The inner model that does the
<ide> def train_step(self, data):
<ide> for (variable, epsilon_w) in zip(
<ide> trainable_variables, epsilon_w_cache
<ide> ):
<del> # Restore the variable to its original value before `apply_gradients()`.
<add> # Restore the variable to its original value before
<add> # `apply_gradients()`.
<ide> self._distributed_apply_epsilon_w(
<ide> variable, -epsilon_w, tf.distribute.get_strategy()
<ide> ) | 3 |
Javascript | Javascript | evaluate arguments in function's scope | f22fffdd4709c069ca00401854dad898cdf2b22e | <ide><path>lib/Parser.js
<ide> class Parser extends Tapable {
<ide> }
<ide>
<ide> walkForInStatement(statement) {
<del> if (statement.left.type === "VariableDeclaration")
<add> if (statement.left.type === "VariableDeclaration") {
<ide> this.walkVariableDeclaration(statement.left);
<del> else this.walkPattern(statement.left);
<add> } else {
<add> this.walkPattern(statement.left);
<add> }
<ide> this.walkExpression(statement.right);
<ide> this.walkStatement(statement.body);
<ide> }
<ide>
<ide> prewalkForOfStatement(statement) {
<del> if (statement.left.type === "VariableDeclaration")
<add> if (statement.left.type === "VariableDeclaration") {
<ide> this.prewalkVariableDeclaration(statement.left);
<add> }
<ide> this.prewalkStatement(statement.body);
<ide> }
<ide>
<ide> walkForOfStatement(statement) {
<del> if (statement.left.type === "VariableDeclaration")
<add> if (statement.left.type === "VariableDeclaration") {
<ide> this.walkVariableDeclaration(statement.left);
<del> else this.walkPattern(statement.left);
<add> } else {
<add> this.walkPattern(statement.left);
<add> }
<ide> this.walkExpression(statement.right);
<ide> this.walkStatement(statement.body);
<ide> }
<ide> class Parser extends Tapable {
<ide> walkFunctionDeclaration(statement) {
<ide> const wasTopLevel = this.scope.topLevelScope;
<ide> this.scope.topLevelScope = false;
<del> for (const param of statement.params) this.walkPattern(param);
<ide> this.inScope(statement.params, () => {
<add> for (const param of statement.params) {
<add> this.walkPattern(param);
<add> }
<ide> if (statement.body.type === "BlockStatement") {
<ide> this.detectStrictMode(statement.body.body);
<ide> this.prewalkStatement(statement.body);
<ide> class Parser extends Tapable {
<ide> }
<ide>
<ide> walkExpressions(expressions) {
<del> for (
<del> let expressionsIndex = 0, len = expressions.length;
<del> expressionsIndex < len;
<del> expressionsIndex++
<del> ) {
<del> const expression = expressions[expressionsIndex];
<del> if (expression) this.walkExpression(expression);
<add> for (const expression of expressions) {
<add> if (expression) {
<add> this.walkExpression(expression);
<add> }
<ide> }
<ide> }
<ide>
<ide> class Parser extends Tapable {
<ide> walkFunctionExpression(expression) {
<ide> const wasTopLevel = this.scope.topLevelScope;
<ide> this.scope.topLevelScope = false;
<del> for (const param of expression.params) this.walkPattern(param);
<ide> this.inScope(expression.params, () => {
<add> for (const param of expression.params) {
<add> this.walkPattern(param);
<add> }
<ide> if (expression.body.type === "BlockStatement") {
<ide> this.detectStrictMode(expression.body.body);
<ide> this.prewalkStatement(expression.body);
<ide> class Parser extends Tapable {
<ide> }
<ide>
<ide> walkArrowFunctionExpression(expression) {
<del> for (const param of expression.params) this.walkPattern(param);
<ide> this.inScope(expression.params, () => {
<add> for (const param of expression.params) {
<add> this.walkPattern(param);
<add> }
<ide> if (expression.body.type === "BlockStatement") {
<ide> this.detectStrictMode(expression.body.body);
<ide> this.prewalkStatement(expression.body);
<ide> class Parser extends Tapable {
<ide> if (functionExpression.body.type === "BlockStatement") {
<ide> this.prewalkStatement(functionExpression.body);
<ide> this.walkStatement(functionExpression.body);
<del> } else this.walkExpression(functionExpression.body);
<add> } else {
<add> this.walkExpression(functionExpression.body);
<add> }
<ide> });
<ide> this.scope.topLevelScope = wasTopLevel;
<ide> }
<ide> class Parser extends Tapable {
<ide>
<ide> this.scope.renames.set("this", null);
<ide>
<del> for (
<del> let paramIndex = 0, len = params.length;
<del> paramIndex < len;
<del> paramIndex++
<del> ) {
<del> const param = params[paramIndex];
<del>
<add> for (const param of params) {
<ide> if (typeof param !== "string") {
<ide> this.enterPattern(param, param => {
<ide> this.scope.renames.set(param, null); | 1 |
Ruby | Ruby | remove unecesarry exception variable | 2b9e04b6f9b21087a8b44c4b3758d0b3ae1e7e12 | <ide><path>activestorage/lib/active_storage/service/azure_storage_service.rb
<ide> def upload(key, io, checksum: nil)
<ide> instrument :upload, key, checksum: checksum do
<ide> begin
<ide> blobs.create_block_blob(container, key, io, content_md5: checksum)
<del> rescue Azure::Core::Http::HTTPError => e
<add> rescue Azure::Core::Http::HTTPError
<ide> raise ActiveStorage::IntegrityError
<ide> end
<ide> end | 1 |
Ruby | Ruby | use file.dirname in most cleaner tests | 0d818645971a59527c4205408c9f2f49afb12a6e | <ide><path>Library/Homebrew/test/cleaner_spec.rb
<ide> it "removes '.la' files" do
<ide> file = f.lib/"foo.la"
<ide>
<del> f.lib.mkpath
<add> file.dirname.mkpath
<ide> touch file
<ide>
<ide> cleaner.clean
<ide> it "removes 'perllocal' files" do
<ide> file = f.lib/"perl5/darwin-thread-multi-2level/perllocal.pod"
<ide>
<del> (f.lib/"perl5/darwin-thread-multi-2level").mkpath
<add> file.dirname.mkpath
<ide> touch file
<ide>
<ide> cleaner.clean
<ide> it "removes '.packlist' files" do
<ide> file = f.lib/"perl5/darwin-thread-multi-2level/auto/test/.packlist"
<ide>
<del> (f.lib/"perl5/darwin-thread-multi-2level/auto/test").mkpath
<add> file.dirname.mkpath
<ide> touch file
<ide>
<ide> cleaner.clean
<ide> it "removes 'charset.alias' files" do
<ide> file = f.lib/"charset.alias"
<ide>
<del> f.lib.mkpath
<add> file.dirname.mkpath
<ide> touch file
<ide>
<ide> cleaner.clean | 1 |
Python | Python | use apache.spark provider without kubernetes | f9c9e9c38f444a39987478f3d1a262db909de8c4 | <ide><path>airflow/providers/apache/spark/hooks/spark_submit.py
<ide>
<ide> try:
<ide> from airflow.kubernetes import kube_client
<del>except ImportError:
<add>except (ImportError, NameError):
<ide> pass
<ide>
<ide> | 1 |
Text | Text | add v3.28.0-beta.5 to changelog | 55d012c49bb6af87b9f0841457c1380f0006292d | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.28.0-beta.5 (June 14, 2021)
<add>
<add>- [#19597](https://github.com/emberjs/ember.js/pull/19597) [BUGFIX] Fix `<LinkTo>` with nested children
<add>
<ide> ### v3.28.0-beta.4 (June 7, 2021)
<ide>
<ide> - [#19586](https://github.com/emberjs/ember.js/pull/19586) [BUGFIX] Fix Embroider compatibility | 1 |
Go | Go | simplify code to make function more readable | a6379399818402be12b9d29e343d348031cbe62f | <ide><path>daemon/exec.go
<ide> func (d *Daemon) ExecExists(name string) (bool, error) {
<ide> // with the exec instance is stopped or paused, it will return an error.
<ide> func (d *Daemon) getExecConfig(name string) (*exec.Config, error) {
<ide> ec := d.execCommands.Get(name)
<add> if ec == nil {
<add> return nil, errExecNotFound(name)
<add> }
<ide>
<ide> // If the exec is found but its container is not in the daemon's list of
<ide> // containers then it must have been deleted, in which case instead of
<ide> // saying the container isn't running, we should return a 404 so that
<ide> // the user sees the same error now that they will after the
<ide> // 5 minute clean-up loop is run which erases old/dead execs.
<del>
<del> if ec != nil {
<del> if container := d.containers.Get(ec.ContainerID); container != nil {
<del> if !container.IsRunning() {
<del> return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
<del> }
<del> if container.IsPaused() {
<del> return nil, errExecPaused(container.ID)
<del> }
<del> if container.IsRestarting() {
<del> return nil, errContainerIsRestarting(container.ID)
<del> }
<del> return ec, nil
<del> }
<add> container := d.containers.Get(ec.ContainerID)
<add> if container == nil {
<add> return nil, containerNotFound(name)
<ide> }
<del>
<del> return nil, errExecNotFound(name)
<add> if !container.IsRunning() {
<add> return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
<add> }
<add> if container.IsPaused() {
<add> return nil, errExecPaused(container.ID)
<add> }
<add> if container.IsRestarting() {
<add> return nil, errContainerIsRestarting(container.ID)
<add> }
<add> return ec, nil
<ide> }
<ide>
<ide> func (d *Daemon) unregisterExecCommand(container *container.Container, execConfig *exec.Config) { | 1 |
PHP | PHP | resolve ambiguous column names for sqlite | 010bbc6764f26576a4c42f47aa4a68ca14d9f213 | <ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php
<ide> public function testJoinsAfterFind() {
<ide>
<ide> $User->Article = $Article;
<ide> $User->find('first', array(
<del> 'fields' => array('User.*', 'Article.*'),
<add> 'fields' => array(
<add> 'Article.id',
<add> 'Article.user_id',
<add> 'Article.title',
<add> 'Article.body',
<add> 'Article.published',
<add> 'Article.created',
<add> 'Article.updated'
<add> ),
<ide> 'conditions' => array('User.id' => 1),
<ide> 'recursive' => -1,
<ide> 'joins' => array( | 1 |
Javascript | Javascript | use passive flag to schedule onpostcommit | 8b2d3783e58d1acea53428a10d2035a8399060fe | <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.new.js
<ide> import {
<ide> ContentReset,
<ide> DidCapture,
<ide> Update,
<add> Passive,
<ide> Ref,
<ide> Deletion,
<ide> ForceUpdateForLegacySuspense,
<ide> function updateProfiler(
<ide> renderLanes: Lanes,
<ide> ) {
<ide> if (enableProfilerTimer) {
<del> workInProgress.flags |= Update;
<add> // TODO: Only call onRender et al if subtree has effects
<add> workInProgress.flags |= Update | Passive;
<ide>
<ide> // Reset effect durations for the next eventual effect phase.
<ide> // These are reset during render to allow the DevTools commit hook a chance to read them,
<ide> function beginWork(
<ide> case Profiler:
<ide> if (enableProfilerTimer) {
<ide> // Profiler should only call onRender when one of its descendants actually rendered.
<add> // TODO: Only call onRender et al if subtree has effects
<ide> const hasChildWork = includesSomeLane(
<ide> renderLanes,
<ide> workInProgress.childLanes,
<ide> );
<ide> if (hasChildWork) {
<del> workInProgress.flags |= Update;
<add> workInProgress.flags |= Passive | Update;
<ide> }
<ide>
<ide> // Reset effect durations for the next eventual effect phase.
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> import {
<ide> captureCommitPhaseError,
<ide> resolveRetryWakeable,
<ide> markCommitTimeOfFallback,
<del> enqueuePendingPassiveProfilerEffect,
<ide> schedulePassiveEffectCallback,
<ide> } from './ReactFiberWorkLoop.new';
<ide> import {
<ide> function commitHookEffectListMount2(fiber: Fiber): void {
<ide> }
<ide> }
<ide>
<del>export function commitPassiveEffectDurations(
<add>function commitProfilerPassiveEffect(
<ide> finishedRoot: FiberRoot,
<ide> finishedWork: Fiber,
<ide> ): void {
<ide> if (enableProfilerTimer && enableProfilerCommitHooks) {
<del> // Only Profilers with work in their subtree will have an Update effect scheduled.
<del> if ((finishedWork.flags & Update) !== NoFlags) {
<del> switch (finishedWork.tag) {
<del> case Profiler: {
<del> const {passiveEffectDuration} = finishedWork.stateNode;
<del> const {id, onPostCommit} = finishedWork.memoizedProps;
<del>
<del> // This value will still reflect the previous commit phase.
<del> // It does not get reset until the start of the next commit phase.
<del> const commitTime = getCommitTime();
<del>
<del> if (typeof onPostCommit === 'function') {
<del> if (enableSchedulerTracing) {
<del> onPostCommit(
<del> id,
<del> finishedWork.alternate === null ? 'mount' : 'update',
<del> passiveEffectDuration,
<del> commitTime,
<del> finishedRoot.memoizedInteractions,
<del> );
<del> } else {
<del> onPostCommit(
<del> id,
<del> finishedWork.alternate === null ? 'mount' : 'update',
<del> passiveEffectDuration,
<del> commitTime,
<del> );
<del> }
<add> switch (finishedWork.tag) {
<add> case Profiler: {
<add> const {passiveEffectDuration} = finishedWork.stateNode;
<add> const {id, onPostCommit} = finishedWork.memoizedProps;
<add>
<add> // This value will still reflect the previous commit phase.
<add> // It does not get reset until the start of the next commit phase.
<add> const commitTime = getCommitTime();
<add>
<add> if (typeof onPostCommit === 'function') {
<add> if (enableSchedulerTracing) {
<add> onPostCommit(
<add> id,
<add> finishedWork.alternate === null ? 'mount' : 'update',
<add> passiveEffectDuration,
<add> commitTime,
<add> finishedRoot.memoizedInteractions,
<add> );
<add> } else {
<add> onPostCommit(
<add> id,
<add> finishedWork.alternate === null ? 'mount' : 'update',
<add> passiveEffectDuration,
<add> commitTime,
<add> );
<ide> }
<add> }
<ide>
<del> // Bubble times to the next nearest ancestor Profiler.
<del> // After we process that Profiler, we'll bubble further up.
<del> let parentFiber = finishedWork.return;
<del> while (parentFiber !== null) {
<del> if (parentFiber.tag === Profiler) {
<del> const parentStateNode = parentFiber.stateNode;
<del> parentStateNode.passiveEffectDuration += passiveEffectDuration;
<del> break;
<del> }
<del> parentFiber = parentFiber.return;
<add> // Bubble times to the next nearest ancestor Profiler.
<add> // After we process that Profiler, we'll bubble further up.
<add> // TODO: Use JS Stack instead
<add> let parentFiber = finishedWork.return;
<add> while (parentFiber !== null) {
<add> if (parentFiber.tag === Profiler) {
<add> const parentStateNode = parentFiber.stateNode;
<add> parentStateNode.passiveEffectDuration += passiveEffectDuration;
<add> break;
<ide> }
<del> break;
<add> parentFiber = parentFiber.return;
<ide> }
<del> default:
<del> break;
<add> break;
<ide> }
<add> default:
<add> break;
<ide> }
<ide> }
<ide> }
<ide> function commitLifeCycles(
<ide> }
<ide> }
<ide>
<del> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<del> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<del> // because the effect is also where times bubble to parent Profilers.
<del> enqueuePendingPassiveProfilerEffect(finishedWork);
<del>
<ide> // Propagate layout effect durations to the next nearest Profiler ancestor.
<ide> // Do not reset these values until the next render so DevTools has a chance to read them first.
<add> // TODO: Use JS Stack instead
<ide> let parentFiber = finishedWork.return;
<ide> while (parentFiber !== null) {
<ide> if (parentFiber.tag === Profiler) {
<ide> function commitPassiveWork(finishedWork: Fiber): void {
<ide> finishedWork,
<ide> finishedWork.return,
<ide> );
<add> break;
<ide> }
<ide> }
<ide> }
<ide> function commitPassiveUnmount(
<ide> }
<ide> }
<ide>
<del>function commitPassiveLifeCycles(finishedWork: Fiber): void {
<add>function commitPassiveLifeCycles(
<add> finishedRoot: FiberRoot,
<add> finishedWork: Fiber,
<add>): void {
<ide> switch (finishedWork.tag) {
<ide> case FunctionComponent:
<ide> case ForwardRef:
<ide> case SimpleMemoComponent:
<ide> case Block: {
<ide> commitHookEffectListMount2(finishedWork);
<add> break;
<add> }
<add> case Profiler: {
<add> commitProfilerPassiveEffect(finishedRoot, finishedWork);
<add> break;
<ide> }
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> enableSuspenseServerRenderer,
<ide> replayFailedUnitOfWorkWithInvokeGuardedCallback,
<ide> enableProfilerTimer,
<del> enableProfilerCommitHooks,
<ide> enableSchedulerTracing,
<ide> warnAboutUnmockedScheduler,
<ide> deferRenderPhaseUpdateToNextBatch,
<ide> import {
<ide> commitPassiveLifeCycles as commitPassiveEffectOnFiber,
<ide> commitDetachRef,
<ide> commitAttachRef,
<del> commitPassiveEffectDurations,
<ide> commitResetTextContent,
<ide> isSuspenseBoundaryBeingHidden,
<ide> } from './ReactFiberCommitWork.new';
<ide> let rootDoesHavePassiveEffects: boolean = false;
<ide> let rootWithPendingPassiveEffects: FiberRoot | null = null;
<ide> let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority;
<ide> let pendingPassiveEffectsLanes: Lanes = NoLanes;
<del>let pendingPassiveProfilerEffects: Array<Fiber> = [];
<ide>
<ide> let rootsWithPendingDiscreteUpdates: Set<FiberRoot> | null = null;
<ide>
<ide> export function flushPassiveEffects(): boolean {
<ide> return false;
<ide> }
<ide>
<del>export function enqueuePendingPassiveProfilerEffect(fiber: Fiber): void {
<del> if (enableProfilerTimer && enableProfilerCommitHooks) {
<del> pendingPassiveProfilerEffects.push(fiber);
<del> if (!rootDoesHavePassiveEffects) {
<del> rootDoesHavePassiveEffects = true;
<del> scheduleCallback(NormalSchedulerPriority, () => {
<del> flushPassiveEffects();
<del> return null;
<del> });
<del> }
<del> }
<del>}
<del>
<del>function flushPassiveMountEffects(firstChild: Fiber): void {
<add>function flushPassiveMountEffects(root, firstChild: Fiber): void {
<ide> let fiber = firstChild;
<ide> while (fiber !== null) {
<ide> const primarySubtreeFlags = fiber.subtreeFlags & PassiveMask;
<ide>
<ide> if (fiber.child !== null && primarySubtreeFlags !== NoFlags) {
<del> flushPassiveMountEffects(fiber.child);
<add> flushPassiveMountEffects(root, fiber.child);
<ide> }
<ide>
<ide> if ((fiber.flags & Passive) !== NoFlags) {
<ide> setCurrentDebugFiberInDEV(fiber);
<del> commitPassiveEffectOnFiber(fiber);
<add> commitPassiveEffectOnFiber(root, fiber);
<ide> resetCurrentDebugFiberInDEV();
<ide> }
<ide>
<ide> function flushPassiveEffectsImpl() {
<ide> // value set by a create function in another component.
<ide> // Layout effects have the same constraint.
<ide> flushPassiveUnmountEffects(root.current);
<del> flushPassiveMountEffects(root.current);
<del>
<del> if (enableProfilerTimer && enableProfilerCommitHooks) {
<del> const profilerEffects = pendingPassiveProfilerEffects;
<del> pendingPassiveProfilerEffects = [];
<del> for (let i = 0; i < profilerEffects.length; i++) {
<del> const fiber = ((profilerEffects[i]: any): Fiber);
<del> commitPassiveEffectDurations(root, fiber);
<del> }
<del> }
<add> flushPassiveMountEffects(root, root.current);
<ide>
<ide> if (enableSchedulerTracing) {
<ide> popInteractions(((prevInteractions: any): Set<Interaction>)); | 3 |
Java | Java | add shortcuts for elements with no annotations | 1733d0111d1fb0b253b0085be9347d269548bac4 | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
<ide> public static boolean isAnnotated(AnnotatedElement element, final String annotat
<ide> Assert.notNull(element, "AnnotatedElement must not be null");
<ide> Assert.hasLength(annotationName, "annotationName must not be null or empty");
<ide>
<add> if (element.getAnnotations().length == 0) {
<add> return false;
<add> }
<ide> return Boolean.TRUE.equals(searchWithGetSemantics(element, annotationName, new SimpleAnnotationProcessor<Boolean>() {
<ide> @Override
<ide> public Boolean process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
<ide> public static AnnotationAttributes getAnnotationAttributes(AnnotatedElement elem
<ide> public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element, String annotationName,
<ide> boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
<ide>
<add> if (element.getAnnotations().length == 0) {
<add> return null;
<add> }
<ide> AnnotationAttributes attributes = searchWithGetSemantics(element, annotationName,
<ide> new MergedAnnotationAttributesProcessor(annotationName, classValuesAsString, nestedAnnotationsAsMap));
<ide> AnnotationUtils.postProcessAnnotationAttributes(element, attributes, classValuesAsString, nestedAnnotationsAsMap); | 1 |
Python | Python | improve trapz docstring | dbed464aa31069a90637a540cc464e6a59feec30 | <ide><path>numpy/lib/function_base.py
<ide> def _trapz_dispatcher(y, x=None, dx=None, axis=None):
<ide>
<ide> @array_function_dispatch(_trapz_dispatcher)
<ide> def trapz(y, x=None, dx=1.0, axis=-1):
<del> """
<add> r"""
<ide> Integrate along the given axis using the composite trapezoidal rule.
<ide>
<del> Integrate `y` (`x`) along given axis.
<del>
<add> If `x` is provided, the integration happens in sequence along its
<add> elements - they are not sorted.
<add>
<add> Integrate `y` (`x`) along each 1d slice on the given axis, compute
<add> :math:`\int y(x) dx`.
<add> When `x` is specified, this integrates along the parametric curve,
<add> computing :math:`\int_t y(t) dt =
<add> \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
<add>
<ide> Parameters
<ide> ----------
<ide> y : array_like
<ide> def trapz(y, x=None, dx=1.0, axis=-1):
<ide> 8.0
<ide> >>> np.trapz([1,2,3], dx=2)
<ide> 8.0
<add>
<add> Using a decreasing `x` corresponds to integrating in reverse:
<add>
<add> >>> np.trapz([1,2,3], x=[8,6,4])
<add> -8.0
<add>
<add> More generally `x` is used to integrate along a parametric curve.
<add> This finds the area of a circle, noting we repeat the sample which closes
<add> the curve:
<add>
<add> >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
<add> >>> np.trapz(np.cos(theta), x=np.sin(theta))
<add> 3.141571941375841
<add>
<ide> >>> a = np.arange(6).reshape(2, 3)
<ide> >>> a
<ide> array([[0, 1, 2],
<ide> def trapz(y, x=None, dx=1.0, axis=-1):
<ide> array([1.5, 2.5, 3.5])
<ide> >>> np.trapz(a, axis=1)
<ide> array([2., 8.])
<del>
<ide> """
<ide> y = asanyarray(y)
<ide> if x is None: | 1 |
Java | Java | fix exception mock request builder | 0eeb6717e09a81e58ba206fce3176b9b22f23f44 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
<ide> public final MockHttpServletRequest buildRequest(ServletContext servletContext)
<ide>
<ide> for (Entry<String, List<String>> entry : this.uriComponents.getQueryParams().entrySet()) {
<ide> for (String value : entry.getValue()) {
<del> request.addParameter(
<del> UriUtils.decode(entry.getKey(), "UTF-8"),
<del> UriUtils.decode(value, "UTF-8"));
<add> value = (value != null) ? UriUtils.decode(value, "UTF-8") : null;
<add> request.addParameter(UriUtils.decode(entry.getKey(), "UTF-8"), value);
<ide> }
<ide> }
<ide> }
<ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java
<ide> public void requestParameterFromQueryWithEncoding() throws Exception {
<ide> assertEquals("bar=baz", request.getParameter("foo"));
<ide> }
<ide>
<add> // SPR-11043
<add>
<add> @Test
<add> public void requestParameterFromQueryNull() throws Exception {
<add> this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo");
<add>
<add> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
<add> Map<String, String[]> parameterMap = request.getParameterMap();
<add>
<add> assertArrayEquals(new String[]{null}, parameterMap.get("foo"));
<add> assertEquals("foo", request.getQueryString());
<add> }
<add>
<ide> @Test
<ide> public void acceptHeader() throws Exception {
<ide> this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML); | 2 |
Javascript | Javascript | fix import path | 9a72fea4854f1a12dbd81b7779afd77f99331b7e | <ide><path>packages/ember-glimmer/tests/integration/helpers/closure-action-test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import { computed } from 'ember-metal/computed';
<ide> import isEnabled from 'ember-metal/features';
<ide> import { subscribe, unsubscribe } from 'ember-metal/instrumentation';
<del>import { INVOKE } from 'ember-routing-htmlbars/keywords/closure-action';
<add>import { INVOKE } from 'ember-htmlbars/keywords/closure-action';
<ide> import { RenderingTest, moduleFor } from '../../utils/test-case';
<ide> import { Component } from '../../utils/helpers';
<ide> | 1 |
Text | Text | put release script specifics in details | d71b467bbe8ffa5cacb54ff70b7329256b7f9c0a | <ide><path>doc/guides/releases.md
<ide> $ ./tools/release.sh -i ~/.ssh/node_id_rsa
<ide>
<ide> `tools/release.sh` will perform the following actions when run:
<ide>
<add><details>
<add>
<ide> **a.** Select a GPG key from your private keys. It will use a command similar
<ide> to: `gpg --list-secret-keys` to list your keys. If you don't have any keys, it
<ide> will bail. If you have only one key, it will use that. If you have more than
<ide> SHASUMS256.txt.sig.
<ide>
<ide> **g.** Upload the `SHASUMS256.txt` files back to the server into the release
<ide> directory.
<add></details>
<ide>
<ide> If you didn't wait for ARM builds in the previous step before promoting the
<ide> release, you should re-run `tools/release.sh` after the ARM builds have | 1 |
Python | Python | add missing "self" parameter to class method | b5b1c111c4bdb813f89636912d2668fd0e1dffb3 | <ide><path>celery/backends/cassandra.py
<ide> def __init__(self, servers=None, keyspace=None, column_family=None,
<ide>
<ide> self._column_family = None
<ide>
<del> def _retry_on_error(func):
<add> def _retry_on_error(self, func):
<ide> def wrapper(*args, **kwargs):
<ide> self = args[0]
<ide> ts = time.time() + self._retry_timeout | 1 |
Text | Text | add reactfoo 2017 to list of upcoming conferences | 7e297e9b20d75ee9cc39aadf7e83133af1869881 | <ide><path>docs/community/conferences.md
<ide> September 8-10 in Tel Aviv, Israel
<ide>
<ide> [Website](http://react-next.com/) - [Twitter](https://twitter.com/ReactNext)
<ide>
<add>### ReactFoo 2017
<add>September 14 in Bangalore, India
<add>
<add>[Website](https://reactfoo.in/2017/)
<add>
<ide> ### React Boston 2017
<ide> September 23-24 in Boston, Massachusetts USA
<ide> | 1 |
Python | Python | remove unnecessary test skips | 65add6679d5eebe5c8baadb02b4c105da388e0e5 | <ide><path>rest_framework/compat.py
<ide> The `compat` module provides support for backwards compatibility with older
<ide> versions of Django/Python, and compatibility wrappers around optional packages.
<ide> """
<del>import sys
<del>
<ide> from django.conf import settings
<ide> from django.views.generic import View
<ide>
<ide> def md_filter_add_syntax_highlight(md):
<ide> SHORT_SEPARATORS = (',', ':')
<ide> LONG_SEPARATORS = (', ', ': ')
<ide> INDENT_SEPARATORS = (',', ': ')
<del>
<del>
<del># Version Constants.
<del>PY36 = sys.version_info >= (3, 6)
<ide><path>tests/test_permissions.py
<ide> from unittest import mock
<ide>
<ide> import django
<del>import pytest
<ide> from django.conf import settings
<ide> from django.contrib.auth.models import AnonymousUser, Group, Permission, User
<ide> from django.db import models
<ide> HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers,
<ide> status, views
<ide> )
<del>from rest_framework.compat import PY36
<ide> from rest_framework.routers import DefaultRouter
<ide> from rest_framework.test import APIRequestFactory
<ide> from tests.models import BasicModel
<ide> def test_several_levels_and_precedence(self):
<ide> )
<ide> assert composed_perm().has_permission(request, None) is True
<ide>
<del> @pytest.mark.skipif(not PY36, reason="assert_called_once() not available")
<ide> def test_or_lazyness(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = AnonymousUser()
<ide> def test_or_lazyness(self):
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.AllowAny | permissions.IsAuthenticated)
<ide> hasperm = composed_perm().has_permission(request, None)
<del> self.assertIs(hasperm, True)
<del> mock_allow.assert_called_once()
<add> assert hasperm is True
<add> assert mock_allow.call_count == 1
<ide> mock_deny.assert_not_called()
<ide>
<ide> with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow:
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.IsAuthenticated | permissions.AllowAny)
<ide> hasperm = composed_perm().has_permission(request, None)
<del> self.assertIs(hasperm, True)
<del> mock_deny.assert_called_once()
<del> mock_allow.assert_called_once()
<add> assert hasperm is True
<add> assert mock_deny.call_count == 1
<add> assert mock_allow.call_count == 1
<ide>
<del> @pytest.mark.skipif(not PY36, reason="assert_called_once() not available")
<ide> def test_object_or_lazyness(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = AnonymousUser()
<ide> def test_object_or_lazyness(self):
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.AllowAny | permissions.IsAuthenticated)
<ide> hasperm = composed_perm().has_object_permission(request, None, None)
<del> self.assertIs(hasperm, True)
<del> mock_allow.assert_called_once()
<add> assert hasperm is True
<add> assert mock_allow.call_count == 1
<ide> mock_deny.assert_not_called()
<ide>
<ide> with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow:
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.IsAuthenticated | permissions.AllowAny)
<ide> hasperm = composed_perm().has_object_permission(request, None, None)
<del> self.assertIs(hasperm, True)
<del> mock_deny.assert_called_once()
<del> mock_allow.assert_called_once()
<add> assert hasperm is True
<add> assert mock_deny.call_count == 1
<add> assert mock_allow.call_count == 1
<ide>
<del> @pytest.mark.skipif(not PY36, reason="assert_called_once() not available")
<ide> def test_and_lazyness(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = AnonymousUser()
<ide> def test_and_lazyness(self):
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.AllowAny & permissions.IsAuthenticated)
<ide> hasperm = composed_perm().has_permission(request, None)
<del> self.assertIs(hasperm, False)
<del> mock_allow.assert_called_once()
<del> mock_deny.assert_called_once()
<add> assert hasperm is False
<add> assert mock_allow.call_count == 1
<add> assert mock_deny.call_count == 1
<ide>
<ide> with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow:
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.IsAuthenticated & permissions.AllowAny)
<ide> hasperm = composed_perm().has_permission(request, None)
<del> self.assertIs(hasperm, False)
<add> assert hasperm is False
<add> assert mock_deny.call_count == 1
<ide> mock_allow.assert_not_called()
<del> mock_deny.assert_called_once()
<ide>
<del> @pytest.mark.skipif(not PY36, reason="assert_called_once() not available")
<ide> def test_object_and_lazyness(self):
<ide> request = factory.get('/1', format='json')
<ide> request.user = AnonymousUser()
<ide> def test_object_and_lazyness(self):
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.AllowAny & permissions.IsAuthenticated)
<ide> hasperm = composed_perm().has_object_permission(request, None, None)
<del> self.assertIs(hasperm, False)
<del> mock_allow.assert_called_once()
<del> mock_deny.assert_called_once()
<add> assert hasperm is False
<add> assert mock_allow.call_count == 1
<add> assert mock_deny.call_count == 1
<ide>
<ide> with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow:
<ide> with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny:
<ide> composed_perm = (permissions.IsAuthenticated & permissions.AllowAny)
<ide> hasperm = composed_perm().has_object_permission(request, None, None)
<del> self.assertIs(hasperm, False)
<add> assert hasperm is False
<add> assert mock_deny.call_count == 1
<ide> mock_allow.assert_not_called()
<del> mock_deny.assert_called_once() | 2 |
Go | Go | remove ipopt as it's no longer used | 21dac5e441d608260e700984fd6219753f038b28 | <ide><path>opts/ip.go
<del>package opts // import "github.com/docker/docker/opts"
<del>
<del>import (
<del> "fmt"
<del> "net"
<del>)
<del>
<del>// IPOpt holds an IP. It is used to store values from CLI flags.
<del>type IPOpt struct {
<del> *net.IP
<del>}
<del>
<del>// NewIPOpt creates a new IPOpt from a reference net.IP and a
<del>// string representation of an IP. If the string is not a valid
<del>// IP it will fallback to the specified reference.
<del>func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
<del> o := &IPOpt{
<del> IP: ref,
<del> }
<del> o.Set(defaultVal)
<del> return o
<del>}
<del>
<del>// Set sets an IPv4 or IPv6 address from a given string. If the given
<del>// string is not parsable as an IP address it returns an error.
<del>func (o *IPOpt) Set(val string) error {
<del> ip := net.ParseIP(val)
<del> if ip == nil {
<del> return fmt.Errorf("%s is not an ip address", val)
<del> }
<del> *o.IP = ip
<del> return nil
<del>}
<del>
<del>// String returns the IP address stored in the IPOpt. If stored IP is a
<del>// nil pointer, it returns an empty string.
<del>func (o *IPOpt) String() string {
<del> if *o.IP == nil {
<del> return ""
<del> }
<del> return o.IP.String()
<del>}
<del>
<del>// Type returns the type of the option
<del>func (o *IPOpt) Type() string {
<del> return "ip"
<del>}
<ide><path>opts/ip_test.go
<del>package opts // import "github.com/docker/docker/opts"
<del>
<del>import (
<del> "net"
<del> "testing"
<del>)
<del>
<del>func TestIpOptString(t *testing.T) {
<del> addresses := []string{"", "0.0.0.0"}
<del> var ip net.IP
<del>
<del> for _, address := range addresses {
<del> stringAddress := NewIPOpt(&ip, address).String()
<del> if stringAddress != address {
<del> t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress)
<del> }
<del> }
<del>}
<del>
<del>func TestNewIpOptInvalidDefaultVal(t *testing.T) {
<del> ip := net.IPv4(127, 0, 0, 1)
<del> defaultVal := "Not an ip"
<del>
<del> ipOpt := NewIPOpt(&ip, defaultVal)
<del>
<del> expected := "127.0.0.1"
<del> if ipOpt.String() != expected {
<del> t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
<del> }
<del>}
<del>
<del>func TestNewIpOptValidDefaultVal(t *testing.T) {
<del> ip := net.IPv4(127, 0, 0, 1)
<del> defaultVal := "192.168.1.1"
<del>
<del> ipOpt := NewIPOpt(&ip, defaultVal)
<del>
<del> expected := "192.168.1.1"
<del> if ipOpt.String() != expected {
<del> t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
<del> }
<del>}
<del>
<del>func TestIpOptSetInvalidVal(t *testing.T) {
<del> ip := net.IPv4(127, 0, 0, 1)
<del> ipOpt := &IPOpt{IP: &ip}
<del>
<del> invalidIP := "invalid ip"
<del> expectedError := "invalid ip is not an ip address"
<del> err := ipOpt.Set(invalidIP)
<del> if err == nil || err.Error() != expectedError {
<del> t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error())
<del> }
<del>} | 2 |
Mixed | Javascript | add isdisturbed helper | 4832d1c02c8caf3269c5e3f7bfe750f65885c34c | <ide><path>doc/api/stream.md
<ide> added: v11.4.0
<ide> Is `true` if it is safe to call [`readable.read()`][stream-read], which means
<ide> the stream has not been destroyed or emitted `'error'` or `'end'`.
<ide>
<add>##### `readable.readableAborted`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>> Stability: 1 - Experimental
<add>
<add>* {boolean}
<add>
<add>Returns whether the stream was destroyed or errored before emitting `'end'`.
<add>
<ide> ##### `readable.readableDidRead`
<ide> <!-- YAML
<ide> added: REPLACEME
<ide> -->
<ide>
<add>> Stability: 1 - Experimental
<add>
<ide> * {boolean}
<ide>
<del>Allows determining if the stream has been or is about to be read.
<del>Returns true if `'data'`, `'end'`, `'error'` or `'close'` has been
<del>emitted.
<add>Returns whether `'data'` has been emitted.
<ide>
<ide> ##### `readable.readableEncoding`
<ide> <!-- YAML
<ide> added: REPLACEME
<ide> * `signal` {AbortSignal}
<ide> * Returns: {stream.Readable}
<ide>
<add>### `stream.Readable.isDisturbed(stream)`
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>> Stability: 1 - Experimental
<add>
<add>* `stream` {stream.Readable|ReadableStream}
<add>* Returns: `boolean`
<add>
<add>Returns whether the stream has been read from or cancelled.
<add>
<ide> ### `stream.Readable.toWeb(streamReadable)`
<ide> <!-- YAML
<ide> added: REPLACEME
<ide><path>lib/internal/streams/readable.js
<ide> ObjectDefineProperties(Readable.prototype, {
<ide> readableDidRead: {
<ide> enumerable: false,
<ide> get: function() {
<del> return (
<del> this._readableState.dataEmitted ||
<del> this._readableState.endEmitted ||
<del> this._readableState.errorEmitted ||
<del> this._readableState.closeEmitted
<del> );
<add> return this._readableState.dataEmitted;
<add> }
<add> },
<add>
<add> readableAborted: {
<add> enumerable: false,
<add> get: function() {
<add> return !!(this._readableState.destroyed || this._readableState.errored) &&
<add> !this._readableState.endEmitted;
<ide> }
<ide> },
<ide>
<ide><path>lib/internal/streams/utils.js
<ide> const {
<ide> } = primordials;
<ide>
<ide> const kDestroyed = Symbol('kDestroyed');
<add>const kIsDisturbed = Symbol('kIsDisturbed');
<ide>
<ide> function isReadableNodeStream(obj) {
<ide> return !!(
<ide> function willEmitClose(stream) {
<ide> );
<ide> }
<ide>
<add>function isDisturbed(stream) {
<add> return !!(stream && (
<add> stream.readableDidRead ||
<add> stream.readableAborted ||
<add> stream[kIsDisturbed]
<add> ));
<add>}
<add>
<ide> module.exports = {
<ide> kDestroyed,
<add> isDisturbed,
<add> kIsDisturbed,
<ide> isClosed,
<ide> isDestroyed,
<ide> isDuplexNodeStream,
<ide><path>lib/internal/webstreams/readablestream.js
<ide> const {
<ide> queueMicrotask,
<ide> } = require('internal/process/task_queues');
<ide>
<add>const {
<add> kIsDisturbed,
<add>} = require('internal/streams/utils');
<add>
<ide> const {
<ide> ArrayBufferViewGetBuffer,
<ide> ArrayBufferViewGetByteLength,
<ide> class ReadableStream {
<ide> promise: undefined,
<ide> }
<ide> };
<add>
<ide> // The spec requires handling of the strategy first
<ide> // here. Specifically, if getting the size and
<ide> // highWaterMark from the strategy fail, that has
<ide> class ReadableStream {
<ide> return makeTransferable(this);
<ide> }
<ide>
<add> get [kIsDisturbed]() {
<add> return this[kState].disturbed;
<add> }
<add>
<ide> /**
<ide> * @readonly
<ide> * @type {boolean}
<ide><path>lib/stream.js
<ide> const internalBuffer = require('internal/buffer');
<ide> const promises = require('stream/promises');
<ide>
<ide> const Stream = module.exports = require('internal/streams/legacy').Stream;
<add>Stream.isDisturbed = require('internal/streams/utils').isDisturbed;
<ide> Stream.Readable = require('internal/streams/readable');
<ide> Stream.Writable = require('internal/streams/writable');
<ide> Stream.Duplex = require('internal/streams/duplex');
<ide><path>test/parallel/test-stream-readable-aborted.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const { Readable } = require('stream');
<add>
<add>{
<add> const readable = new Readable({
<add> read() {
<add> }
<add> });
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.destroy();
<add> assert.strictEqual(readable.readableAborted, true);
<add>}
<add>
<add>{
<add> const readable = new Readable({
<add> read() {
<add> }
<add> });
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.push(null);
<add> readable.destroy();
<add> assert.strictEqual(readable.readableAborted, true);
<add>}
<add>
<add>{
<add> const readable = new Readable({
<add> read() {
<add> }
<add> });
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.push('asd');
<add> readable.destroy();
<add> assert.strictEqual(readable.readableAborted, true);
<add>}
<add>
<add>{
<add> const readable = new Readable({
<add> read() {
<add> }
<add> });
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.push('asd');
<add> readable.push(null);
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.on('end', common.mustCall(() => {
<add> assert.strictEqual(readable.readableAborted, false);
<add> readable.destroy();
<add> assert.strictEqual(readable.readableAborted, false);
<add> queueMicrotask(() => {
<add> assert.strictEqual(readable.readableAborted, false);
<add> });
<add> }));
<add> readable.resume();
<add>}
<ide><path>test/parallel/test-stream-readable-didRead.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const Readable = require('stream').Readable;
<add>const { isDisturbed, Readable } = require('stream');
<ide>
<ide> function noop() {}
<ide>
<ide> function check(readable, data, fn) {
<ide> assert.strictEqual(readable.readableDidRead, false);
<add> assert.strictEqual(isDisturbed(readable), false);
<ide> if (data === -1) {
<ide> readable.on('error', common.mustCall());
<ide> readable.on('data', common.mustNotCall());
<ide> function check(readable, data, fn) {
<ide> readable.on('close', common.mustCall());
<ide> fn();
<ide> setImmediate(() => {
<del> assert.strictEqual(readable.readableDidRead, true);
<add> assert.strictEqual(readable.readableDidRead, data > 0);
<add> if (data > 0) {
<add> assert.strictEqual(isDisturbed(readable), true);
<add> }
<ide> });
<ide> }
<ide>
<ide><path>test/parallel/test-whatwg-readablestream.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>const { isDisturbed } = require('stream');
<ide> const assert = require('assert');
<ide> const {
<ide> isPromise,
<ide> class Source {
<ide> readableByteStreamControllerClose(controller);
<ide> readableByteStreamControllerEnqueue(controller);
<ide> }
<add>
<add>{
<add> const stream = new ReadableStream({
<add> start(controller) {
<add> controller.enqueue('a');
<add> controller.close();
<add> },
<add> pull: common.mustNotCall(),
<add> });
<add>
<add> const reader = stream.getReader();
<add> (async () => {
<add> isDisturbed(stream, false);
<add> await reader.read();
<add> isDisturbed(stream, true);
<add> })().then(common.mustCall());
<add>}
<add>
<add>{
<add> const stream = new ReadableStream({
<add> start(controller) {
<add> controller.close();
<add> },
<add> pull: common.mustNotCall(),
<add> });
<add>
<add> const reader = stream.getReader();
<add> (async () => {
<add> isDisturbed(stream, false);
<add> await reader.read();
<add> isDisturbed(stream, true);
<add> })().then(common.mustCall());
<add>}
<add>
<add>{
<add> const stream = new ReadableStream({
<add> start(controller) {
<add> },
<add> pull: common.mustNotCall(),
<add> });
<add> stream.cancel();
<add>
<add> const reader = stream.getReader();
<add> (async () => {
<add> isDisturbed(stream, false);
<add> await reader.read();
<add> isDisturbed(stream, true);
<add> })().then(common.mustCall());
<add>} | 8 |
Javascript | Javascript | simplify function process.emitwarning | d01a06a916efd30844e1e0a38e79dc0054fc4451 | <ide><path>lib/internal/process/warning.js
<ide> function writeToFile(message) {
<ide> }
<ide>
<ide> function doEmitWarning(warning) {
<del> return () => process.emit('warning', warning);
<add> process.emit('warning', warning);
<ide> }
<ide>
<ide> let traceWarningHelperShown = false;
<ide> function emitWarning(warning, type, code, ctor) {
<ide> if (process.throwDeprecation)
<ide> throw warning;
<ide> }
<del> process.nextTick(doEmitWarning(warning));
<add> process.nextTick(doEmitWarning, warning);
<ide> }
<ide>
<ide> function emitWarningSync(warning) { | 1 |
Java | Java | add destinationusernameprovider interface | e4ad2b352e35a0cdbc5d4834f9689a13162c8d19 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.java
<ide> protected boolean checkDestination(String destination, String requiredPrefix) {
<ide> return true;
<ide> }
<ide>
<del> protected String getTargetDestination(String origDestination, String targetDestination, String sessionId, String user) {
<add> protected String getTargetDestination(String origDestination, String targetDestination,
<add> String sessionId, String user) {
<add>
<ide> return targetDestination + "-user" + sessionId;
<ide> }
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/DestinationUserNameProvider.java
<add>package org.springframework.messaging.simp.user;
<add>
<add>/**
<add> * An interface to be implemented in addition to {@link java.security.Principal}
<add> * when {@link java.security.Principal#getName()} is not globally unique enough
<add> * for use in user destinations. For more on user destination see
<add> * {@link org.springframework.messaging.simp.user.UserDestinationResolver}.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 4.0.1
<add> */
<add>public interface DestinationUserNameProvider {
<add>
<add>
<add> /**
<add> * Return the (globally unique) user name to use with user destinations.
<add> */
<add> String getDestinationUserName();
<add>
<add>}
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java
<ide> public class DefaultUserDestinationResolverTests {
<ide>
<ide> private UserSessionRegistry registry;
<ide>
<add> private TestPrincipal user;
<add>
<ide>
<ide> @Before
<ide> public void setup() {
<add> this.user = new TestPrincipal("joe");
<ide> this.registry = new DefaultUserSessionRegistry();
<del> this.registry.registerSessionId("joe", SESSION_ID);
<del>
<add> this.registry.registerSessionId(this.user.getName(), SESSION_ID);
<ide> this.resolver = new DefaultUserDestinationResolver(this.registry);
<ide> }
<ide>
<ide>
<ide> @Test
<ide> public void handleSubscribe() {
<del> Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, "joe", SESSION_ID, "/user/queue/foo");
<add> Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, this.user, SESSION_ID, "/user/queue/foo");
<ide> Set<String> actual = this.resolver.resolveDestination(message);
<ide>
<ide> assertEquals(1, actual.size());
<ide> public void handleSubscribeOneUserMultipleSessions() {
<ide> this.registry.registerSessionId("joe", "456");
<ide> this.registry.registerSessionId("joe", "789");
<ide>
<del> Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, "joe", SESSION_ID, "/user/queue/foo");
<add> Message<?> message = createMessage(SimpMessageType.SUBSCRIBE, this.user, SESSION_ID, "/user/queue/foo");
<ide> Set<String> actual = this.resolver.resolveDestination(message);
<ide>
<ide> assertEquals(1, actual.size());
<ide> public void handleSubscribeOneUserMultipleSessions() {
<ide>
<ide> @Test
<ide> public void handleUnsubscribe() {
<del> Message<?> message = createMessage(SimpMessageType.UNSUBSCRIBE, "joe", SESSION_ID, "/user/queue/foo");
<add> Message<?> message = createMessage(SimpMessageType.UNSUBSCRIBE, this.user, SESSION_ID, "/user/queue/foo");
<ide> Set<String> actual = this.resolver.resolveDestination(message);
<ide>
<ide> assertEquals(1, actual.size());
<ide> public void handleUnsubscribe() {
<ide>
<ide> @Test
<ide> public void handleMessage() {
<del> Message<?> message = createMessage(SimpMessageType.MESSAGE, "joe", SESSION_ID, "/user/joe/queue/foo");
<add> Message<?> message = createMessage(SimpMessageType.MESSAGE, this.user, SESSION_ID, "/user/joe/queue/foo");
<ide> Set<String> actual = this.resolver.resolveDestination(message);
<ide>
<ide> assertEquals(1, actual.size());
<ide> public void handleMessage() {
<ide> public void ignoreMessage() {
<ide>
<ide> // no destination
<del> Message<?> message = createMessage(SimpMessageType.MESSAGE, "joe", SESSION_ID, null);
<add> Message<?> message = createMessage(SimpMessageType.MESSAGE, this.user, SESSION_ID, null);
<ide> Set<String> actual = this.resolver.resolveDestination(message);
<ide> assertEquals(0, actual.size());
<ide>
<ide> // not a user destination
<del> message = createMessage(SimpMessageType.MESSAGE, "joe", SESSION_ID, "/queue/foo");
<add> message = createMessage(SimpMessageType.MESSAGE, this.user, SESSION_ID, "/queue/foo");
<ide> actual = this.resolver.resolveDestination(message);
<ide> assertEquals(0, actual.size());
<ide>
<ide> public void ignoreMessage() {
<ide> assertEquals(0, actual.size());
<ide>
<ide> // subscribe + not a user destination
<del> message = createMessage(SimpMessageType.SUBSCRIBE, "joe", SESSION_ID, "/queue/foo");
<add> message = createMessage(SimpMessageType.SUBSCRIBE, this.user, SESSION_ID, "/queue/foo");
<ide> actual = this.resolver.resolveDestination(message);
<ide> assertEquals(0, actual.size());
<ide>
<ide> // no match on message type
<del> message = createMessage(SimpMessageType.CONNECT, "joe", SESSION_ID, "user/joe/queue/foo");
<add> message = createMessage(SimpMessageType.CONNECT, this.user, SESSION_ID, "user/joe/queue/foo");
<ide> actual = this.resolver.resolveDestination(message);
<ide> assertEquals(0, actual.size());
<ide> }
<ide>
<ide>
<del> private Message<?> createMessage(SimpMessageType messageType, String user, String sessionId, String destination) {
<add> private Message<?> createMessage(SimpMessageType messageType, TestPrincipal user, String sessionId, String destination) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(messageType);
<ide> if (destination != null) {
<ide> headers.setDestination(destination);
<ide> }
<ide> if (user != null) {
<del> headers.setUser(new TestPrincipal(user));
<add> headers.setUser(user);
<ide> }
<ide> if (sessionId != null) {
<ide> headers.setSessionId(sessionId);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java
<ide> import org.springframework.messaging.simp.stomp.StompDecoder;
<ide> import org.springframework.messaging.simp.stomp.StompEncoder;
<ide> import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
<add>import org.springframework.messaging.simp.user.DestinationUserNameProvider;
<ide> import org.springframework.messaging.simp.user.UserSessionRegistry;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> import org.springframework.util.Assert;
<ide> private void afterStompSessionConnected(StompHeaderAccessor headers, WebSocketSe
<ide> if (principal != null) {
<ide> headers.setNativeHeader(CONNECTED_USER_HEADER, principal.getName());
<ide> if (this.userSessionRegistry != null) {
<del> this.userSessionRegistry.registerSessionId(principal.getName(), session.getId());
<add> String userName = getNameForUserSessionRegistry(principal);
<add> this.userSessionRegistry.registerSessionId(userName, session.getId());
<ide> }
<ide> }
<ide> }
<ide>
<add> private String getNameForUserSessionRegistry(Principal principal) {
<add> String userName = principal.getName();
<add> if (principal instanceof DestinationUserNameProvider) {
<add> userName = ((DestinationUserNameProvider) principal).getDestinationUserName();
<add> }
<add> return userName;
<add> }
<add>
<ide> @Override
<ide> public String resolveSessionId(Message<?> message) {
<ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
<ide> public void afterSessionStarted(WebSocketSession session, MessageChannel outputC
<ide> @Override
<ide> public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) {
<ide>
<del> if ((this.userSessionRegistry != null) && (session.getPrincipal() != null)) {
<del> this.userSessionRegistry.unregisterSessionId(session.getPrincipal().getName(), session.getId());
<add> Principal principal = session.getPrincipal();
<add> if ((this.userSessionRegistry != null) && (principal != null)) {
<add> String userName = getNameForUserSessionRegistry(principal);
<add> this.userSessionRegistry.unregisterSessionId(userName, session.getId());
<ide> }
<ide>
<ide> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompSubProtocolHandlerTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import java.nio.ByteBuffer;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<ide> import java.util.HashSet;
<ide>
<ide> import org.junit.Before;
<ide> import org.springframework.messaging.simp.stomp.StompCommand;
<ide> import org.springframework.messaging.simp.stomp.StompDecoder;
<ide> import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
<add>import org.springframework.messaging.simp.user.DefaultUserSessionRegistry;
<add>import org.springframework.messaging.simp.user.DestinationUserNameProvider;
<add>import org.springframework.messaging.simp.user.UserSessionRegistry;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> import org.springframework.web.socket.TextMessage;
<ide> import org.springframework.web.socket.WebSocketMessage;
<ide> */
<ide> public class StompSubProtocolHandlerTests {
<ide>
<del> private StompSubProtocolHandler stompHandler;
<add> private StompSubProtocolHandler protocolHandler;
<ide>
<ide> private TestWebSocketSession session;
<ide>
<ide> public class StompSubProtocolHandlerTests {
<ide>
<ide> @Before
<ide> public void setup() {
<del> this.stompHandler = new StompSubProtocolHandler();
<add> this.protocolHandler = new StompSubProtocolHandler();
<ide> this.channel = Mockito.mock(MessageChannel.class);
<ide> this.messageCaptor = ArgumentCaptor.forClass(Message.class);
<ide>
<ide> public void setup() {
<ide> }
<ide>
<ide> @Test
<del> public void connectedResponseIsSentWhenConnectAckIsToBeSentToClient() {
<add> public void handleMessageToClientConnected() {
<add>
<add> UserSessionRegistry registry = new DefaultUserSessionRegistry();
<add> this.protocolHandler.setUserSessionRegistry(registry);
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
<add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
<add> this.protocolHandler.handleMessageToClient(this.session, message);
<add>
<add> assertEquals(1, this.session.getSentMessages().size());
<add> WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0);
<add> assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload());
<add>
<add> assertEquals(Collections.singleton("s1"), registry.getSessionIds("joe"));
<add> }
<add>
<add> @Test
<add> public void handleMessageToClientConnectedUniqueUserName() {
<add>
<add> this.session.setPrincipal(new UniqueUser("joe"));
<add>
<add> UserSessionRegistry registry = new DefaultUserSessionRegistry();
<add> this.protocolHandler.setUserSessionRegistry(registry);
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
<add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
<add> this.protocolHandler.handleMessageToClient(this.session, message);
<add>
<add> assertEquals(1, this.session.getSentMessages().size());
<add> WebSocketMessage<?> textMessage = this.session.getSentMessages().get(0);
<add> assertEquals("CONNECTED\n" + "user-name:joe\n" + "\n" + "\u0000", textMessage.getPayload());
<add>
<add> assertEquals(Collections.<String>emptySet(), registry.getSessionIds("joe"));
<add> assertEquals(Collections.singleton("s1"), registry.getSessionIds("Me myself and I"));
<add> }
<add>
<add> @Test
<add> public void handleMessageToClientConnectAck() {
<add>
<ide> StompHeaderAccessor connectHeaders = StompHeaderAccessor.create(StompCommand.CONNECT);
<ide> connectHeaders.setHeartbeat(10000, 10000);
<ide> connectHeaders.setNativeHeader(StompHeaderAccessor.STOMP_ACCEPT_VERSION_HEADER, "1.0,1.1");
<del>
<ide> Message<?> connectMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(connectHeaders).build();
<ide>
<ide> SimpMessageHeaderAccessor connectAckHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
<ide> connectAckHeaders.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
<add> Message<byte[]> connectAckMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(connectAckHeaders).build();
<ide>
<del> Message<byte[]> connectAck = MessageBuilder.withPayload(new byte[0]).setHeaders(connectAckHeaders).build();
<del> this.stompHandler.handleMessageToClient(this.session, connectAck);
<add> this.protocolHandler.handleMessageToClient(this.session, connectAckMessage);
<ide>
<ide> verifyNoMoreInteractions(this.channel);
<ide>
<ide> public void connectedResponseIsSentWhenConnectAckIsToBeSentToClient() {
<ide> }
<ide>
<ide> @Test
<del> public void messagesAreAugmentedAndForwarded() {
<add> public void handleMessageFromClient() {
<ide>
<ide> TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.CONNECT).headers(
<ide> "login:guest", "passcode:guest", "accept-version:1.1,1.0", "heart-beat:10000,10000").build();
<ide>
<del> this.stompHandler.handleMessageFromClient(this.session, textMessage, this.channel);
<add> this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);
<ide>
<ide> verify(this.channel).send(this.messageCaptor.capture());
<ide> Message<?> actual = this.messageCaptor.getValue();
<ide> public void messagesAreAugmentedAndForwarded() {
<ide> }
<ide>
<ide> @Test
<del> public void invalidStompCommand() {
<add> public void handleMessageFromClientInvalidStompCommand() {
<ide>
<ide> TextMessage textMessage = new TextMessage("FOO");
<ide>
<del> this.stompHandler.handleMessageFromClient(this.session, textMessage, this.channel);
<add> this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);
<ide>
<ide> verifyZeroInteractions(this.channel);
<ide> assertEquals(1, this.session.getSentMessages().size());
<ide> TextMessage actual = (TextMessage) this.session.getSentMessages().get(0);
<ide> assertTrue(actual.getPayload().startsWith("ERROR"));
<ide> }
<ide>
<add>
<add> private static class UniqueUser extends TestPrincipal implements DestinationUserNameProvider {
<add>
<add> private UniqueUser(String name) {
<add> super(name);
<add> }
<add>
<add> @Override
<add> public String getDestinationUserName() {
<add> return "Me myself and I";
<add> }
<add> }
<add>
<ide> } | 5 |
Javascript | Javascript | emit errors on close whilst async action | 5795e835a1021abdf803e1460501487adbac8d7c | <ide><path>lib/_tls_wrap.js
<ide> function loadSession(self, hello, cb) {
<ide> if (err)
<ide> return cb(err);
<ide>
<add> if (!self._handle)
<add> return cb(new Error('Socket is closed'));
<add>
<ide> // NOTE: That we have disabled OpenSSL's internal session storage in
<ide> // `node_crypto.cc` and hence its safe to rely on getting servername only
<ide> // from clienthello or this place.
<ide> function loadSNI(self, servername, cb) {
<ide> if (err)
<ide> return cb(err);
<ide>
<add> if (!self._handle)
<add> return cb(new Error('Socket is closed'));
<add>
<ide> // TODO(indutny): eventually disallow raw `SecureContext`
<ide> if (context)
<ide> self._handle.sni_context = context.context || context;
<ide> function requestOCSP(self, hello, ctx, cb) {
<ide> if (err)
<ide> return cb(err);
<ide>
<add> if (!self._handle)
<add> return cb(new Error('Socket is closed'));
<add>
<ide> if (response)
<ide> self._handle.setOCSPResponse(response);
<ide> cb(null);
<ide> function oncertcb(info) {
<ide> if (err)
<ide> return self.destroy(err);
<ide>
<add> if (!self._handle)
<add> return cb(new Error('Socket is closed'));
<add>
<ide> self._handle.certCbDone();
<ide> });
<ide> });
<ide> function onnewsession(key, session) {
<ide> return;
<ide> once = true;
<ide>
<add> if (!self._handle)
<add> return cb(new Error('Socket is closed'));
<add>
<ide> self._handle.newSessionDone();
<ide>
<ide> self._newSessionPending = false;
<ide><path>test/parallel/test-tls-async-cb-after-socket-end.js
<add>'use strict';
<add>
<add>var common = require('../common');
<add>
<add>var assert = require('assert');
<add>var path = require('path');
<add>var fs = require('fs');
<add>var constants = require('constants');
<add>
<add>if (!common.hasCrypto) {
<add> console.log('1..0 # Skipped: missing crypto');
<add> process.exit();
<add>}
<add>
<add>var tls = require('tls');
<add>
<add>var options = {
<add> secureOptions: constants.SSL_OP_NO_TICKET,
<add> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')),
<add> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))
<add>};
<add>
<add>var server = tls.createServer(options, function(c) {
<add>});
<add>
<add>var sessionCb = null;
<add>var client = null;
<add>
<add>server.on('newSession', function(key, session, done) {
<add> done();
<add>});
<add>
<add>server.on('resumeSession', function(id, cb) {
<add> sessionCb = cb;
<add>
<add> next();
<add>});
<add>
<add>server.listen(1443, function() {
<add> var clientOpts = {
<add> port: 1443,
<add> rejectUnauthorized: false,
<add> session: false
<add> };
<add>
<add> var s1 = tls.connect(clientOpts, function() {
<add> clientOpts.session = s1.getSession();
<add> console.log('1st secure');
<add>
<add> s1.destroy();
<add> var s2 = tls.connect(clientOpts, function(s) {
<add> console.log('2nd secure');
<add>
<add> s2.destroy();
<add> }).on('connect', function() {
<add> console.log('2nd connected');
<add> client = s2;
<add>
<add> next();
<add> });
<add> });
<add>});
<add>
<add>function next() {
<add> if (!client || !sessionCb)
<add> return;
<add>
<add> client.destroy();
<add> setTimeout(function() {
<add> sessionCb();
<add> server.close();
<add> }, 100);
<add>} | 2 |
Text | Text | fix boolean error in form helpers guide | 8efd634cabd1ce876a7c1770b120ffaa87d70098 | <ide><path>guides/source/form_helpers.md
<ide> end
<ide>
<ide> ### Preventing Empty Records
<ide>
<del>It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `false` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.
<add>It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `true` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.
<ide>
<ide> ```ruby
<ide> class Person < ApplicationRecord | 1 |
PHP | PHP | fix an error when no options are provided | d669082f8beb602b8c2cd53d20ec45c8e33693cf | <ide><path>lib/Cake/Routing/Router.php
<ide> public static function promote($which = null) {
<ide> * a list of query string parameters.
<ide> * @return string Full translated URL with base path.
<ide> */
<del> public static function url($url = null, $options = false) {
<add> public static function url($url = null, $options = array()) {
<ide> $full = false;
<ide> if (is_bool($options)) {
<ide> $full = $options;
<ide> public static function url($url = null, $options = false) {
<ide> $url
<ide> ));
<ide> }
<del> $url = $options + $route->defaults + array('_name' => $url);
<add> $url = $options +
<add> $route->defaults +
<add> array('_name' => $url);
<ide> $output = self::$_routes->match($url, $params);
<ide> } else {
<ide> // String urls.
<ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php
<ide> public function testUrlGenerationWithCompactForm() {
<ide> * Test url generation with named routes.
<ide> */
<ide> public function testUrlGenerationNamedRoute() {
<add> Router::connect(
<add> '/users',
<add> array('controller' => 'users', 'action' => 'index'),
<add> array('_name' => 'users-index')
<add> );
<ide> Router::connect(
<ide> '/users/:name',
<ide> array('controller' => 'users', 'action' => 'view'),
<ide> public function testUrlGenerationNamedRoute() {
<ide>
<ide> $url = Router::url('test', array('name' => 'mark', 'page' => 1, 'sort' => 'title', 'dir' => 'desc'));
<ide> $this->assertEquals('/users/mark?page=1&sort=title&dir=desc', $url);
<add>
<add> $url = Router::url('users-index');
<add> $this->assertEquals('/users', $url);
<ide> }
<ide>
<ide> /** | 2 |
PHP | PHP | fix a bunch of failing tests/errors | dd02aeec159f6e91d6be2628d9eeccc91ffdb4a6 | <ide><path>lib/Cake/Console/Command/Task/ExtractTask.php
<ide> public function execute() {
<ide> $this->_extractCore = strtolower($response) === 'y';
<ide> }
<ide>
<del> if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
<del> $this->_exclude = array_merge($this->_exclude, App::path('plugins'));
<del> }
<del>
<del> if (!empty($this->params['ignore-model-validation']) || (!$this->_isExtractingApp() && empty($plugin))) {
<del> $this->_extractValidation = false;
<del> }
<del> if (!empty($this->params['validation-domain'])) {
<del> $this->_validationDomain = $this->params['validation-domain'];
<del> }
<del>
<ide> if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
<ide> $this->_exclude = array_merge($this->_exclude, App::path('Plugin'));
<ide> }
<ide><path>lib/Cake/Console/Shell.php
<ide> public function __isset($name) {
<ide> if ($name === $class) {
<ide> return $this->loadModel($modelClass);
<ide> }
<add> list(, $class) = namespaceSplit($modelClass);
<add> if ($name === $class) {
<add> return $this->loadModel($class);
<add> }
<ide> }
<ide> }
<ide> }
<ide> public function loadModel($modelClass = null, $id = null) {
<ide> }
<ide>
<ide> $this->{$modelClass} = ClassRegistry::init(array(
<del> 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
<add> 'class' => $plugin . $modelClass,
<add> 'alias' => $modelClass,
<add> 'id' => $id
<ide> ));
<ide> if (!$this->{$modelClass}) {
<ide> throw new MissingModelException($modelClass);
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php
<ide> public function getUser(Request $request) {
<ide> /**
<ide> * Handle unauthenticated access attempt.
<ide> *
<del> * @param CakeRequest $request A request object.
<del> * @param CakeResponse $response A response object.
<add> * @param Cake\Network\Request $request A request object.
<add> * @param Cake\Network\Response $response A response object.
<ide> * @return mixed Either true to indicate the unauthenticated request has been
<ide> * dealt with and no more action is required by AuthComponent or void (default).
<ide> */
<del> public function unauthenticated(CakeRequest $request, CakeResponse $response) {
<add> public function unauthenticated(Request $request, Response $response) {
<ide> }
<ide>
<ide> }
<ide><path>lib/Cake/Controller/Component/Auth/BasicAuthenticate.php
<ide> public function __construct(ComponentCollection $collection, $settings) {
<ide> * @param Cake\Network\Response $response The response to add headers to.
<ide> * @return mixed Either false on failure, or an array of user data on success.
<ide> */
<del> public function authenticate(CakeRequest $request, CakeResponse $response) {
<add> public function authenticate(Request $request, Response $response) {
<ide> return $this->getUser($request);
<ide> }
<ide>
<del>/**
<del> * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
<del> *
<del> * @param CakeRequest $request Request object.
<del> * @return mixed Either false or an array of user information
<del> */
<del> public function getUser(CakeRequest $request) {
<del> $username = env('PHP_AUTH_USER');
<del> }
<del>
<ide> /**
<ide> * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
<ide> *
<ide> public function getUser(Request $request) {
<ide> * @param CakeResponse $response A response object.
<ide> * @return boolean True
<ide> */
<del> public function unauthenticated(CakeRequest $request, CakeResponse $response) {
<add> public function unauthenticated(Request $request, Response $response) {
<ide> $response->header($this->loginHeaders());
<ide> $response->statusCode(401);
<ide> $response->send();
<ide><path>lib/Cake/Model/ConnectionManager.php
<ide> public static function getDataSource($name) {
<ide>
<ide> $class = static::loadDataSource($name);
<ide>
<del> if (strpos(App::location($class), 'Datasource') === false) {
<add> if (strpos($class, '\Datasource') === false) {
<ide> throw new Error\MissingDatasourceException(array(
<ide> 'class' => $class,
<ide> 'plugin' => null,
<ide><path>lib/Cake/Test/TestCase/BasicsTest.php
<ide> public function testPrCli() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>/**
<del> * test stripslashes_deep()
<del> *
<del> * @return void
<del> */
<del> public function testStripslashesDeep() {
<del> $this->skipIf(ini_get('magic_quotes_sybase') === '1', 'magic_quotes_sybase is on.');
<del>
<del> $this->assertEquals(stripslashes_deep("tes\'t"), "tes't");
<del> $this->assertEquals(stripslashes_deep('tes\\' . chr(0) . 't'), 'tes' . chr(0) . 't');
<del> $this->assertEquals(stripslashes_deep('tes\"t'), 'tes"t');
<del> $this->assertEquals(stripslashes_deep("tes\'t"), "tes't");
<del> $this->assertEquals(stripslashes_deep('te\\st'), 'test');
<del>
<del> $nested = array(
<del> 'a' => "tes\'t",
<del> 'b' => 'tes\\' . chr(0) . 't',
<del> 'c' => array(
<del> 'd' => 'tes\"t',
<del> 'e' => "te\'s\'t",
<del> array('f' => "tes\'t")
<del> ),
<del> 'g' => 'te\\st'
<del> );
<del> $expected = array(
<del> 'a' => "tes't",
<del> 'b' => 'tes' . chr(0) . 't',
<del> 'c' => array(
<del> 'd' => 'tes"t',
<del> 'e' => "te's't",
<del> array('f' => "tes't")
<del> ),
<del> 'g' => 'test'
<del> );
<del> $this->assertEquals($expected, stripslashes_deep($nested));
<del> }
<del>
<del>/**
<del> * test stripslashes_deep() with magic_quotes_sybase on
<del> *
<del> * @return void
<del> */
<del> public function testStripslashesDeepSybase() {
<del> if (!(ini_get('magic_quotes_sybase') === '1')) {
<del> $this->markTestSkipped('magic_quotes_sybase is off');
<del> }
<del>
<del> $this->assertEquals(stripslashes_deep("tes\'t"), "tes\'t");
<del>
<del> $nested = array(
<del> 'a' => "tes't",
<del> 'b' => "tes''t",
<del> 'c' => array(
<del> 'd' => "tes'''t",
<del> 'e' => "tes''''t",
<del> array('f' => "tes''t")
<del> ),
<del> 'g' => "te'''''st"
<del> );
<del> $expected = array(
<del> 'a' => "tes't",
<del> 'b' => "tes't",
<del> 'c' => array(
<del> 'd' => "tes''t",
<del> 'e' => "tes''t",
<del> array('f' => "tes't")
<del> ),
<del> 'g' => "te'''st"
<del> );
<del> $this->assertEquals($expected, stripslashes_deep($nested));
<del> }
<del>
<ide> /**
<ide> * test pluginSplit
<ide> *
<ide><path>lib/Cake/Test/TestCase/Console/Command/Task/ExtractTaskTest.php
<ide> public function testExtractExcludePlugins() {
<ide> array('_isExtractingApp', '_extractValidationMessages', 'in', 'out', 'err', 'clear', '_stop'),
<ide> array($this->out, $this->out, $this->in)
<ide> );
<del> $this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true));
<add> $this->Task->expects($this->exactly(2))
<add> ->method('_isExtractingApp')
<add> ->will($this->returnValue(true));
<ide>
<ide> $this->Task->params['paths'] = CAKE . 'Test/TestApp/';
<ide> $this->Task->params['output'] = $this->path . DS;
<ide> public function testExtractModelValidation() {
<ide> array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
<ide> array($this->out, $this->out, $this->in)
<ide> );
<del> $this->Task->expects($this->exactly(2))->method('_isExtractingApp')->will($this->returnValue(true));
<add> $this->Task->expects($this->exactly(2))
<add> ->method('_isExtractingApp')
<add> ->will($this->returnValue(true));
<ide>
<ide> $this->Task->params['paths'] = CAKE . 'Test/TestApp/';
<ide> $this->Task->params['output'] = $this->path . DS;
<ide><path>lib/Cake/Test/TestCase/Console/ShellTest.php
<ide>
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\App;
<add>use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Folder;
<ide> use Cake\Utility\Hash;
<ide>
<add>/**
<add> * Class for testing merging vars
<add> */
<add>class MergeShell extends Shell {
<add>
<add> public $tasks = array('DbConfig', 'Fixture');
<add>
<add> public $uses = array('Comment');
<add>
<add>}
<add>
<ide> /**
<ide> * ShellTestShell class
<ide> *
<ide> public function testInitialize() {
<ide> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/'),
<ide> 'Model' => array(CAKE . 'Test/TestApp/Model/')
<ide> ), App::RESET);
<add> Configure::write('App.namespace', 'TestApp');
<ide>
<ide> Plugin::load('TestPlugin');
<ide> $this->Shell->uses = array('TestPlugin.TestPluginPost');
<ide> public function testInitialize() {
<ide> $this->Shell->initialize();
<ide> $this->assertTrue(isset($this->Shell->Comment));
<ide> $this->assertInstanceOf('TestApp\Model\Comment', $this->Shell->Comment);
<del> $this->assertEquals('Comment', $this->Shell->modelClass);
<add> $this->assertEquals('TestApp\Model\Comment', $this->Shell->modelClass);
<ide>
<ide> App::build();
<ide> }
<ide> public function testInitialize() {
<ide> */
<ide> public function testLoadModel() {
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
<del> 'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS)
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS),
<add> 'Model' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Model' . DS)
<ide> ), App::RESET);
<add> Configure::write('App.namespace', 'TestApp');
<ide>
<del> $Shell = new TestMergeShell();
<add> $Shell = new MergeShell();
<ide> $this->assertEquals('Comment', $Shell->Comment->alias);
<del> $this->assertInstanceOf('Comment', $Shell->Comment);
<add> $this->assertInstanceOf('TestApp\Model\Comment', $Shell->Comment);
<ide> $this->assertEquals('Comment', $Shell->modelClass);
<ide>
<del> CakePlugin::load('TestPlugin');
<add> Plugin::load('TestPlugin');
<ide> $this->Shell->loadModel('TestPlugin.TestPluginPost');
<ide> $this->assertTrue(isset($this->Shell->TestPluginPost));
<del> $this->assertInstanceOf('TestPluginPost', $this->Shell->TestPluginPost);
<add> $this->assertInstanceOf('TestPlugin\Model\TestPluginPost', $this->Shell->TestPluginPost);
<ide> $this->assertEquals('TestPluginPost', $this->Shell->modelClass);
<del> CakePlugin::unload('TestPlugin');
<ide>
<ide> App::build();
<add> Plugin::unload('TestPlugin');
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Controller/Component/AuthComponentTest.php
<ide> use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<add>use Cake\Model\Datasource\Session;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide> use Cake\Routing\Dispatcher;
<ide> public function testUser() {
<ide> * @return void
<ide> */
<ide> public function testStatelessAuthNoRedirect() {
<del> if (CakeSession::id()) {
<add> if (Session::id()) {
<ide> session_destroy();
<del> CakeSession::$id = null;
<add> Session::$id = null;
<ide> }
<ide> $_SESSION = null;
<ide>
<ide> public function testStatelessAuthNoRedirect() {
<ide> $this->assertFalse($result);
<ide>
<ide> $this->assertNull($this->Controller->testUrl);
<del> $this->assertNull(CakeSession::id());
<add> $this->assertNull(Session::id());
<ide> }
<ide>
<ide> /**
<ide> public function testStatelessAuthNoRedirect() {
<ide> * @return void
<ide> */
<ide> public function testStatelessAuthNoSessionStart() {
<del> if (CakeSession::id()) {
<add> if (Session::id()) {
<ide> session_destroy();
<del> CakeSession::$id = null;
<add> Session::$id = null;
<ide> }
<ide> $_SESSION = null;
<ide>
<ide> public function testStatelessAuthNoSessionStart() {
<ide> $result = $this->Auth->startup($this->Controller);
<ide> $this->assertTrue($result);
<ide>
<del> $this->assertNull(CakeSession::id());
<add> $this->assertNull(Session::id());
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/View/Helper/FormHelperTest.php
<ide> public function testMonth() {
<ide> $result = $this->Form->month('Project.release');
<ide>
<ide> $expected = array(
<del> array('select' => array('name' => 'data[Project][release][month]', 'id' => 'ProjectReleaseMonth')),
<add> array('select' => array('name' => 'Project[release][month]', 'id' => 'ProjectReleaseMonth')),
<ide> array('option' => array('value' => '')),
<ide> '/option',
<ide> array('option' => array('value' => '01')),
<ide> public function testDay() {
<ide> $result = $this->Form->day('Project.release');
<ide>
<ide> $expected = array(
<del> array('select' => array('name' => 'data[Project][release][day]', 'id' => 'ProjectReleaseDay')),
<add> array('select' => array('name' => 'Project[release][day]', 'id' => 'ProjectReleaseDay')),
<ide> array('option' => array('value' => '')),
<ide> '/option',
<ide> array('option' => array('value' => '01')),
<ide> public function testHour() {
<ide> $this->Form->request->data['Model']['field'] = '2050-10-10 01:12:32';
<ide> $result = $this->Form->hour('Model.field', true);
<ide> $expected = array(
<del> array('select' => array('name' => 'data[Model][field][hour]', 'id' => 'ModelFieldHour')),
<add> array('select' => array('name' => 'Model[field][hour]', 'id' => 'ModelFieldHour')),
<ide> array('option' => array('value' => '')),
<ide> '/option',
<ide> array('option' => array('value' => '00')),
<ide><path>lib/Cake/TestSuite/Fixture/FixtureManager.php
<ide> public function unload(TestCase $test) {
<ide> * @throws UnexpectedValueException if $name is not a previously loaded class
<ide> */
<ide> public function loadSingle($name, $db = null, $dropTables = true) {
<del> $name .= 'Fixture';
<ide> if (isset($this->_fixtureMap[$name])) {
<ide> $fixture = $this->_fixtureMap[$name];
<ide> if (!$db) {
<ide><path>lib/Cake/Utility/Xml.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error;
<ide> use Cake\Network\Http\Client;
<add>use \DOMDocument;
<ide>
<ide> /**
<ide> * XML handling for Cake.
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> use Cake\Utility\Security;
<ide> use Cake\View\Helper;
<ide> use Cake\View\View;
<add>use \DateTime;
<ide>
<ide> /**
<ide> * Form helper library. | 13 |
Javascript | Javascript | avoid bind and properly clean up in compat | 0d762af48ea4cc298d59724ef5c9d06ff2c6a066 | <ide><path>lib/internal/http2/compat.js
<ide> const {
<ide> } = require('internal/errors').codes;
<ide> const { kSocket } = require('internal/http2/util');
<ide>
<del>const kFinish = Symbol('finish');
<ide> const kBeginSend = Symbol('begin-send');
<ide> const kState = Symbol('state');
<ide> const kStream = Symbol('stream');
<ide> const proxySocketHandler = {
<ide> }
<ide> };
<ide>
<add>function onStreamCloseRequest() {
<add> const req = this[kRequest];
<add>
<add> if (req === undefined)
<add> return;
<add>
<add> const state = req[kState];
<add> state.closed = true;
<add>
<add> req.push(null);
<add> // if the user didn't interact with incoming data and didn't pipe it,
<add> // dump it for compatibility with http1
<add> if (!state.didRead && !req._readableState.resumeScheduled)
<add> req.resume();
<add>
<add> this[kProxySocket] = null;
<add> this[kRequest] = undefined;
<add>
<add> req.emit('close');
<add>}
<add>
<ide> class Http2ServerRequest extends Readable {
<ide> constructor(stream, headers, options, rawHeaders) {
<ide> super(options);
<ide> class Http2ServerRequest extends Readable {
<ide> stream.on('end', onStreamEnd);
<ide> stream.on('error', onStreamError);
<ide> stream.on('aborted', onStreamAbortedRequest);
<del> stream.on('close', this[kFinish].bind(this));
<add> stream.on('close', onStreamCloseRequest);
<ide> this.on('pause', onRequestPause);
<ide> this.on('resume', onRequestResume);
<ide> }
<ide> class Http2ServerRequest extends Readable {
<ide> return;
<ide> this[kStream].setTimeout(msecs, callback);
<ide> }
<del>
<del> [kFinish]() {
<del> const state = this[kState];
<del> if (state.closed)
<del> return;
<del> state.closed = true;
<del> this.push(null);
<del> this[kStream][kRequest] = undefined;
<del> // if the user didn't interact with incoming data and didn't pipe it,
<del> // dump it for compatibility with http1
<del> if (!state.didRead && !this._readableState.resumeScheduled)
<del> this.resume();
<del> this.emit('close');
<del> }
<ide> }
<ide>
<ide> function onStreamTrailersReady() {
<del> this[kStream].sendTrailers(this[kTrailers]);
<add> this.sendTrailers(this[kResponse][kTrailers]);
<add>}
<add>
<add>function onStreamCloseResponse() {
<add> const res = this[kResponse];
<add>
<add> if (res === undefined)
<add> return;
<add>
<add> const state = res[kState];
<add>
<add> if (this.headRequest !== state.headRequest)
<add> return;
<add>
<add> state.closed = true;
<add>
<add> this[kProxySocket] = null;
<add> this[kResponse] = undefined;
<add>
<add> res.emit('finish');
<add> res.emit('close');
<ide> }
<ide>
<ide> class Http2ServerResponse extends Stream {
<ide> class Http2ServerResponse extends Stream {
<ide> this.writable = true;
<ide> stream.on('drain', onStreamDrain);
<ide> stream.on('aborted', onStreamAbortedResponse);
<del> stream.on('close', this[kFinish].bind(this));
<del> stream.on('wantTrailers', onStreamTrailersReady.bind(this));
<add> stream.on('close', onStreamCloseResponse);
<add> stream.on('wantTrailers', onStreamTrailersReady);
<ide> }
<ide>
<ide> // User land modules such as finalhandler just check truthiness of this
<ide> class Http2ServerResponse extends Stream {
<ide> this.writeHead(this[kState].statusCode);
<ide>
<ide> if (isFinished)
<del> this[kFinish]();
<add> onStreamCloseResponse.call(stream);
<ide> else
<ide> stream.end();
<ide>
<ide> class Http2ServerResponse extends Stream {
<ide> this[kStream].respond(headers, options);
<ide> }
<ide>
<del> [kFinish]() {
<del> const stream = this[kStream];
<del> const state = this[kState];
<del> if (state.closed || stream.headRequest !== state.headRequest)
<del> return;
<del> state.closed = true;
<del> this[kProxySocket] = null;
<del> stream[kResponse] = undefined;
<del> this.emit('finish');
<del> this.emit('close');
<del> }
<del>
<ide> // TODO doesn't support callbacks
<ide> writeContinue() {
<ide> const stream = this[kStream]; | 1 |
Ruby | Ruby | rename outdated_keg to linked_keg | 710db1fb720adcbb93bcf51f5f14f3dcb970a96a | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def install_dependency(dep, inherited_options)
<ide> df = dep.to_formula
<ide> tab = Tab.for_formula(df)
<ide>
<del> outdated_keg = Keg.new(df.linked_keg.realpath) if df.linked_keg.directory?
<add> linked_keg = Keg.new(df.linked_keg.realpath) if df.linked_keg.directory?
<ide>
<ide> fi = DependencyInstaller.new(df)
<ide> fi.options |= tab.used_options
<ide> def install_dependency(dep, inherited_options)
<ide> fi.debug = debug?
<ide> fi.prelude
<ide> oh1 "Installing #{f} dependency: #{Tty.green}#{dep.name}#{Tty.reset}"
<del> outdated_keg.unlink if outdated_keg
<add> linked_keg.unlink if linked_keg
<ide> fi.install
<ide> fi.caveats
<ide> fi.finish
<ide> ensure
<ide> # restore previous installation state if build failed
<del> outdated_keg.link if outdated_keg and not df.installed? rescue nil
<add> linked_keg.link if linked_keg and not df.installed? rescue nil
<ide> end
<ide>
<ide> def caveats | 1 |
PHP | PHP | rearrange check order | 2e12e8ac272699172bbc928c3f203202dc8fa855 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> protected function invalidOperatorAndValue($operator, $value)
<ide> {
<ide> $isOperator = in_array($operator, $this->operators);
<ide>
<del> return $isOperator && ! in_array($operator, ['=', '<>', '!=']) && is_null($value);
<add> return is_null($value) && $isOperator && ! in_array($operator, ['=', '<>', '!=']);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add corsearch to in the wild | b7692098918aa2c9f4124bd2710fa673f4c5eb40 | <ide><path>INTHEWILD.md
<ide> Currently, **officially** using Airflow:
<ide> 1. [Compass](https://www.compass.com) [[@wdhorton](https://github.com/wdhorton)]
<ide> 1. [ConnectWise](https://www.connectwise.com/) [[@jacobeturpin](https://github.com/jacobeturpin)]
<ide> 1. [ContaAzul](https://www.contaazul.com) [[@bern4rdelli](https://github.com/bern4rdelli), [@renanleme](https://github.com/renanleme) & [@sabino](https://github.com/sabino)]
<add>1. [Corsearch](https://corsearch.com/) [[@silvantonio](https://github.com/silvantonio), [@erjanmx](https://github.com/erjanmx), [@honarkhah](https://github.com/honarkhah), [@RogierVanDoggenaar](https://github.com/RogierVanDoggenaar), [@arekgorecki](https://github.com/arekgorecki), [@jmolpointerbp](https://github.com/jmolpointerbp)]
<ide> 1. [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<ide> 1. [Craig@Work](https://www.craigatwork.com)
<ide> 1. [Crealytics](https://crealytics.com) | 1 |
Python | Python | add tests for yandex hook | a6b04d7b9a6117c66e8b586fe9fd2a955827a0e7 | <ide><path>tests/providers/yandex/hooks/test_yandex.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># 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,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import unittest
<add>from unittest import mock
<add>
<add>from airflow.exceptions import AirflowException
<add>from airflow.providers.yandex.hooks.yandex import YandexCloudBaseHook
<add>
<add>
<add>class TestYandexHook(unittest.TestCase):
<add>
<add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection')
<add> @mock.patch('airflow.providers.yandex.hooks.yandex.YandexCloudBaseHook._get_credentials')
<add> def test_client_created_without_exceptions(self, get_credentials_mock,
<add> get_connection_mock):
<add> """ tests `init` method to validate client creation when all parameters are passed """
<add>
<add> # Inputs to constructor
<add> default_folder_id = 'test_id'
<add> default_public_ssh_key = 'test_key'
<add>
<add> extra_dejson = '{"extras": "extra"}'
<add> get_connection_mock['extra_dejson'] = "sdsd"
<add> get_connection_mock.extra_dejson = '{"extras": "extra"}'
<add> get_connection_mock.return_value = mock.\
<add> Mock(connection_id='yandexcloud_default', extra_dejson=extra_dejson)
<add> get_credentials_mock.return_value = {"token": 122323}
<add>
<add> hook = YandexCloudBaseHook(None,
<add> default_folder_id, default_public_ssh_key)
<add> self.assertIsNotNone(hook.client)
<add>
<add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection')
<add> def test_get_credentials_raise_exception(self, get_connection_mock):
<add>
<add> """ tests 'get_credentials' method raising exception if none of the required fields are passed."""
<add>
<add> # Inputs to constructor
<add> default_folder_id = 'test_id'
<add> default_public_ssh_key = 'test_key'
<add>
<add> extra_dejson = '{"extras": "extra"}'
<add> get_connection_mock['extra_dejson'] = "sdsd"
<add> get_connection_mock.extra_dejson = '{"extras": "extra"}'
<add> get_connection_mock.return_value = mock.Mock(connection_id='yandexcloud_default',
<add> extra_dejson=extra_dejson)
<add>
<add> self.assertRaises(AirflowException, YandexCloudBaseHook, None,
<add> default_folder_id, default_public_ssh_key)
<add>
<add> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection')
<add> @mock.patch('airflow.providers.yandex.hooks.yandex.YandexCloudBaseHook._get_credentials')
<add> def test_get_field(self, get_credentials_mock, get_connection_mock):
<add> # Inputs to constructor
<add> default_folder_id = 'test_id'
<add> default_public_ssh_key = 'test_key'
<add>
<add> extra_dejson = {"extra__yandexcloud__one": "value_one"}
<add> get_connection_mock['extra_dejson'] = "sdsd"
<add> get_connection_mock.extra_dejson = '{"extras": "extra"}'
<add> get_connection_mock.return_value = mock.Mock(connection_id='yandexcloud_default',
<add> extra_dejson=extra_dejson)
<add> get_credentials_mock.return_value = {"token": 122323}
<add>
<add> hook = YandexCloudBaseHook(None,
<add> default_folder_id, default_public_ssh_key)
<add>
<add> self.assertEqual(hook._get_field('one'), 'value_one')
<ide><path>tests/test_project_structure.py
<ide> 'tests/providers/microsoft/azure/sensors/test_azure_cosmos.py',
<ide> 'tests/providers/microsoft/azure/log/test_wasb_task_handler.py',
<ide> 'tests/providers/microsoft/mssql/hooks/test_mssql.py',
<del> 'tests/providers/samba/hooks/test_samba.py',
<del> 'tests/providers/yandex/hooks/test_yandex.py'
<add> 'tests/providers/samba/hooks/test_samba.py'
<ide> }
<ide>
<ide> | 2 |
Javascript | Javascript | mover vector3 legacy code | 80bfa452412ab24774c9268fb3f71fa9408586cc | <ide><path>src/Three.Legacy.js
<ide> Object.defineProperties( THREE.Box3.prototype, {
<ide> }
<ide> } );
<ide>
<add>//
<add>
<add>Object.defineProperties( THREE.Vector3.prototype, {
<add> setEulerFromRotationMatrix: {
<add> value: function () {
<add> console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
<add> }
<add> },
<add> setEulerFromQuaternion: {
<add> value: function () {
<add> console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
<add> }
<add> },
<add> getPositionFromMatrix: {
<add> value: function ( m ) {
<add> console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
<add> return this.setFromMatrixPosition( m );
<add> }
<add> },
<add> getScaleFromMatrix: {
<add> value: function ( m ) {
<add> console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
<add> return this.setFromMatrixScale( m );
<add> }
<add> },
<add> getColumnFromMatrix: {
<add> value: function ( index, matrix ) {
<add> console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
<add> return this.setFromMatrixColumn( index, matrix );
<add> }
<add> }
<add>} );
<add>
<add>//
<add>
<ide> Object.defineProperties( THREE.Light.prototype, {
<ide> onlyShadow: {
<ide> set: function ( value ) {
<ide><path>src/math/Vector3.js
<ide> THREE.Vector3.prototype = {
<ide>
<ide> },
<ide>
<del> setEulerFromRotationMatrix: function ( m, order ) {
<del>
<del> console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
<del>
<del> },
<del>
<del> setEulerFromQuaternion: function ( q, order ) {
<del>
<del> console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
<del>
<del> },
<del>
<del> getPositionFromMatrix: function ( m ) {
<del>
<del> console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
<del>
<del> return this.setFromMatrixPosition( m );
<del>
<del> },
<del>
<del> getScaleFromMatrix: function ( m ) {
<del>
<del> console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
<del>
<del> return this.setFromMatrixScale( m );
<del>
<del> },
<del>
<del> getColumnFromMatrix: function ( index, matrix ) {
<del>
<del> console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
<del>
<del> return this.setFromMatrixColumn( index, matrix );
<del>
<del> },
<del>
<ide> setFromMatrixPosition: function ( m ) {
<ide>
<ide> this.x = m.elements[ 12 ]; | 2 |
Python | Python | add compatibility for py-cpuinfo 7.0.0 or higher | ca8e2c3a94279646655a2f78cb9a598e8b758ed3 | <ide><path>glances/plugins/glances_quicklook.py
<ide> def update(self):
<ide> stats['cpu_name'] = cpu_info.get('brand', 'CPU')
<ide> if 'hz_actual_raw' in cpu_info:
<ide> stats['cpu_hz_current'] = cpu_info['hz_actual_raw'][0]
<add> elif 'hz_actual' in cpu_info:
<add> stats['cpu_hz_current'] = cpu_info['hz_actual'][0]
<ide> if 'hz_advertised_raw' in cpu_info:
<ide> stats['cpu_hz'] = cpu_info['hz_advertised_raw'][0]
<add> elif 'hz_advertised' in cpu_info:
<add> stats['cpu_hz'] = cpu_info['hz_advertised'][0]
<ide>
<ide> # Update the stats
<ide> self.stats = stats | 1 |
PHP | PHP | apply fixes from styleci | 06ddd7c7f350d4b4b9cfacf04b87d57f76c7d909 | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php
<ide> protected function gatherKeysByType($type, $keyType)
<ide> return $keyType !== 'string'
<ide> ? array_keys($this->dictionary[$type])
<ide> : array_map(function ($modelId) {
<del> return (string) $modelId;
<del> }, array_keys($this->dictionary[$type]));
<add> return (string) $modelId;
<add> }, array_keys($this->dictionary[$type]));
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add whitlockjc to collaborators | e6f6f347744e30dbbfbcde9fc2ce3fde450108cd | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** <thlorenz@gmx.de>
<ide> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com>
<ide> * [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** <vladimir.kurchatkin@gmail.com>
<add>* [whitlockjc](https://github.com/whitlockjc) - **Jeremy Whitlock** <jwhitlock@apache.org>
<ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) - **Yosuke Furukawa** <yosuke.furukawa@gmail.com>
<ide> * [zkat](https://github.com/zkat) - **Kat Marchán** <kzm@sykosomatic.org>
<ide> | 1 |
PHP | PHP | fix reflection exceptions | c6e8357e19b10a800df8a67446f23310f4e83d1f | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function gatherRouteMiddleware(Route $route)
<ide> return true;
<ide> }
<ide>
<add> if (! class_exists($name)) {
<add> return false;
<add> }
<add>
<ide> $reflection = new ReflectionClass($name);
<ide>
<ide> return collect($excluded)->contains(function ($exclude) use ($reflection) {
<del> return $reflection->isSubclassOf($exclude);
<add> return class_exists($exclude) && $reflection->isSubclassOf($exclude);
<ide> });
<ide> })->values();
<ide> | 1 |
Text | Text | add packages list for archlinux [ci skip] | 1565821c3432b5723909bf8b3b08d4230efa42f6 | <ide><path>guides/source/development_dependencies_install.md
<ide> If you are on Fedora or CentOS, you can run
<ide> $ sudo yum install libxml2 libxml2-devel libxslt libxslt-devel
<ide> ```
<ide>
<add>If you are running Arch Linux, you're done with:
<add>
<add>```bash
<add>$ sudo pacman -S lixml2 libxslt
<add>```
<add>
<ide> If you have any problems with these libraries, you can install them manually by compiling the source code. Just follow the instructions at the [Red Hat/CentOS section of the Nokogiri tutorials](http://nokogiri.org/tutorials/installing_nokogiri.html#red_hat__centos) .
<ide>
<ide> Also, SQLite3 and its development files for the `sqlite3` gem — in Ubuntu you're done with just
<ide> And if you are on Fedora or CentOS, you're done with
<ide> $ sudo yum install sqlite3 sqlite3-devel
<ide> ```
<ide>
<add>If you are on Arch Linux, you will need to run:
<add>
<add>```bash
<add>$ sudo pacman -S sqlite
<add>```
<add>
<ide> Get a recent version of [Bundler](http://gembundler.com/)
<ide>
<ide> ```bash
<ide> $ sudo yum install mysql-server mysql-devel
<ide> $ sudo yum install postgresql-server postgresql-devel
<ide> ```
<ide>
<add>If you are running Arch Linux, MySQL isn't supported anymore so you will need to
<add>use MariaDB instead (see [this announcement](https://www.archlinux.org/news/mariadb-replaces-mysql-in-repositories/)):
<add>
<add>```bash
<add>$ sudo pacman -S mariadb libmariadbclient mariadb-clients
<add>$ sudo pacman -S postgresql postgresql-libs
<add>```
<add>
<ide> After that, run:
<ide>
<ide> ```bash | 1 |
Go | Go | update testupdatepidslimit to be more atomic | 1101568fa11cb00d8f8de3ff8953c581c351928f | <ide><path>integration/container/update_linux_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<del> "github.com/docker/docker/api/types"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/integration/internal/container"
<ide> func TestUpdatePidsLimit(t *testing.T) {
<ide> oldAPIclient := request.NewAPIClient(t, client.WithVersion("1.24"))
<ide> ctx := context.Background()
<ide>
<del> cID := container.Run(t, ctx, apiClient)
<del>
<ide> intPtr := func(i int64) *int64 {
<ide> return &i
<ide> }
<ide>
<ide> for _, test := range []struct {
<ide> desc string
<ide> oldAPI bool
<add> initial *int64
<ide> update *int64
<ide> expect int64
<ide> expectCg string
<ide> }{
<ide> {desc: "update from none", update: intPtr(32), expect: 32, expectCg: "32"},
<del> {desc: "no change", update: nil, expectCg: "32"},
<del> {desc: "update lower", update: intPtr(16), expect: 16, expectCg: "16"},
<del> {desc: "update on old api ignores value", oldAPI: true, update: intPtr(10), expect: 16, expectCg: "16"},
<del> {desc: "unset limit", update: intPtr(0), expect: 0, expectCg: "max"},
<del> {desc: "reset", update: intPtr(32), expect: 32, expectCg: "32"},
<del> {desc: "unset limit with minus one", update: intPtr(-1), expect: 0, expectCg: "max"},
<del> {desc: "reset", update: intPtr(32), expect: 32, expectCg: "32"},
<del> {desc: "unset limit with minus two", update: intPtr(-2), expect: 0, expectCg: "max"},
<add> {desc: "no change", initial: intPtr(32), expect: 32, expectCg: "32"},
<add> {desc: "update lower", initial: intPtr(32), update: intPtr(16), expect: 16, expectCg: "16"},
<add> {desc: "update on old api ignores value", oldAPI: true, initial: intPtr(32), update: intPtr(16), expect: 32, expectCg: "32"},
<add> {desc: "unset limit with zero", initial: intPtr(32), update: intPtr(0), expect: 0, expectCg: "max"},
<add> {desc: "unset limit with minus one", initial: intPtr(32), update: intPtr(-1), expect: 0, expectCg: "max"},
<add> {desc: "unset limit with minus two", initial: intPtr(32), update: intPtr(-2), expect: 0, expectCg: "max"},
<ide> } {
<ide> c := apiClient
<ide> if test.oldAPI {
<ide> c = oldAPIclient
<ide> }
<ide>
<del> var before types.ContainerJSON
<del> if test.update == nil {
<del> var err error
<del> before, err = c.ContainerInspect(ctx, cID)
<del> assert.NilError(t, err)
<del> }
<del>
<ide> t.Run(test.desc, func(t *testing.T) {
<add> // Using "network=host" to speed up creation (13.96s vs 6.54s)
<add> cID := container.Run(t, ctx, apiClient, container.WithPidsLimit(test.initial), container.WithNetworkMode("host"))
<add>
<ide> _, err := c.ContainerUpdate(ctx, cID, containertypes.UpdateConfig{
<ide> Resources: containertypes.Resources{
<ide> PidsLimit: test.update,
<ide> func TestUpdatePidsLimit(t *testing.T) {
<ide> inspect, err := c.ContainerInspect(ctx, cID)
<ide> assert.NilError(t, err)
<ide> assert.Assert(t, inspect.HostConfig.Resources.PidsLimit != nil)
<del>
<del> if test.update == nil {
<del> assert.Assert(t, before.HostConfig.Resources.PidsLimit != nil)
<del> assert.Equal(t, *before.HostConfig.Resources.PidsLimit, *inspect.HostConfig.Resources.PidsLimit)
<del> } else {
<del> assert.Equal(t, *inspect.HostConfig.Resources.PidsLimit, test.expect)
<del> }
<add> assert.Equal(t, *inspect.HostConfig.Resources.PidsLimit, test.expect)
<ide>
<ide> ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
<ide> defer cancel()
<ide><path>integration/internal/container/ops.go
<ide> func WithAutoRemove(c *TestContainerConfig) {
<ide> c.HostConfig.AutoRemove = true
<ide> }
<ide>
<add>// WithPidsLimit sets the container's "pids-limit
<add>func WithPidsLimit(limit *int64) func(*TestContainerConfig) {
<add> return func(c *TestContainerConfig) {
<add> if c.HostConfig == nil {
<add> c.HostConfig = &containertypes.HostConfig{}
<add> }
<add> c.HostConfig.PidsLimit = limit
<add> }
<add>}
<add>
<ide> // WithRestartPolicy sets container's restart policy
<ide> func WithRestartPolicy(policy string) func(c *TestContainerConfig) {
<ide> return func(c *TestContainerConfig) { | 2 |
Python | Python | add node_use_openssl check to install.py | 471aa19ffa5f61d3f50fa6566b283c7ee0e9d74a | <ide><path>tools/install.py
<ide> def headers(action):
<ide> if 'false' == variables.get('node_shared_libuv'):
<ide> subdir_files('deps/uv/include', 'include/node/', action)
<ide>
<del> if 'false' == variables.get('node_shared_openssl'):
<add> if 'true' == variables.get('node_use_openssl') and \
<add> 'false' == variables.get('node_shared_openssl'):
<ide> subdir_files('deps/openssl/openssl/include/openssl', 'include/node/openssl/', action)
<ide> subdir_files('deps/openssl/config/archs', 'include/node/openssl/archs', action)
<ide> action(['deps/openssl/config/opensslconf.h'], 'include/node/openssl/') | 1 |
Ruby | Ruby | fix relocation of frameworks | 06634edab7f5dee0904cc779ef8c2c109815766c | <ide><path>Library/Homebrew/keg_relocate.rb
<ide> class Keg
<ide> PREFIX_PLACEHOLDER = "".freeze
<ide> CELLAR_PLACEHOLDER = "".freeze
<ide>
<add> # Matches framework references like `XXX.framework/Versions/YYY/XXX` and
<add> # `XXX.framework/XXX`, both with or without a slash-delimited prefix.
<add> FRAMEWORK_RX = %r{(?:^|/)(?<suffix>(?<name>[^/]+)\.framework/(?:Versions/[^/]+/)?\k<name>)$}.freeze
<add>
<ide> def fix_install_names(options = {})
<ide> mach_o_files.each do |file|
<ide> file.ensure_writable do
<ide> def fixed_name(file, bad_name)
<ide> "@loader_path/#{bad_name}"
<ide> elsif file.mach_o_executable? && (lib + bad_name).exist?
<ide> "#{lib}/#{bad_name}"
<del> elsif (abs_name = find_dylib(Pathname.new(bad_name).basename)) && abs_name.exist?
<add> elsif (abs_name = find_dylib(bad_name)) && abs_name.exist?
<ide> abs_name.to_s
<ide> else
<ide> opoo "Could not fix #{bad_name} in #{file}"
<ide> def dylib_id_for(file, options)
<ide> opt_record.join(relative_dirname, basename).to_s
<ide> end
<ide>
<del> def find_dylib(name)
<del> lib.find { |pn| break pn if pn.basename == name } if lib.directory?
<add> def find_dylib_suffix_from(bad_name)
<add> if (framework = bad_name.match(FRAMEWORK_RX))
<add> framework["suffix"]
<add> else
<add> File.basename(bad_name)
<add> end
<add> end
<add>
<add> def find_dylib(bad_name)
<add> return unless lib.directory?
<add> suffix = "/#{find_dylib_suffix_from(bad_name)}"
<add> lib.find { |pn| break pn if pn.to_s.end_with?(suffix) }
<ide> end
<ide>
<ide> def mach_o_files | 1 |
PHP | PHP | fix cluster resolution | f21ab706def178635410b2a17a9bee38e4bf2f9b | <ide><path>src/Illuminate/Redis/Connectors/PhpRedisConnector.php
<ide> class PhpRedisConnector
<ide> * @param array $config
<ide> * @param array $clusterOptions
<ide> * @param array $options
<del> * @return \Illuminate\Redis\PredisConnection
<add> * @return \Illuminate\Redis\PhpRedisConnection
<ide> */
<ide> public function connect(array $config, array $options)
<ide> {
<ide> public function connect(array $config, array $options)
<ide> * @param array $config
<ide> * @param array $clusterOptions
<ide> * @param array $options
<del> * @return \Illuminate\Redis\PredisClusterConnection
<add> * @return \Illuminate\Redis\PhpRedisClusterConnection
<ide> */
<ide> public function connectToCluster(array $config, array $clusterOptions, array $options)
<ide> {
<ide><path>src/Illuminate/Redis/Connectors/PredisConnector.php
<ide> public function connect(array $config, array $options)
<ide> */
<ide> public function connectToCluster(array $config, array $clusterOptions, array $options)
<ide> {
<add> $clusterSpecificOptions = Arr::pull($config, 'options', []);
<add>
<ide> return new PredisClusterConnection(new Client(array_values($config), array_merge(
<del> $options, $clusterOptions, Arr::pull($config, 'options', [])
<add> $options, $clusterOptions, $clusterSpecificOptions
<ide> )));
<ide> }
<ide> }
<ide><path>src/Illuminate/Redis/RedisManager.php
<ide> protected function resolveCluster($name)
<ide> $clusterOptions = Arr::get($this->config, 'clusters.options', []);
<ide>
<ide> return $this->connector()->connectToCluster(
<del> $this->config['clusters'][$name], $clusterOptions, $this->config
<add> $this->config['clusters'][$name], $clusterOptions, Arr::get($this->config, 'options', [])
<ide> );
<ide> }
<ide> | 3 |
Javascript | Javascript | prefer textcontent to innertext | 309a88bcf62c1c64a2b91c0eb753c19209a425b2 | <ide><path>src/dom/getTextContentAccessor.js
<ide> var contentKey = null;
<ide> */
<ide> function getTextContentAccessor() {
<ide> if (!contentKey && ExecutionEnvironment.canUseDOM) {
<del> contentKey = 'innerText' in document.createElement('div') ?
<del> 'innerText' :
<del> 'textContent';
<add> // Prefer textContent to innerText because many browsers support both but
<add> // SVG <text> elements don't support innerText even when <div> does.
<add> contentKey = 'textContent' in document.createElement('div') ?
<add> 'textContent' :
<add> 'innerText';
<ide> }
<ide> return contentKey;
<ide> } | 1 |
Ruby | Ruby | remove unused constant | c937ddb5cec87168c4eb0d6c3030f771e80c2e72 | <ide><path>actionpack/lib/action_controller/metal/renderers.rb
<ide> module All
<ide> extend ActiveSupport::Concern
<ide> include Renderers
<ide>
<del> INCLUDED = []
<ide> included do
<ide> self._renderers = RENDERERS
<del> INCLUDED << self
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | display possible circular compiler dependencies | ccaca5fa17e6efdfd43cfa1735423ddb923a52b3 | <ide><path>lib/MultiCompiler.js
<ide> module.exports = class MultiCompiler extends Tapable {
<ide> validateDependencies(callback) {
<ide> const edges = [];
<ide> const missing = [];
<add> const sortEdges = (e1, e2) => {
<add> return e1.source.name.localeCompare(e2.source.name) ||
<add> e1.target.name.localeCompare(e2.target.name);
<add> };
<ide> for(const source of this.compilers) {
<ide> if(source.dependencies) {
<ide> for(const dep of source.dependencies) {
<ide> module.exports = class MultiCompiler extends Tapable {
<ide> }
<ide> }
<ide> if(edges.length > 0) {
<del> errors.unshift("Circular dependency found in compiler dependencies.");
<add> const lines = edges.sort(sortEdges).map(edge => `${edge.source.name} -> ${edge.target.name}`);
<add> lines.unshift("Circular dependency found in compiler dependencies.");
<add> errors.unshift(lines.join("\n"));
<ide> }
<ide> if(errors.length > 0) {
<ide> const message = errors.join("\n"); | 1 |
Python | Python | add werkzeug to flask --version | 3fd51c65fb4774b10848715b62ec284a0b86a6b1 | <ide><path>flask/cli.py
<ide> from functools import update_wrapper
<ide> from operator import attrgetter
<ide> from threading import Lock, Thread
<add>import werkzeug
<ide>
<ide> import click
<ide> from werkzeug.utils import import_string
<ide> def locate_app(script_info, module_name, app_name, raise_if_not_found=True):
<ide> def get_version(ctx, param, value):
<ide> if not value or ctx.resilient_parsing:
<ide> return
<del> message = 'Flask %(version)s\nPython %(python_version)s'
<add> message = 'Python %(python_version)s\nFlask %(version)s\nWerkzeug %(werkzeug_version)s'
<ide> click.echo(message % {
<ide> 'version': __version__,
<ide> 'python_version': sys.version,
<add> 'werkzeug_version': werkzeug.__version__,
<ide> }, color=ctx.color)
<ide> ctx.exit()
<ide> | 1 |
Javascript | Javascript | add missing import. fixes | 3952ae4683616f7a2e0be4c11229185ad40ade1f | <ide><path>src/layout/chord.js
<ide> import "../arrays/range";
<ide> import "../math/trigonometry";
<add>import "layout";
<ide>
<ide> d3.layout.chord = function() {
<ide> var chord = {},
<ide><path>test/layout/chord-test.js
<add>var vows = require("vows"),
<add> load = require("../load"),
<add> assert = require("../assert");
<add>
<add>var suite = vows.describe("d3.layout.chord");
<add>
<add>suite.addBatch({
<add> "chord": {
<add> topic: load("layout/chord").expression("d3.layout.chord"),
<add> "of a simple matrix": {
<add> topic: function(chord) {
<add> return chord()
<add> .padding(.05)
<add> .sortSubgroups(function(a, b) { return b - a; })
<add> .matrix([
<add> [11975, 5871, 8916, 2868],
<add> [ 1951, 10048, 2060, 6171],
<add> [ 8010, 16145, 8090, 8045],
<add> [ 1013, 990, 940, 6907]
<add> ]);
<add> },
<add> "computes chord groups": function(chord) {
<add> var groups = chord.groups();
<add> assert.equal(groups.length, 4);
<add>
<add> assert.equal(groups[0].index, 0);
<add> assert.inDelta(groups[0].startAngle, 0.0000000000000000, 1e-6);
<add> assert.inDelta(groups[0].endAngle, 1.8024478065173115, 1e-6);
<add> assert.inDelta(groups[0].value, 29630, 1e-6);
<add>
<add> assert.equal(groups[1].index, 1);
<add> assert.inDelta(groups[1].startAngle, 1.8524478065173116, 1e-6);
<add> assert.inDelta(groups[1].endAngle, 3.0830761941597418, 1e-6);
<add> assert.inDelta(groups[1].value, 20230, 1e-6);
<add>
<add> assert.equal(groups[2].index, 2);
<add> assert.inDelta(groups[2].startAngle, 3.1330761941597416, 1e-6);
<add> assert.inDelta(groups[2].endAngle, 5.583991554422396, 1e-6);
<add> assert.inDelta(groups[2].value, 40290, 1e-6);
<add>
<add> assert.equal(groups[3].index, 3);
<add> assert.inDelta(groups[3].startAngle, 5.6339915544223960, 1e-6);
<add> assert.inDelta(groups[3].endAngle, 6.233185307179585, 1e-6);
<add> assert.inDelta(groups[3].value, 9850, 1e-6);
<add> },
<add> "computes chords": function(chord) {
<add> var chords = chord.chords();
<add> assert.equal(chords.length, 10);
<add>
<add> assert.equal(chords[0].source.index, 0);
<add> assert.equal(chords[0].source.subindex, 0);
<add> assert.inDelta(chords[0].source.startAngle, 0, 1e-6);
<add> assert.inDelta(chords[0].source.endAngle, 0.7284614405347555, 1e-6);
<add> assert.equal(chords[0].source.value, 11975);
<add> assert.equal(chords[0].target.index, 0);
<add> assert.equal(chords[0].target.subindex, 0);
<add> assert.inDelta(chords[0].target.startAngle, 0, 1e-6);
<add> assert.inDelta(chords[0].target.endAngle, 0.7284614405347555, 1e-6);
<add> assert.equal(chords[0].target.value, 11975);
<add>
<add> assert.equal(chords[1].source.index, 0);
<add> assert.equal(chords[1].source.subindex, 1);
<add> assert.inDelta(chords[1].source.startAngle, 1.2708382425228875, 1e-6);
<add> assert.inDelta(chords[1].source.endAngle, 1.6279820519074009, 1e-6);
<add> assert.equal(chords[1].source.value, 5871);
<add> assert.equal(chords[1].target.index, 1);
<add> assert.equal(chords[1].target.subindex, 0);
<add> assert.inDelta(chords[1].target.startAngle, 2.964393248816668, 1e-6);
<add> assert.inDelta(chords[1].target.endAngle, 3.0830761941597418, 1e-6);
<add> assert.equal(chords[1].target.value, 1951);
<add>
<add> assert.equal(chords[2].source.index, 0);
<add> assert.equal(chords[2].source.subindex, 2);
<add> assert.inDelta(chords[2].source.startAngle, 0.7284614405347555, 1e-6);
<add> assert.inDelta(chords[2].source.endAngle, 1.2708382425228875, 1e-6);
<add> assert.equal(chords[2].source.value, 8916);
<add> assert.equal(chords[2].target.index, 2);
<add> assert.equal(chords[2].target.subindex, 0);
<add> assert.inDelta(chords[2].target.startAngle, 5.0967284113173115, 1e-6);
<add> assert.inDelta(chords[2].target.endAngle, 5.583991554422396, 1e-6);
<add> assert.equal(chords[2].target.value, 8010);
<add>
<add> assert.equal(chords[3].source.index, 0);
<add> assert.equal(chords[3].source.subindex, 3);
<add> assert.inDelta(chords[3].source.startAngle, 1.6279820519074009, 1e-6);
<add> assert.inDelta(chords[3].source.endAngle, 1.8024478065173115, 1e-6);
<add> assert.equal(chords[3].source.value, 2868);
<add> assert.equal(chords[3].target.index, 3);
<add> assert.equal(chords[3].target.subindex, 0);
<add> assert.inDelta(chords[3].target.startAngle, 6.05415716358929, 1e-6);
<add> assert.inDelta(chords[3].target.endAngle, 6.115779830751019, 1e-6);
<add> assert.equal(chords[3].target.value, 1013);
<add>
<add> assert.equal(chords[4].source.index, 1);
<add> assert.equal(chords[4].source.subindex, 1);
<add> assert.inDelta(chords[4].source.startAngle, 1.8524478065173116, 1e-6);
<add> assert.inDelta(chords[4].source.endAngle, 2.4636862661827164, 1e-6);
<add> assert.equal(chords[4].source.value, 10048);
<add> assert.equal(chords[4].target.index, 1);
<add> assert.equal(chords[4].target.subindex, 1);
<add> assert.inDelta(chords[4].target.startAngle, 1.8524478065173116, 1e-6);
<add> assert.inDelta(chords[4].target.endAngle, 2.4636862661827164, 1e-6);
<add> assert.equal(chords[4].target.value, 10048);
<add>
<add> assert.equal(chords[5].source.index, 2);
<add> assert.equal(chords[5].source.subindex, 1);
<add> assert.inDelta(chords[5].source.startAngle, 3.1330761941597416, 1e-6);
<add> assert.inDelta(chords[5].source.endAngle, 4.1152064620038855, 1e-6);
<add> assert.equal(chords[5].source.value, 16145);
<add> assert.equal(chords[5].target.index, 1);
<add> assert.equal(chords[5].target.subindex, 2);
<add> assert.inDelta(chords[5].target.startAngle, 2.8390796314887687, 1e-6);
<add> assert.inDelta(chords[5].target.endAngle, 2.964393248816668, 1e-6);
<add> assert.equal(chords[5].target.value, 2060);
<add>
<add> assert.equal(chords[6].source.index, 1);
<add> assert.equal(chords[6].source.subindex, 3);
<add> assert.inDelta(chords[6].source.startAngle, 2.4636862661827164, 1e-6);
<add> assert.inDelta(chords[6].source.endAngle, 2.8390796314887687, 1e-6);
<add> assert.equal(chords[6].source.value, 6171);
<add> assert.equal(chords[6].target.index, 3);
<add> assert.equal(chords[6].target.subindex, 1);
<add> assert.inDelta(chords[6].target.startAngle, 6.115779830751019, 1e-6);
<add> assert.inDelta(chords[6].target.endAngle, 6.176003365292097, 1e-6);
<add> assert.equal(chords[6].target.value, 990);
<add>
<add> assert.equal(chords[7].source.index, 2);
<add> assert.equal(chords[7].source.subindex, 2);
<add> assert.inDelta(chords[7].source.startAngle, 4.1152064620038855, 1e-6);
<add> assert.inDelta(chords[7].source.endAngle, 4.607336153354714, 1e-6);
<add> assert.equal(chords[7].source.value, 8090);
<add> assert.equal(chords[7].target.index, 2);
<add> assert.equal(chords[7].target.subindex, 2);
<add> assert.inDelta(chords[7].target.startAngle, 4.1152064620038855, 1e-6);
<add> assert.inDelta(chords[7].target.endAngle, 4.607336153354714, 1e-6);
<add> assert.equal(chords[7].target.value, 8090);
<add>
<add> assert.equal(chords[8].source.index, 2);
<add> assert.equal(chords[8].source.subindex, 3);
<add> assert.inDelta(chords[8].source.startAngle, 4.607336153354714, 1e-6);
<add> assert.inDelta(chords[8].source.endAngle, 5.0967284113173115, 1e-6);
<add> assert.equal(chords[8].source.value, 8045);
<add> assert.equal(chords[8].target.index, 3);
<add> assert.equal(chords[8].target.subindex, 2);
<add> assert.inDelta(chords[8].target.startAngle, 6.176003365292097, 1e-6);
<add> assert.inDelta(chords[8].target.endAngle, 6.233185307179585, 1e-6);
<add> assert.equal(chords[8].target.value, 940);
<add>
<add> assert.equal(chords[9].source.index, 3);
<add> assert.equal(chords[9].source.subindex, 3);
<add> assert.inDelta(chords[9].source.startAngle, 5.633991554422396, 1e-6);
<add> assert.inDelta(chords[9].source.endAngle, 6.05415716358929, 1e-6);
<add> assert.equal(chords[9].source.value, 6907);
<add> assert.equal(chords[9].target.index, 3);
<add> assert.equal(chords[9].target.subindex, 3);
<add> assert.inDelta(chords[9].target.startAngle, 5.633991554422396, 1e-6);
<add> assert.inDelta(chords[9].target.endAngle, 6.05415716358929, 1e-6);
<add> assert.equal(chords[9].target.value, 6907);
<add> }
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 2 |
Text | Text | remove the specific timing from the readme | d01a7239339760ef410ca689aead1de0ba438a6a | <ide><path>resnet/README.md
<ide> bazel-bin/resnet/resnet_main --train_data_path=cifar10/data_batch* \
<ide> --dataset='cifar10' \
<ide> --num_gpus=1
<ide>
<del># Note that training takes about 5 hours on a K40 GPU, but the training script will not produce any output. In the meantime you can check on progress using tensorboard:
<add># Note that the training script will not produce any output. In the meantime, you can check on its progress using tensorboard:
<ide> tensorboard --logdir=/tmp/resnet_model
<ide>
<ide> # Evaluate the model. | 1 |
Javascript | Javascript | fix odd grammar in api docs | e569f8fc4d82fd340b4752ae6764047fbbfe989a | <ide><path>src/dock.js
<ide> module.exports = class Dock {
<ide> return this.paneContainer.getTextEditors()
<ide> }
<ide>
<del> // Essential: Get the active item if it is an {TextEditor}.
<add> // Essential: Get the active item if it is a {TextEditor}.
<ide> //
<del> // Returns an {TextEditor} or `undefined` if the current active item is not an
<add> // Returns a {TextEditor} or `undefined` if the current active item is not a
<ide> // {TextEditor}.
<ide> getActiveTextEditor () {
<ide> const activeItem = this.getActivePaneItem() | 1 |
Javascript | Javascript | remove references to cache | 27a6f36738ef4b1c9809ea8681dd3ab1d32990b3 | <ide><path>src/file-system-blob-store.js
<ide> class FileSystemBlobStore {
<ide> constructor (directory) {
<ide> this.inMemoryBlobs = new Map()
<ide> this.blobFilename = path.join(directory, 'BLOB')
<del> this.mapFilename = path.join(directory, 'MAP')
<add> this.blobMapFilename = path.join(directory, 'MAP')
<ide> this.storedBlob = new Buffer(0)
<del> this.storedMap = {}
<add> this.storedBlobMap = {}
<ide> }
<ide>
<ide> load () {
<del> if (!fs.existsSync(this.mapFilename)) {
<add> if (!fs.existsSync(this.blobMapFilename)) {
<ide> return
<ide> }
<ide> if (!fs.existsSync(this.blobFilename)) {
<ide> return
<ide> }
<ide> this.storedBlob = fs.readFileSync(this.blobFilename)
<del> this.storedMap = JSON.parse(fs.readFileSync(this.mapFilename))
<add> this.storedBlobMap = JSON.parse(fs.readFileSync(this.blobMapFilename))
<ide> }
<ide>
<ide> save () {
<ide> let dump = this.getDump()
<del> let cacheBlob = Buffer.concat(dump[0])
<del> let cacheMap = JSON.stringify(dump[1])
<del> fs.writeFileSync(this.blobFilename, cacheBlob)
<del> fs.writeFileSync(this.mapFilename, cacheMap)
<add> let blobToStore = Buffer.concat(dump[0])
<add> let mapToStore = JSON.stringify(dump[1])
<add> fs.writeFileSync(this.blobFilename, blobToStore)
<add> fs.writeFileSync(this.blobMapFilename, mapToStore)
<ide> }
<ide>
<ide> has (key) {
<del> return this.inMemoryBlobs.hasOwnProperty(key) || this.storedMap.hasOwnProperty(key)
<add> return this.inMemoryBlobs.hasOwnProperty(key) || this.storedBlobMap.hasOwnProperty(key)
<ide> }
<ide>
<ide> get (key) {
<ide> class FileSystemBlobStore {
<ide>
<ide> delete (key) {
<ide> this.inMemoryBlobs.delete(key)
<del> delete this.storedMap[key]
<add> delete this.storedBlobMap[key]
<ide> }
<ide>
<ide> getFromMemory (key) {
<ide> return this.inMemoryBlobs.get(key)
<ide> }
<ide>
<ide> getFromStorage (key) {
<del> if (this.storedMap[key] == null) {
<add> if (!this.storedBlobMap[key]) {
<ide> return
<ide> }
<ide>
<del> return this.storedBlob.slice.apply(this.storedBlob, this.storedMap[key])
<add> return this.storedBlob.slice.apply(this.storedBlob, this.storedBlobMap[key])
<ide> }
<ide>
<ide> getDump () {
<ide> let buffers = []
<del> let cacheMap = {}
<add> let blobMap = {}
<ide> let currentBufferStart = 0
<ide>
<ide> function dump (key, getBufferByKey) {
<ide> let buffer = getBufferByKey(key)
<ide> buffers.push(buffer)
<del> cacheMap[key] = [currentBufferStart, currentBufferStart + buffer.length]
<add> blobMap[key] = [currentBufferStart, currentBufferStart + buffer.length]
<ide> currentBufferStart += buffer.length
<ide> }
<ide>
<ide> for (let key of this.inMemoryBlobs.keys()) {
<ide> dump(key, this.getFromMemory.bind(this))
<ide> }
<ide>
<del> for (let key of Object.keys(this.storedMap)) {
<del> if (!cacheMap[key]) {
<add> for (let key of Object.keys(this.storedBlobMap)) {
<add> if (!blobMap[key]) {
<ide> dump(key, this.getFromStorage.bind(this))
<ide> }
<ide> }
<ide>
<del> return [buffers, cacheMap]
<add> return [buffers, blobMap]
<ide> }
<ide> }
<ide><path>static/index.js
<ide>
<ide> var loadSettings = null
<ide> var loadSettingsError = null
<del> var cacheStorage = null
<add> var blobStore = null
<ide>
<ide> app.on('before-quit', function () {
<del> if (cacheStorage) {
<del> cacheStorage.save()
<add> if (blobStore) {
<add> blobStore.save()
<ide> }
<ide> })
<ide> | 2 |
Text | Text | fix reactiflux url | d715e134478a0ddec1581dd8298f270813b507fd | <ide><path>.github/SUPPORT.md
<ide> If you'd like to discuss topics related to the future of React Native, please ch
<ide>
<ide> If you want to participate in casual discussions about the use of React Native, consider participating in one of the following forums:
<ide>
<del>- [Reactiflux Discord Server](https://www.reactiflux)
<add>- [Reactiflux Discord Server](https://www.reactiflux.com)
<ide> - [Spectrum Chat](https://spectrum.chat/react-native)
<ide> - [React Native Community Facebook Group](https://www.facebook.com/groups/react.native.community)
<ide> | 1 |
Java | Java | add putifabsent on cache abstraction | 3e74d3b2fbea16c55805b9b73c182bdc02e70b83 | <ide><path>spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java
<ide> *
<ide> * @author Costin Leau
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<ide> public class EhCacheCache implements Cache {
<ide> public final Ehcache getNativeCache() {
<ide> @Override
<ide> public ValueWrapper get(Object key) {
<ide> Element element = this.cache.get(key);
<del> return (element != null ? new SimpleValueWrapper(element.getObjectValue()) : null);
<add> return toWrapper(element);
<ide> }
<ide>
<ide> @Override
<ide> public void put(Object key, Object value) {
<ide> this.cache.put(new Element(key, value));
<ide> }
<ide>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, Object value) {
<add> Element existingElement = this.cache.putIfAbsent(new Element(key, value));
<add> return toWrapper(existingElement);
<add> }
<add>
<ide> @Override
<ide> public void evict(Object key) {
<ide> this.cache.remove(key);
<ide> public void clear() {
<ide> this.cache.removeAll();
<ide> }
<ide>
<add> private ValueWrapper toWrapper(Element element) {
<add> return (element != null ? new SimpleValueWrapper(element.getObjectValue()) : null);
<add> }
<add>
<ide> }
<ide><path>spring-context-support/src/main/java/org/springframework/cache/guava/GuavaCache.java
<ide> package org.springframework.cache.guava;
<ide>
<ide> import java.io.Serializable;
<add>import java.util.concurrent.Callable;
<add>import java.util.concurrent.ExecutionException;
<ide>
<ide> import org.springframework.cache.Cache;
<ide> import org.springframework.cache.support.SimpleValueWrapper;
<ide> * <p>Requires Google Guava 12.0 or higher.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 4.0
<ide> */
<ide> public class GuavaCache implements Cache {
<ide> public final boolean isAllowNullValues() {
<ide> @Override
<ide> public ValueWrapper get(Object key) {
<ide> Object value = this.cache.getIfPresent(key);
<del> return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
<add> return toWrapper(value);
<ide> }
<ide>
<ide> @Override
<ide> public void put(Object key, Object value) {
<ide> this.cache.put(key, toStoreValue(value));
<ide> }
<ide>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, final Object value) {
<add> try {
<add> PutIfAbsentCallable callable = new PutIfAbsentCallable(value);
<add> Object result = this.cache.get(key, callable);
<add> return (callable.called ? null : toWrapper(result));
<add> } catch (ExecutionException e) {
<add> throw new IllegalArgumentException(e);
<add> }
<add> }
<add>
<ide> @Override
<ide> public void evict(Object key) {
<ide> this.cache.invalidate(key);
<ide> protected Object toStoreValue(Object userValue) {
<ide> return userValue;
<ide> }
<ide>
<add> private ValueWrapper toWrapper(Object value) {
<add> return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
<add> }
<add>
<ide>
<ide> @SuppressWarnings("serial")
<ide> private static class NullHolder implements Serializable {
<ide> }
<ide>
<add> private class PutIfAbsentCallable implements Callable<Object> {
<add> private boolean called;
<add>
<add> private final Object value;
<add>
<add> private PutIfAbsentCallable(Object value) {
<add> this.value = value;
<add> }
<add>
<add> @Override
<add> public Object call() throws Exception {
<add> called = true;
<add> return toStoreValue(value);
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-context-support/src/main/java/org/springframework/cache/jcache/JCacheCache.java
<ide> * <p>Note: This class has been updated for JCache 1.0, as of Spring 4.0.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.2
<ide> */
<ide> public class JCacheCache implements Cache {
<ide> public void put(Object key, Object value) {
<ide> this.cache.put(key, toStoreValue(value));
<ide> }
<ide>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, Object value) {
<add> boolean set = this.cache.putIfAbsent(key, toStoreValue(value));
<add> return (set ? null : get(key));
<add> }
<add>
<ide> @Override
<ide> public void evict(Object key) {
<ide> this.cache.remove(key);
<ide><path>spring-context-support/src/main/java/org/springframework/cache/transaction/TransactionAwareCacheDecorator.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * successful transaction. If no transaction is active, {@link #put} and {@link #evict}
<ide> * operations will be performed immediately, as usual.
<ide> *
<add> * <p>Use of more aggressive operations such as {@link #putIfAbsent} cannot be deferred
<add> * to the after-commit phase of a running transaction. Use these with care.
<add> *
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 3.2
<ide> * @see TransactionAwareCacheManagerProxy
<ide> */
<ide> public void afterCommit() {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public ValueWrapper putIfAbsent(final Object key, final Object value) {
<add> return this.targetCache.putIfAbsent(key, value);
<add> }
<add>
<ide> @Override
<ide> public void evict(final Object key) {
<ide> if (TransactionSynchronizationManager.isSynchronizationActive()) {
<ide><path>spring-context-support/src/test/java/org/springframework/cache/AbstractCacheTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<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>
<add>package org.springframework.cache;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import org.junit.Test;
<add>
<add>/**
<add> * @author Stephane Nicoll
<add> */
<add>public abstract class AbstractCacheTests<T extends Cache> {
<add>
<add> protected final static String CACHE_NAME = "testCache";
<add>
<add> protected abstract T getCache();
<add>
<add> protected abstract Object getNativeCache();
<add>
<add> @Test
<add> public void testCacheName() throws Exception {
<add> assertEquals(CACHE_NAME, getCache().getName());
<add> }
<add>
<add> @Test
<add> public void testNativeCache() throws Exception {
<add> assertSame(getNativeCache(), getCache().getNativeCache());
<add> }
<add>
<add> @Test
<add> public void testCachePut() throws Exception {
<add> T cache = getCache();
<add>
<add> Object key = "enescu";
<add> Object value = "george";
<add>
<add> assertNull(cache.get(key));
<add> assertNull(cache.get(key, String.class));
<add> assertNull(cache.get(key, Object.class));
<add>
<add> cache.put(key, value);
<add> assertEquals(value, cache.get(key).get());
<add> assertEquals(value, cache.get(key, String.class));
<add> assertEquals(value, cache.get(key, Object.class));
<add> assertEquals(value, cache.get(key, null));
<add>
<add> cache.put(key, null);
<add> assertNotNull(cache.get(key));
<add> assertNull(cache.get(key).get());
<add> assertNull(cache.get(key, String.class));
<add> assertNull(cache.get(key, Object.class));
<add> }
<add>
<add> @Test
<add> public void testCachePutIfAbsent() throws Exception {
<add> T cache = getCache();
<add>
<add> Object key = new Object();
<add> Object value = "initialValue";
<add>
<add> assertNull(cache.get(key));
<add> assertNull(cache.putIfAbsent(key, value));
<add> assertEquals(value, cache.get(key).get());
<add> assertEquals("initialValue", cache.putIfAbsent(key, "anotherValue").get());
<add> assertEquals(value, cache.get(key).get()); // not changed
<add> }
<add>
<add> @Test
<add> public void testCacheRemove() throws Exception {
<add> T cache = getCache();
<add>
<add> Object key = "enescu";
<add> Object value = "george";
<add>
<add> assertNull(cache.get(key));
<add> cache.put(key, value);
<add> }
<add>
<add> @Test
<add> public void testCacheClear() throws Exception {
<add> T cache = getCache();
<add>
<add> assertNull(cache.get("enescu"));
<add> cache.put("enescu", "george");
<add> assertNull(cache.get("vlaicu"));
<add> cache.put("vlaicu", "aurel");
<add> cache.clear();
<add> assertNull(cache.get("vlaicu"));
<add> assertNull(cache.get("enescu"));
<add> }
<add>}
<ide><path>spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTests.java
<ide>
<ide> package org.springframework.cache.ehcache;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> import net.sf.ehcache.CacheManager;
<ide> import net.sf.ehcache.Ehcache;
<ide> import net.sf.ehcache.Element;
<ide> import net.sf.ehcache.config.CacheConfiguration;
<add>import net.sf.ehcache.config.Configuration;
<add>import org.junit.After;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<del>
<del>import org.springframework.cache.Cache;
<add>import org.springframework.cache.AbstractCacheTests;
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<ide>
<del>import static org.junit.Assert.*;
<del>
<ide> /**
<ide> * @author Costin Leau
<add> * @author Stephane Nicoll
<ide> * @author Juergen Hoeller
<ide> */
<del>public class EhCacheCacheTests {
<del>
<del> protected final static String CACHE_NAME = "testCache";
<del>
<del> protected Ehcache nativeCache;
<del>
<del> protected Cache cache;
<add>public class EhCacheCacheTests extends AbstractCacheTests<EhCacheCache> {
<ide>
<add> private CacheManager cacheManager;
<add> private Ehcache nativeCache;
<add> private EhCacheCache cache;
<ide>
<ide> @Before
<del> public void setUp() throws Exception {
<del> if (CacheManager.getInstance().cacheExists(CACHE_NAME)) {
<del> nativeCache = CacheManager.getInstance().getEhcache(CACHE_NAME);
<del> }
<del> else {
<del> nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
<del> CacheManager.getInstance().addCache(nativeCache);
<del> }
<add> public void setUp() {
<add> cacheManager = new CacheManager(new Configuration().name("EhCacheCacheTests")
<add> .defaultCache(new CacheConfiguration("default", 100)));
<add> nativeCache = new net.sf.ehcache.Cache(new CacheConfiguration(CACHE_NAME, 100));
<add> cacheManager.addCache(nativeCache);
<add>
<ide> cache = new EhCacheCache(nativeCache);
<del> cache.clear();
<ide> }
<ide>
<del>
<del> @Test
<del> public void testCacheName() throws Exception {
<del> assertEquals(CACHE_NAME, cache.getName());
<add> @After
<add> public void tearDown() {
<add> cacheManager.shutdown();
<ide> }
<ide>
<del> @Test
<del> public void testNativeCache() throws Exception {
<del> assertSame(nativeCache, cache.getNativeCache());
<add> @Override
<add> protected EhCacheCache getCache() {
<add> return cache;
<ide> }
<ide>
<add> @Override
<add> protected Ehcache getNativeCache() {
<add> return nativeCache;
<add> }
<ide> @Test
<ide> public void testCachePut() throws Exception {
<ide> Object key = "enescu";
<ide> public void testCachePut() throws Exception {
<ide> assertNull(cache.get(key, Object.class));
<ide> }
<ide>
<del> @Test
<del> public void testCacheRemove() throws Exception {
<del> Object key = "enescu";
<del> Object value = "george";
<del>
<del> assertNull(cache.get(key));
<del> cache.put(key, value);
<del> }
<del>
<del> @Test
<del> public void testCacheClear() throws Exception {
<del> assertNull(cache.get("enescu"));
<del> cache.put("enescu", "george");
<del> assertNull(cache.get("vlaicu"));
<del> cache.put("vlaicu", "aurel");
<del> cache.clear();
<del> assertNull(cache.get("vlaicu"));
<del> assertNull(cache.get("enescu"));
<del> }
<del>
<ide> @Test
<ide> public void testExpiredElements() throws Exception {
<ide> Assume.group(TestGroup.LONG_RUNNING);
<ide> public void testExpiredElements() throws Exception {
<ide> Thread.sleep(5 * 1000);
<ide> assertNull(cache.get(key));
<ide> }
<del>
<ide> }
<ide><path>spring-context-support/src/test/java/org/springframework/cache/guava/GuavaCacheTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<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>
<add>package org.springframework.cache.guava;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import com.google.common.cache.CacheBuilder;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import org.springframework.cache.AbstractCacheTests;
<add>import org.springframework.cache.Cache;
<add>
<add>/**
<add> * @author Stephane Nicoll
<add> */
<add>public class GuavaCacheTests extends AbstractCacheTests<GuavaCache> {
<add>
<add> private com.google.common.cache.Cache<Object, Object> nativeCache;
<add> private GuavaCache cache;
<add>
<add> @Before
<add> public void setUp() {
<add> nativeCache = CacheBuilder.newBuilder().build();
<add> cache = new GuavaCache(CACHE_NAME, nativeCache);
<add> }
<add>
<add> @Override
<add> protected GuavaCache getCache() {
<add> return cache;
<add> }
<add>
<add> @Override
<add> protected Object getNativeCache() {
<add> return nativeCache;
<add> }
<add>
<add> @Test
<add> public void putIfAbsentNullValue() throws Exception {
<add> GuavaCache cache = getCache();
<add>
<add> Object key = new Object();
<add> Object value = null;
<add>
<add> assertNull(cache.get(key));
<add> assertNull(cache.putIfAbsent(key, value));
<add> assertEquals(value, cache.get(key).get());
<add> Cache.ValueWrapper wrapper = cache.putIfAbsent(key, "anotherValue");
<add> assertNotNull(wrapper); // A value is set but is 'null'
<add> assertEquals(null, wrapper.get());
<add> assertEquals(value, cache.get(key).get()); // not changed
<add> }
<add>}
<ide><path>spring-context-support/src/test/java/org/springframework/cache/transaction/TransactionAwareCacheDecoratorTests.java
<ide> public void putTransactional() {
<ide> assertEquals("123", target.get(key, String.class));
<ide> }
<ide>
<add> @Test
<add> public void putIfAbsent() { // no transactional support for putIfAbsent
<add> Cache target = new ConcurrentMapCache("testCache");
<add> Cache cache = new TransactionAwareCacheDecorator(target);
<add>
<add> Object key = new Object();
<add> assertNull(cache.putIfAbsent(key, "123"));
<add> assertEquals("123", target.get(key, String.class));
<add> assertEquals("123", cache.putIfAbsent(key, "456").get());
<add> assertEquals("123", target.get(key, String.class)); // unchanged
<add> }
<add>
<ide> @Test
<ide> public void evictNonTransactional() {
<ide> Cache target = new ConcurrentMapCache("testCache");
<ide><path>spring-context/src/main/java/org/springframework/cache/Cache.java
<ide> public interface Cache {
<ide> */
<ide> void put(Object key, Object value);
<ide>
<add> /**
<add> * Atomically associate the specified value with the specified key in this cache if
<add> * it is not set already.
<add> * <p>This is equivalent to:
<add> * <pre><code>
<add> * Object existingValue = cache.get(key);
<add> * if (existingValue == null) {
<add> * cache.put(key, value);
<add> * return null;
<add> * } else {
<add> * return existingValue;
<add> * }
<add> * </code></pre>
<add> * except that the action is performed atomically. While all known providers are
<add> * able to perform the put atomically, the returned value may be retrieved after
<add> * the attempt to put (i.e. in a non atomic way). Check the documentation of
<add> * the native cache implementation that you are using for more details.
<add> * @param key the key with which the specified value is to be associated
<add> * @param value the value to be associated with the specified key
<add> * @return the value to which this cache maps the specified key (which may
<add> * be {@code null} itself), or also {@code null} if the cache did not contain
<add> * any mapping for that key prior to this call. Returning {@code null} is
<add> * therefore an indicator that the given {@code value} has been associated
<add> * with the key
<add> */
<add> ValueWrapper putIfAbsent(Object key, Object value);
<add>
<ide> /**
<ide> * Evict the mapping for this key from this cache if it is present.
<ide> * @param key the key whose mapping is to be removed from the cache
<ide><path>spring-context/src/main/java/org/springframework/cache/concurrent/ConcurrentMapCache.java
<ide> public final boolean isAllowNullValues() {
<ide> @Override
<ide> public ValueWrapper get(Object key) {
<ide> Object value = this.store.get(key);
<del> return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
<add> return toWrapper(value);
<ide> }
<ide>
<ide> @Override
<ide> public void put(Object key, Object value) {
<ide> this.store.put(key, toStoreValue(value));
<ide> }
<ide>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, Object value) {
<add> Object existing = this.store.putIfAbsent(key, value);
<add> return toWrapper(existing);
<add> }
<add>
<ide> @Override
<ide> public void evict(Object key) {
<ide> this.store.remove(key);
<ide> protected Object toStoreValue(Object userValue) {
<ide> return userValue;
<ide> }
<ide>
<add> private ValueWrapper toWrapper(Object value) {
<add> return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
<add> }
<ide>
<ide> @SuppressWarnings("serial")
<ide> private static class NullHolder implements Serializable {
<ide><path>spring-context/src/main/java/org/springframework/cache/support/NoOpCacheManager.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * <p>Will simply accept any items into the cache not actually storing them.
<ide> *
<ide> * @author Costin Leau
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> * @see CompositeCacheManager
<ide> */
<ide> public Object getNativeCache() {
<ide> @Override
<ide> public void put(Object key, Object value) {
<ide> }
<add>
<add> @Override
<add> public ValueWrapper putIfAbsent(Object key, Object value) {
<add> return null;
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/cache/concurrent/ConcurrentCacheTests.java
<ide> /*
<del> * Copyright 2010-2014 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> /**
<ide> * @author Costin Leau
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> */
<ide> public class ConcurrentCacheTests {
<ide>
<ide> public void testCachePut() throws Exception {
<ide> assertNull(cache.get(key, Object.class));
<ide> }
<ide>
<add> @Test
<add> public void testCachePutIfAbsent() throws Exception {
<add> Object key = new Object();
<add> Object value = "initialValue";
<add>
<add> assertNull(cache.get(key));
<add> assertNull(cache.putIfAbsent(key, value));
<add> assertEquals(value, cache.get(key).get());
<add> assertEquals("initialValue", cache.putIfAbsent(key, "anotherValue").get());
<add> assertEquals(value, cache.get(key).get()); // not changed
<add> }
<add>
<ide> @Test
<ide> public void testCacheRemove() throws Exception {
<ide> Object key = "enescu"; | 12 |
Javascript | Javascript | preserve object prototypes when cloning | 51be3447170fc648c3b5bc3002c963be62bccdf9 | <ide><path>src/helpers/helpers.core.js
<ide> export function clone(source) {
<ide> }
<ide>
<ide> if (isObject(source)) {
<del> const target = {};
<add> const target = Object.create(source);
<ide> const keys = Object.keys(source);
<ide> const klen = keys.length;
<ide> let k = 0;
<ide><path>test/specs/helpers.core.tests.js
<ide> describe('Chart.helpers.core', function() {
<ide> expect(output.o).not.toBe(o0);
<ide> expect(output.o.a).not.toBe(a1);
<ide> });
<add> it('should preserve prototype of objects', function() {
<add> // https://github.com/chartjs/Chart.js/issues/7340
<add> class MyConfigObject {
<add> constructor(s) {
<add> this._s = s;
<add> }
<add> func() {
<add> return 10;
<add> }
<add> }
<add> var original = new MyConfigObject('something');
<add> var output = helpers.merge({}, {
<add> plugins: [{
<add> test: original
<add> }]
<add> });
<add> var clone = output.plugins[0].test;
<add> expect(clone).toBeInstanceOf(MyConfigObject);
<add> expect(clone).toEqual(original);
<add> expect(clone === original).toBeFalse();
<add> });
<ide> });
<ide>
<ide> describe('mergeIf', function() { | 2 |
Javascript | Javascript | fix missing param in url benchmark | e7913e450ce5b94f95379c0e7f0ed9dd9da7c6c9 | <ide><path>test/parallel/test-benchmark-url.js
<ide> runBenchmark('url',
<ide> 'to=ascii',
<ide> 'prop=href',
<ide> 'n=1',
<add> 'param=one'
<ide> ],
<ide> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); | 1 |
PHP | PHP | add deprecations for controller | 0eee967d26437bb5679766418a9a166088ff91ad | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function initialize(array $config)
<ide> $this->setEventManager($controller->getEventManager());
<ide> $this->response =& $controller->response;
<ide> $this->session = $controller->request->getSession();
<add>
<add> if ($this->getConfig('ajaxLogin')) {
<add> deprecationWarning(
<add> 'The `ajaxLogin` option is deprecated. Your client-side ' .
<add> 'code should instead check for 403 status code and show ' .
<add> 'appropriate login form.'
<add> );
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>src/Controller/Component/PaginatorComponent.php
<ide> protected function _setPagingParams()
<ide> */
<ide> public function config($key = null, $value = null, $merge = true)
<ide> {
<add> deprecationWarning('PaginatorComponent::config() is deprecated. Use getConfig()/setConfig() instead.');
<ide> $return = $this->_paginator->config($key, $value, $merge);
<ide> if ($return instanceof Paginator) {
<ide> $return = $this;
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function beforeRedirect(Event $event, $url, Response $response)
<ide> if (!$this->getConfig('enableBeforeRedirect')) {
<ide> return null;
<ide> }
<add> deprecationWarning(
<add> 'RequestHandlerComponent::beforeRedirect() is deprecated. ' .
<add> 'This functionality will be removed in 4.0.0. Set the `enableBeforeRedirect` ' .
<add> 'option to `false` to disable this warning.'
<add> );
<ide> $request = $this->request;
<ide> if (!$request->is('ajax')) {
<ide> return null;
<ide> public function mapAlias($alias)
<ide> */
<ide> public function addInputType($type, $handler)
<ide> {
<del> trigger_error(
<del> 'RequestHandlerComponent::addInputType() is deprecated. Use setConfig("inputTypeMap", ...) instead.',
<del> E_USER_DEPRECATED
<add> deprecationWarning(
<add> 'RequestHandlerComponent::addInputType() is deprecated. Use setConfig("inputTypeMap", ...) instead.'
<ide> );
<ide> if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) {
<ide> throw new Exception('You must give a handler callback.');
<ide> public function addInputType($type, $handler)
<ide> */
<ide> public function viewClassMap($type = null, $viewClass = null)
<ide> {
<del> trigger_error(
<del> 'RequestHandlerComponent::viewClassMap() is deprecated. Use setConfig("viewClassMap", ...) instead.',
<del> E_USER_DEPRECATED
<add> deprecationWarning(
<add> 'RequestHandlerComponent::viewClassMap() is deprecated. Use setConfig("viewClassMap", ...) instead.'
<ide> );
<ide> if (!$viewClass && is_string($type)) {
<ide> return $this->getConfig('viewClassMap.' . $type);
<ide><path>src/Controller/Component/SecurityComponent.php
<ide> public function requireSecure($actions = null)
<ide> */
<ide> public function requireAuth($actions)
<ide> {
<add> deprecationWarning('SecurityComponent::requireAuth() will be removed in 4.0.0.');
<ide> $this->_requireMethod('Auth', (array)$actions);
<ide> }
<ide>
<ide> protected function _authRequired(Controller $controller)
<ide> !empty($this->_config['requireAuth']) &&
<ide> $request->getData()
<ide> ) {
<add> deprecationWarning('SecurityComponent::requireAuth() will be removed in 4.0.0.');
<ide> $requireAuth = $this->_config['requireAuth'];
<ide>
<ide> if (in_array($request->getParam('action'), $requireAuth) || $requireAuth == ['*']) {
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testMergeOptionsExtraWhitelist()
<ide> 'limit' => 20,
<ide> 'maxLimit' => 100,
<ide> ];
<del> $this->Paginator->config('whitelist', ['fields']);
<add> $this->Paginator->setConfig('whitelist', ['fields']);
<ide> $result = $this->Paginator->mergeOptions('Post', $settings);
<ide> $expected = [
<ide> 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields']
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testBeforeRedirectDisabled()
<ide> /**
<ide> * testNonAjaxRedirect method
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testNonAjaxRedirect()
<ide> {
<del> $event = new Event('Controller.startup', $this->Controller);
<del> $this->RequestHandler->initialize([]);
<del> $this->RequestHandler->startup($event);
<del> $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
<add> $this->deprecated(function () {
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->RequestHandler->initialize([]);
<add> $this->RequestHandler->startup($event);
<add> $this->assertNull($this->RequestHandler->beforeRedirect($event, '/', $this->Controller->response));
<add> });
<ide> }
<ide>
<ide> /**
<ide> * test that redirects with ajax and no URL don't do anything.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAjaxRedirectWithNoUrl()
<ide> {
<del> $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
<del> $event = new Event('Controller.startup', $this->Controller);
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<add> $this->deprecated(function () {
<add> $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide>
<del> $this->Controller->response->expects($this->never())
<del> ->method('body');
<add> $this->Controller->response->expects($this->never())
<add> ->method('body');
<ide>
<del> $this->RequestHandler->initialize([]);
<del> $this->RequestHandler->startup($event);
<del> $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
<add> $this->RequestHandler->initialize([]);
<add> $this->RequestHandler->startup($event);
<add> $this->assertNull($this->RequestHandler->beforeRedirect($event, null, $this->Controller->response));
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testPrefers()
<ide> /**
<ide> * test that AJAX requests involving redirects trigger requestAction instead.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRedirect $this->Controller
<ide> */
<ide> public function testAjaxRedirectAsRequestAction()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action');
<del> $event = new Event('Controller.beforeRedirect', $this->Controller);
<del>
<del> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['is'])
<del> ->getMock();
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<del> ->setMethods(['_sendHeader', 'stop'])
<del> ->getMock();
<del> $this->Controller->request->expects($this->any())
<del> ->method('is')
<del> ->will($this->returnValue(true));
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
<del> $this->Controller->response
<del> );
<del> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action');
<add> $event = new Event('Controller.beforeRedirect', $this->Controller);
<add>
<add> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<add> ->setMethods(['is'])
<add> ->getMock();
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<add> ->setMethods(['_sendHeader', 'stop'])
<add> ->getMock();
<add> $this->Controller->request->expects($this->any())
<add> ->method('is')
<add> ->will($this->returnValue(true));
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
<add> $this->Controller->response
<add> );
<add> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Test that AJAX requests involving redirects handle querystrings
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRedirect $this->Controller
<ide> */
<ide> public function testAjaxRedirectAsRequestActionWithQueryString()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action');
<del>
<del> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['is'])
<del> ->getMock();
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<del> ->setMethods(['_sendHeader', 'stop'])
<del> ->getMock();
<del> $this->Controller->request->expects($this->any())
<del> ->method('is')
<del> ->with('ajax')
<del> ->will($this->returnValue(true));
<del> $event = new Event('Controller.beforeRedirect', $this->Controller);
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> '/request_action/params_pass?a=b&x=y?ish',
<del> $this->Controller->response
<del> );
<del> $data = json_decode($response, true);
<del> $this->assertEquals('/request_action/params_pass', $data['here']);
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> '/request_action/query_pass?a=b&x=y?ish',
<del> $this->Controller->response
<del> );
<del> $data = json_decode($response, true);
<del> $this->assertEquals('y?ish', $data['x']);
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action');
<add>
<add> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<add> ->setMethods(['is'])
<add> ->getMock();
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<add> ->setMethods(['_sendHeader', 'stop'])
<add> ->getMock();
<add> $this->Controller->request->expects($this->any())
<add> ->method('is')
<add> ->with('ajax')
<add> ->will($this->returnValue(true));
<add> $event = new Event('Controller.beforeRedirect', $this->Controller);
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> '/request_action/params_pass?a=b&x=y?ish',
<add> $this->Controller->response
<add> );
<add> $data = json_decode($response, true);
<add> $this->assertEquals('/request_action/params_pass', $data['here']);
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> '/request_action/query_pass?a=b&x=y?ish',
<add> $this->Controller->response
<add> );
<add> $data = json_decode($response, true);
<add> $this->assertEquals('y?ish', $data['x']);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Test that AJAX requests involving redirects handle cookie data
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRedirect $this->Controller
<ide> */
<ide> public function testAjaxRedirectAsRequestActionWithCookieData()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action');
<del> $event = new Event('Controller.beforeRedirect', $this->Controller);
<del>
<del> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['is'])
<del> ->getMock();
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<del> ->setMethods(['_sendHeader', 'stop'])
<del> ->getMock();
<del> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<del>
<del> $cookies = [
<del> 'foo' => 'bar'
<del> ];
<del> $this->Controller->request->cookies = $cookies;
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> '/request_action/cookie_pass',
<del> $this->Controller->response
<del> );
<del> $data = json_decode($response, true);
<del> $this->assertEquals($cookies, $data);
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action');
<add> $event = new Event('Controller.beforeRedirect', $this->Controller);
<add>
<add> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<add> ->setMethods(['is'])
<add> ->getMock();
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<add> ->setMethods(['_sendHeader', 'stop'])
<add> ->getMock();
<add> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<add>
<add> $cookies = [
<add> 'foo' => 'bar'
<add> ];
<add> $this->Controller->request->cookies = $cookies;
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> '/request_action/cookie_pass',
<add> $this->Controller->response
<add> );
<add> $data = json_decode($response, true);
<add> $this->assertEquals($cookies, $data);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Tests that AJAX requests involving redirects don't let the status code bleed through.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRedirect $this->Controller
<ide> */
<ide> public function testAjaxRedirectAsRequestActionStatusCode()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action');
<del> $event = new Event('Controller.beforeRedirect', $this->Controller);
<del>
<del> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['is'])
<del> ->getMock();
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<del> ->setMethods(['_sendHeader', 'stop'])
<del> ->getMock();
<del> $this->Controller->response->statusCode(302);
<del> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
<del> $this->Controller->response
<del> );
<del> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<del> $this->assertSame(200, $response->statusCode());
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action');
<add> $event = new Event('Controller.beforeRedirect', $this->Controller);
<add>
<add> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<add> ->setMethods(['is'])
<add> ->getMock();
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<add> ->setMethods(['_sendHeader', 'stop'])
<add> ->getMock();
<add> $this->Controller->response->statusCode(302);
<add> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> ['controller' => 'RequestHandlerTest', 'action' => 'destination'],
<add> $this->Controller->response
<add> );
<add> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<add> $this->assertSame(200, $response->statusCode());
<add> });
<ide> }
<ide>
<ide> /**
<ide> * test that ajax requests involving redirects don't force no layout
<ide> * this would cause the ajax layout to not be rendered.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRedirect $this->Controller
<ide> */
<ide> public function testAjaxRedirectAsRequestActionStillRenderingLayout()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action');
<del> $event = new Event('Controller.beforeRedirect', $this->Controller);
<del>
<del> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<del> ->setMethods(['is'])
<del> ->getMock();
<del> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<del> ->setMethods(['_sendHeader', 'stop'])
<del> ->getMock();
<del> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<del>
<del> $response = $this->RequestHandler->beforeRedirect(
<del> $event,
<del> ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
<del> $this->Controller->response
<del> );
<del> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<del> $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action');
<add> $event = new Event('Controller.beforeRedirect', $this->Controller);
<add>
<add> $this->RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')
<add> ->setMethods(['is'])
<add> ->getMock();
<add> $this->Controller->response = $this->getMockBuilder('Cake\Http\Response')
<add> ->setMethods(['_sendHeader', 'stop'])
<add> ->getMock();
<add> $this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
<add>
<add> $response = $this->RequestHandler->beforeRedirect(
<add> $event,
<add> ['controller' => 'RequestHandlerTest', 'action' => 'ajax2_layout'],
<add> $this->Controller->response
<add> );
<add> $this->assertRegExp('/posts index/', $response->body(), 'RequestAction redirect failed.');
<add> $this->assertRegExp('/Ajax!/', $response->body(), 'Layout was not rendered.');
<add> });
<ide> }
<ide>
<ide> /**
<ide> * test that the beforeRedirect callback properly converts
<ide> * array URLs into their correct string ones, and adds base => false so
<ide> * the correct URLs are generated.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.beforeRender $this->Controller
<ide> */
<ide> public function testBeforeRedirectCallbackWithArrayUrl()
<ide> {
<del> static::setAppNamespace();
<del> Router::connect('/:controller/:action/*');
<del> $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
<del> $event = new Event('Controller.beforeRender', $this->Controller);
<del>
<del> Router::setRequestInfo([
<del> ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
<del> ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
<del> ]);
<del>
<del> $RequestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $this->Controller->request = new ServerRequest('posts/index');
<del>
<del> ob_start();
<del> $RequestHandler->beforeRedirect(
<del> $event,
<del> ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
<del> $this->Controller->response
<del> );
<del> $result = ob_get_clean();
<del> $this->assertEquals('one: first two: second', $result);
<add> $this->deprecated(function () {
<add> static::setAppNamespace();
<add> Router::connect('/:controller/:action/*');
<add> $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
<add> $event = new Event('Controller.beforeRender', $this->Controller);
<add>
<add> Router::setRequestInfo([
<add> ['plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => []],
<add> ['base' => '', 'here' => '/accounts/', 'webroot' => '/']
<add> ]);
<add>
<add> $RequestHandler = new RequestHandlerComponent($this->Controller->components());
<add> $this->Controller->request = new ServerRequest('posts/index');
<add>
<add> ob_start();
<add> $RequestHandler->beforeRedirect(
<add> $event,
<add> ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'],
<add> $this->Controller->response
<add> );
<add> $result = ob_get_clean();
<add> $this->assertEquals('one: first two: second', $result);
<add> });
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function testRequireSecureEmptySucceed()
<ide> /**
<ide> * testRequireAuthFail method
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testRequireAuthFail()
<ide> {
<del> $event = new Event('Controller.startup', $this->Controller);
<del> $_SERVER['REQUEST_METHOD'] = 'AUTH';
<del> $this->Controller->request['action'] = 'posted';
<del> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<del> $this->Security->requireAuth(['posted']);
<del> $this->Security->startup($event);
<del> $this->assertTrue($this->Controller->failed);
<del>
<del> $this->Security->session->write('_Token', ['allowedControllers' => []]);
<del> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<del> $this->Controller->request['action'] = 'posted';
<del> $this->Security->requireAuth('posted');
<del> $this->Security->startup($event);
<del> $this->assertTrue($this->Controller->failed);
<del>
<del> $this->Security->session->write('_Token', [
<del> 'allowedControllers' => ['SecurityTest'], 'allowedActions' => ['posted2']
<del> ]);
<del> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<del> $this->Controller->request['action'] = 'posted';
<del> $this->Security->requireAuth('posted');
<del> $this->Security->startup($event);
<del> $this->assertTrue($this->Controller->failed);
<add> $this->deprecated(function () {
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $_SERVER['REQUEST_METHOD'] = 'AUTH';
<add> $this->Controller->request['action'] = 'posted';
<add> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<add> $this->Security->requireAuth(['posted']);
<add> $this->Security->startup($event);
<add> $this->assertTrue($this->Controller->failed);
<add>
<add> $this->Security->session->write('_Token', ['allowedControllers' => []]);
<add> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<add> $this->Controller->request['action'] = 'posted';
<add> $this->Security->requireAuth('posted');
<add> $this->Security->startup($event);
<add> $this->assertTrue($this->Controller->failed);
<add>
<add> $this->Security->session->write('_Token', [
<add> 'allowedControllers' => ['SecurityTest'], 'allowedActions' => ['posted2']
<add> ]);
<add> $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
<add> $this->Controller->request['action'] = 'posted';
<add> $this->Security->requireAuth('posted');
<add> $this->Security->startup($event);
<add> $this->assertTrue($this->Controller->failed);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * testRequireAuthSucceed method
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testRequireAuthSucceed()
<ide> {
<del> $_SERVER['REQUEST_METHOD'] = 'AUTH';
<del> $this->Controller->Security->config('validatePost', false);
<del>
<del> $event = new Event('Controller.startup', $this->Controller);
<del> $this->Controller->request->addParams([
<del> 'action' => 'posted'
<del> ]);
<del> $this->Security->requireAuth('posted');
<del> $this->Security->startup($event);
<del> $this->assertFalse($this->Controller->failed);
<del>
<del> $this->Controller->Security->session->write('_Token', [
<del> 'allowedControllers' => ['SecurityTest'],
<del> 'allowedActions' => ['posted'],
<del> ]);
<del> $this->Controller->request->addParams([
<del> 'controller' => 'SecurityTest',
<del> 'action' => 'posted'
<del> ]);
<del>
<del> $this->Controller->request->data = [
<del> 'username' => 'willy',
<del> 'password' => 'somePass',
<del> '_Token' => ''
<del> ];
<del> $this->Controller->action = 'posted';
<del> $this->Controller->Security->requireAuth('posted');
<del> $this->Controller->Security->startup($event);
<del> $this->assertFalse($this->Controller->failed);
<add> $this->deprecated(function () {
<add> $_SERVER['REQUEST_METHOD'] = 'AUTH';
<add> $this->Controller->Security->config('validatePost', false);
<add>
<add> $event = new Event('Controller.startup', $this->Controller);
<add> $this->Controller->request->addParams([
<add> 'action' => 'posted'
<add> ]);
<add> $this->Security->requireAuth('posted');
<add> $this->Security->startup($event);
<add> $this->assertFalse($this->Controller->failed);
<add>
<add> $this->Controller->Security->session->write('_Token', [
<add> 'allowedControllers' => ['SecurityTest'],
<add> 'allowedActions' => ['posted'],
<add> ]);
<add> $this->Controller->request->addParams([
<add> 'controller' => 'SecurityTest',
<add> 'action' => 'posted'
<add> ]);
<add>
<add> $this->Controller->request->data = [
<add> 'username' => 'willy',
<add> 'password' => 'somePass',
<add> '_Token' => ''
<add> ];
<add> $this->Controller->action = 'posted';
<add> $this->Controller->Security->requireAuth('posted');
<add> $this->Controller->Security->startup($event);
<add> $this->assertFalse($this->Controller->failed);
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testValidatePostUnexpectedDebugToken()
<ide> *
<ide> * Auth required throws exception token not found.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<ide> * @expectedExceptionMessage '_Token' was not found in request data.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
<ide> {
<del> $this->Security->config('requireAuth', ['protected']);
<del> $this->Controller->request->params['action'] = 'protected';
<del> $this->Controller->request->data = 'notEmpty';
<del> $this->Security->authRequired($this->Controller);
<add> $this->deprecated(function () {
<add> $this->Security->config('requireAuth', ['protected']);
<add> $this->Controller->request->params['action'] = 'protected';
<add> $this->Controller->request->data = 'notEmpty';
<add> $this->Security->authRequired($this->Controller);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * testAuthRequiredThrowsExceptionTokenNotFoundSession method
<ide> *
<ide> * Auth required throws exception token not found in Session.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<ide> * @expectedExceptionMessage '_Token' was not found in session.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
<ide> {
<del> $this->Security->config('requireAuth', ['protected']);
<del> $this->Controller->request->params['action'] = 'protected';
<del> $this->Controller->request->data = ['_Token' => 'not empty'];
<del> $this->Security->authRequired($this->Controller);
<add> $this->deprecated(function () {
<add> $this->Security->config('requireAuth', ['protected']);
<add> $this->Controller->request->params['action'] = 'protected';
<add> $this->Controller->request->data = ['_Token' => 'not empty'];
<add> $this->Security->authRequired($this->Controller);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * testAuthRequiredThrowsExceptionControllerNotAllowed method
<ide> *
<ide> * Auth required throws exception controller not allowed.
<ide> *
<add> * @group deprecated
<ide> * @return void
<ide> * @expectedException \Cake\Controller\Exception\AuthSecurityException
<ide> * @expectedExceptionMessage Controller 'NotAllowed' was not found in allowed controllers: 'Allowed, AnotherAllowed'.
<ide> * @triggers Controller.startup $this->Controller
<ide> */
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> {
<del> $this->Security->config('requireAuth', ['protected']);
<del> $this->Controller->request->params['controller'] = 'NotAllowed';
<del> $this->Controller->request->params['action'] = 'protected';
<del> $this->Controller->request->data = ['_Token' => 'not empty'];
<del> $this->Controller->request->session()->write('_Token', [
<del> 'allowedControllers' => ['Allowed', 'AnotherAllowed']
<del> ]);
<del> $this->Security->authRequired($this->Controller);
<add> $this->deprecated(function () {
<add> $this->Security->config('requireAuth', ['protected']);
<add> $this->Controller->request->params['controller'] = 'NotAllowed';
<add> $this->Controller->request->params['action'] = 'protected';
<add> $this->Controller->request->data = ['_Token' => 'not empty'];
<add> $this->Controller->request->session()->write('_Token', [
<add> 'allowedControllers' => ['Allowed', 'AnotherAllowed']
<add> ]);
<add> $this->Security->authRequired($this->Controller);
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> */
<ide> public function testAuthRequiredThrowsExceptionActionNotAllowed()
<ide> {
<del> $this->Security->config('requireAuth', ['protected']);
<del> $this->Controller->request->params['controller'] = 'NotAllowed';
<del> $this->Controller->request->params['action'] = 'protected';
<del> $this->Controller->request->data = ['_Token' => 'not empty'];
<del> $this->Controller->request->session()->write('_Token', [
<del> 'allowedActions' => ['index', 'view']
<del> ]);
<del> $this->Security->authRequired($this->Controller);
<add> $this->deprecated(function () {
<add> $this->Security->config('requireAuth', ['protected']);
<add> $this->Controller->request->params['controller'] = 'NotAllowed';
<add> $this->Controller->request->params['action'] = 'protected';
<add> $this->Controller->request->data = ['_Token' => 'not empty'];
<add> $this->Controller->request->session()->write('_Token', [
<add> 'allowedActions' => ['index', 'view']
<add> ]);
<add> $this->Security->authRequired($this->Controller);
<add> });
<ide> }
<ide>
<ide> /**
<ide> public function testAuthRequiredThrowsExceptionActionNotAllowed()
<ide> */
<ide> public function testAuthRequired()
<ide> {
<del> $this->Security->config('requireAuth', ['protected']);
<del> $this->Controller->request->params['controller'] = 'Allowed';
<del> $this->Controller->request->params['action'] = 'protected';
<del> $this->Controller->request->data = ['_Token' => 'not empty'];
<del> $this->Controller->request->session()->write('_Token', [
<del> 'allowedActions' => ['protected'],
<del> 'allowedControllers' => ['Allowed'],
<del> ]);
<del> $this->assertTrue($this->Security->authRequired($this->Controller));
<add> $this->deprecated(function () {
<add> $this->Security->config('requireAuth', ['protected']);
<add> $this->Controller->request->params['controller'] = 'Allowed';
<add> $this->Controller->request->params['action'] = 'protected';
<add> $this->Controller->request->data = ['_Token' => 'not empty'];
<add> $this->Controller->request->session()->write('_Token', [
<add> 'allowedActions' => ['protected'],
<add> 'allowedControllers' => ['Allowed'],
<add> ]);
<add> $this->assertTrue($this->Security->authRequired($this->Controller));
<add> });
<ide> }
<ide> } | 7 |
Javascript | Javascript | support custom types | dbd85a08d9274689973aa24e4c4e4d7ee669c913 | <ide><path>packages/legacy-events/ReactSyntheticEventType.js
<ide> import type {EventPriority} from 'shared/ReactTypes';
<ide> import type {TopLevelType} from './TopLevelEventTypes';
<ide>
<ide> export type DispatchConfig = {|
<del> dependencies: Array<TopLevelType>,
<del> phasedRegistrationNames?: {|
<del> bubbled: string,
<del> captured: string,
<add> dependencies?: Array<TopLevelType>,
<add> phasedRegistrationNames: {|
<add> bubbled: null | string,
<add> captured: null | string,
<ide> |},
<ide> registrationName?: string,
<ide> eventPriority: EventPriority,
<ide> |};
<ide>
<add>export type CustomDispatchConfig = {|
<add> phasedRegistrationNames: {|
<add> bubbled: null,
<add> captured: null,
<add> |},
<add> customEvent: true,
<add>|};
<add>
<ide> export type ReactSyntheticEvent = {|
<del> dispatchConfig: DispatchConfig,
<add> dispatchConfig: DispatchConfig | CustomDispatchConfig,
<ide> getPooled: (
<del> dispatchConfig: DispatchConfig,
<add> dispatchConfig: DispatchConfig | CustomDispatchConfig,
<ide> targetInst: Fiber,
<ide> nativeTarget: Event,
<ide> nativeEventTarget: EventTarget,
<ide><path>packages/react-dom/src/events/DOMEventProperties.js
<ide> import type {
<ide> TopLevelType,
<ide> DOMTopLevelEventType,
<ide> } from 'legacy-events/TopLevelEventTypes';
<del>import type {DispatchConfig} from 'legacy-events/ReactSyntheticEventType';
<add>import type {
<add> DispatchConfig,
<add> CustomDispatchConfig,
<add>} from 'legacy-events/ReactSyntheticEventType';
<ide>
<ide> import * as DOMTopLevelEventTypes from './DOMTopLevelEventTypes';
<ide> import {
<ide> export const simpleEventPluginEventTypes = {};
<ide>
<ide> export const topLevelEventsToDispatchConfig: Map<
<ide> TopLevelType,
<del> DispatchConfig,
<add> DispatchConfig | CustomDispatchConfig,
<ide> > = new Map();
<ide>
<ide> const eventPriorities = new Map();
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import type {EventSystemFlags} from 'legacy-events/EventSystemFlags';
<ide> import type {EventPriority} from 'shared/ReactTypes';
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<ide> import type {PluginModule} from 'legacy-events/PluginModuleType';
<del>import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
<add>import type {
<add> ReactSyntheticEvent,
<add> CustomDispatchConfig,
<add>} from 'legacy-events/ReactSyntheticEventType';
<ide> import type {ReactDOMListener} from 'shared/ReactDOMTypes';
<ide>
<ide> import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
<ide> import {
<ide> COMMENT_NODE,
<ide> ELEMENT_NODE,
<ide> } from '../shared/HTMLNodeType';
<add>import {topLevelEventsToDispatchConfig} from './DOMEventProperties';
<ide>
<ide> import {enableLegacyFBSupport} from 'shared/ReactFeatureFlags';
<ide>
<ide> const capturePhaseEvents = new Set([
<ide> TOP_WAITING,
<ide> ]);
<ide>
<add>const emptyDispatchConfigForCustomEvents: CustomDispatchConfig = {
<add> customEvent: true,
<add> phasedRegistrationNames: {
<add> bubbled: null,
<add> captured: null,
<add> },
<add>};
<add>
<ide> const isArray = Array.isArray;
<ide>
<ide> function dispatchEventsForPlugins(
<ide> export function attachElementListener(listener: ReactDOMListener): void {
<ide> listeners = new Set();
<ide> initListenersSet(target, listeners);
<ide> }
<del> // Finally, add our listener to the listeners Set.
<add> // Add our listener to the listeners Set.
<ide> listeners.add(listener);
<add> // Finally, add the event to our known event types list.
<add> let dispatchConfig = topLevelEventsToDispatchConfig.get(type);
<add> // If we don't have a dispatchConfig, then we're dealing with
<add> // an event type that React does not know about (i.e. a custom event).
<add> // We need to register an event config for this or the SimpleEventPlugin
<add> // will not appropriately provide a SyntheticEvent, so we use out empty
<add> // dispatch config for custom events.
<add> if (dispatchConfig === undefined) {
<add> topLevelEventsToDispatchConfig.set(
<add> type,
<add> emptyDispatchConfigForCustomEvents,
<add> );
<add> }
<ide> }
<ide>
<ide> export function detachElementListener(listener: ReactDOMListener): void {
<ide><path>packages/react-dom/src/events/SimpleEventPlugin.js
<ide> const SimpleEventPlugin: PluginModule<MouseEvent> = {
<ide> break;
<ide> default:
<ide> if (__DEV__) {
<del> if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
<add> if (
<add> knownHTMLTopLevelTypes.indexOf(topLevelType) === -1 &&
<add> dispatchConfig.customEvent !== true
<add> ) {
<ide> console.error(
<ide> 'SimpleEventPlugin: Unhandled event type, `%s`. This warning ' +
<ide> 'is likely caused by a bug in React. Please file an issue.',
<ide><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js
<ide> let ReactDOM;
<ide> let ReactDOMServer;
<ide> let Scheduler;
<ide>
<del>function dispatchClickEvent(element) {
<add>function dispatchEvent(element, type) {
<ide> const event = document.createEvent('Event');
<del> event.initEvent('click', true, true);
<add> event.initEvent(type, true, true);
<ide> element.dispatchEvent(event);
<ide> }
<ide>
<add>function dispatchClickEvent(element) {
<add> dispatchEvent(element, 'click');
<add>}
<add>
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> let container;
<ide>
<ide> describe('DOMModernPluginEventSystem', () => {
<ide> dispatchClickEvent(button);
<ide> expect(clickEvent).toHaveBeenCalledTimes(1);
<ide> });
<add>
<add> it('handles propagation of custom user events', () => {
<add> const buttonRef = React.createRef();
<add> const divRef = React.createRef();
<add> const log = [];
<add> const onCustomEvent = jest.fn(e =>
<add> log.push(['bubble', e.currentTarget]),
<add> );
<add> const onCustomEventCapture = jest.fn(e =>
<add> log.push(['capture', e.currentTarget]),
<add> );
<add>
<add> function Test() {
<add> let customEventHandle;
<add>
<add> // Test that we get a warning when we don't provide an explicit priortiy
<add> expect(() => {
<add> customEventHandle = ReactDOM.unstable_useEvent('custom-event');
<add> }).toWarnDev(
<add> 'Warning: The event "type" provided to useEvent() does not have a known priority type. ' +
<add> 'It is recommended to provide a "priority" option to specify a priority.',
<add> );
<add>
<add> customEventHandle = ReactDOM.unstable_useEvent('custom-event', {
<add> priority: 0, // Discrete
<add> });
<add>
<add> const customCaptureHandle = ReactDOM.unstable_useEvent(
<add> 'custom-event',
<add> {
<add> capture: true,
<add> priority: 0, // Discrete
<add> },
<add> );
<add>
<add> React.useEffect(() => {
<add> customEventHandle.setListener(buttonRef.current, onCustomEvent);
<add> customCaptureHandle.setListener(
<add> buttonRef.current,
<add> onCustomEventCapture,
<add> );
<add> customEventHandle.setListener(divRef.current, onCustomEvent);
<add> customCaptureHandle.setListener(
<add> divRef.current,
<add> onCustomEventCapture,
<add> );
<add> });
<add>
<add> return (
<add> <button ref={buttonRef}>
<add> <div ref={divRef}>Click me!</div>
<add> </button>
<add> );
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add> Scheduler.unstable_flushAll();
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchEvent(buttonElement, 'custom-event');
<add> expect(onCustomEvent).toHaveBeenCalledTimes(1);
<add> expect(onCustomEventCapture).toHaveBeenCalledTimes(1);
<add> expect(log[0]).toEqual(['capture', buttonElement]);
<add> expect(log[1]).toEqual(['bubble', buttonElement]);
<add>
<add> let divElement = divRef.current;
<add> dispatchEvent(divElement, 'custom-event');
<add> expect(onCustomEvent).toHaveBeenCalledTimes(3);
<add> expect(onCustomEventCapture).toHaveBeenCalledTimes(3);
<add> expect(log[2]).toEqual(['capture', buttonElement]);
<add> expect(log[3]).toEqual(['capture', divElement]);
<add> expect(log[4]).toEqual(['bubble', divElement]);
<add> expect(log[5]).toEqual(['bubble', buttonElement]);
<add> });
<ide> });
<ide> },
<ide> );
<ide><path>packages/react-dom/src/events/accumulateTwoPhaseListeners.js
<ide> export default function accumulateTwoPhaseListeners(
<ide> accumulateUseEventListeners?: boolean,
<ide> ): void {
<ide> const phasedRegistrationNames = event.dispatchConfig.phasedRegistrationNames;
<del> if (phasedRegistrationNames == null) {
<del> return;
<del> }
<del> const {bubbled, captured} = phasedRegistrationNames;
<ide> const dispatchListeners = [];
<ide> const dispatchInstances = [];
<add> const {bubbled, captured} = phasedRegistrationNames;
<ide> let node = event._targetInst;
<ide>
<ide> // Accumulate all instances and listeners via the target -> root path.
<ide> export default function accumulateTwoPhaseListeners(
<ide> }
<ide> }
<ide> // Standard React on* listeners, i.e. onClick prop
<del> const captureListener = getListener(node, captured);
<del> if (captureListener != null) {
<del> // Capture listeners/instances should go at the start, so we
<del> // unshift them to the start of the array.
<del> dispatchListeners.unshift(captureListener);
<del> dispatchInstances.unshift(node);
<add> if (captured !== null) {
<add> const captureListener = getListener(node, captured);
<add> if (captureListener != null) {
<add> // Capture listeners/instances should go at the start, so we
<add> // unshift them to the start of the array.
<add> dispatchListeners.unshift(captureListener);
<add> dispatchInstances.unshift(node);
<add> }
<ide> }
<del> const bubbleListener = getListener(node, bubbled);
<del> if (bubbleListener != null) {
<del> // Bubble listeners/instances should go at the end, so we
<del> // push them to the end of the array.
<del> dispatchListeners.push(bubbleListener);
<del> dispatchInstances.push(node);
<add> if (bubbled !== null) {
<add> const bubbleListener = getListener(node, bubbled);
<add> if (bubbleListener != null) {
<add> // Bubble listeners/instances should go at the end, so we
<add> // push them to the end of the array.
<add> dispatchListeners.push(bubbleListener);
<add> dispatchInstances.push(node);
<add> }
<ide> }
<ide> }
<ide> node = node.return; | 6 |
Javascript | Javascript | allow longer time to connect | c4c9614e9611c3693c2a86c4231c929e2bc49490 | <ide><path>lib/internal/inspector/_inspect.js
<ide> class NodeInspector {
<ide> this.stdout.write(' ok\n');
<ide> }, (error) => {
<ide> debuglog('connect failed', error);
<del> // If it's failed to connect 10 times then print failed message
<del> if (connectionAttempts >= 10) {
<add> // If it's failed to connect 5 times then print failed message
<add> if (connectionAttempts >= 5) {
<ide> this.stdout.write(' failed to connect, please retry\n');
<ide> process.exit(1);
<ide> }
<ide>
<del> return new Promise((resolve) => setTimeout(resolve, 500))
<add> return new Promise((resolve) => setTimeout(resolve, 1000))
<ide> .then(attemptConnect);
<ide> });
<ide> }; | 1 |
Text | Text | add table header in intl.md | 0ac2d0fafd2ce9aa451802f8b53d7d809939c1da | <ide><path>doc/api/intl.md
<ide> in [BUILDING.md][].
<ide> An overview of available Node.js and JavaScript features for each `configure`
<ide> option:
<ide>
<del>| | `none` | `system-icu` | `small-icu` | `full-icu` |
<add>| Feature | `none` | `system-icu` | `small-icu` | `full-icu` |
<ide> |-----------------------------------------|-----------------------------------|------------------------------|------------------------|------------|
<ide> | [`String.prototype.normalize()`][] | none (function is no-op) | full | full | full |
<ide> | `String.prototype.to*Case()` | full | full | full | full | | 1 |
Java | Java | fix view translations in android | b12117a03847f8ead4a202c863a0000abe6abd34 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java
<ide> public void setScaleY(T view, float scaleY) {
<ide> @Deprecated
<ide> @ReactProp(name = PROP_TRANSLATE_X, defaultFloat = 1f)
<ide> public void setTranslateX(T view, float translateX) {
<del> view.setTranslationX(translateX);
<add> view.setTranslationX(PixelUtil.toPixelFromDIP(translateX));
<ide> }
<ide>
<ide> @Deprecated
<ide> @ReactProp(name = PROP_TRANSLATE_Y, defaultFloat = 1f)
<ide> public void setTranslateY(T view, float translateY) {
<del> view.setTranslationY(translateY);
<add> view.setTranslationY(PixelUtil.toPixelFromDIP(translateY));
<ide> }
<ide>
<ide> @ReactProp(name = PROP_ACCESSIBILITY_LIVE_REGION) | 1 |
Ruby | Ruby | reduce allocations in dependency construction | b32202033881d93849f4c44a837389e8a9d450ef | <ide><path>Library/Homebrew/dependency.rb
<ide> class Dependency
<ide>
<ide> attr_reader :name, :tags
<ide>
<del> def initialize(name, *tags)
<add> def initialize(name, tags=[])
<ide> @name = name
<del> @tags = tags.flatten.compact
<add> @tags = tags
<ide> end
<ide>
<ide> def to_s
<ide><path>Library/Homebrew/dependency_collector.rb
<ide> def add(spec)
<ide> end
<ide>
<ide> def build(spec)
<del> spec, tag = case spec
<del> when Hash then spec.shift
<del> else spec
<del> end
<add> spec, tags = case spec
<add> when Hash then spec.shift
<add> else spec
<add> end
<ide>
<del> parse_spec(spec, tag)
<add> parse_spec(spec, Array(tags))
<ide> end
<ide>
<ide> private
<ide>
<del> def parse_spec spec, tag
<add> def parse_spec(spec, tags)
<ide> case spec
<ide> when String
<del> parse_string_spec(spec, tag)
<add> parse_string_spec(spec, tags)
<ide> when Symbol
<del> parse_symbol_spec(spec, tag)
<add> parse_symbol_spec(spec, tags)
<ide> when Requirement, Dependency
<ide> spec
<ide> when Class
<del> parse_class_spec(spec, tag)
<add> parse_class_spec(spec, tags)
<ide> else
<ide> raise TypeError, "Unsupported type #{spec.class} for #{spec}"
<ide> end
<ide> end
<ide>
<del> def parse_string_spec(spec, tag)
<del> if tag && LANGUAGE_MODULES.include?(tag)
<add> def parse_string_spec(spec, tags)
<add> if tags.empty?
<add> Dependency.new(spec, tags)
<add> elsif (tag = tags.first) && LANGUAGE_MODULES.include?(tag)
<ide> LanguageModuleDependency.new(tag, spec)
<ide> else
<del> Dependency.new(spec, tag)
<add> Dependency.new(spec, tags)
<ide> end
<ide> end
<ide>
<del> def parse_symbol_spec spec, tag
<add> def parse_symbol_spec(spec, tags)
<ide> case spec
<ide> when :autoconf, :automake, :bsdmake, :libtool, :libltdl
<ide> # Xcode no longer provides autotools or some other build tools
<del> autotools_dep(spec, tag)
<del> when :x11 then X11Dependency.new(spec.to_s, tag)
<add> autotools_dep(spec, tags)
<add> when :x11 then X11Dependency.new(spec.to_s, tags)
<ide> when *X11Dependency::Proxy::PACKAGES
<del> x11_dep(spec, tag)
<add> x11_dep(spec, tags)
<ide> when :cairo, :pixman
<ide> # We no longer use X11 psuedo-deps for cairo or pixman,
<ide> # so just return a standard formula dependency.
<del> Dependency.new(spec.to_s, tag)
<del> when :xcode then XcodeDependency.new(tag)
<del> when :mysql then MysqlDependency.new(tag)
<del> when :postgresql then PostgresqlDependency.new(tag)
<del> when :tex then TeXDependency.new(tag)
<del> when :clt then CLTDependency.new(tag)
<del> when :arch then ArchRequirement.new(tag)
<del> when :hg then MercurialDependency.new(tag)
<add> Dependency.new(spec.to_s, tags)
<add> when :xcode then XcodeDependency.new(tags)
<add> when :mysql then MysqlDependency.new(tags)
<add> when :postgresql then PostgresqlDependency.new(tags)
<add> when :tex then TeXDependency.new(tags)
<add> when :clt then CLTDependency.new(tags)
<add> when :arch then ArchRequirement.new(tags)
<add> when :hg then MercurialDependency.new(tags)
<ide> else
<ide> raise "Unsupported special dependency #{spec}"
<ide> end
<ide> end
<ide>
<del> def parse_class_spec(spec, tag)
<add> def parse_class_spec(spec, tags)
<ide> if spec < Requirement
<del> spec.new(tag)
<add> spec.new(tags)
<ide> else
<ide> raise TypeError, "#{spec} is not a Requirement subclass"
<ide> end
<ide> end
<ide>
<del> def x11_dep(spec, tag)
<add> def x11_dep(spec, tags)
<ide> if MacOS.version >= :mountain_lion
<del> Dependency.new(spec.to_s, tag)
<add> Dependency.new(spec.to_s, tags)
<ide> else
<del> X11Dependency::Proxy.for(spec.to_s, tag)
<add> X11Dependency::Proxy.for(spec.to_s, tags)
<ide> end
<ide> end
<ide>
<del> def autotools_dep(spec, tag)
<del> case spec
<del> when :libltdl then spec, tag = :libtool, Array(tag)
<del> else tag = Array(tag) << :build
<del> end
<del>
<add> def autotools_dep(spec, tags)
<ide> unless MacOS::Xcode.provides_autotools?
<del> Dependency.new(spec.to_s, tag)
<add> case spec
<add> when :libltdl then spec = :libtool
<add> else tags << :build
<add> end
<add>
<add> Dependency.new(spec.to_s, tags)
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/requirement.rb
<ide> class Requirement
<ide>
<ide> attr_reader :tags, :name
<ide>
<del> def initialize(*tags)
<del> @tags = tags.flatten.compact
<add> def initialize(tags=[])
<add> @tags = tags
<ide> @tags << :build if self.class.build
<ide> @name ||= infer_name
<ide> end
<ide><path>Library/Homebrew/requirements/language_module_dependency.rb
<ide> def initialize language, module_name, import_name=module_name
<ide> @language = language
<ide> @module_name = module_name
<ide> @import_name = import_name
<del> super
<add> super([language, module_name, import_name])
<ide> end
<ide>
<ide> satisfy { quiet_system(*the_test) }
<ide><path>Library/Homebrew/requirements/x11_dependency.rb
<ide> class X11Dependency < Requirement
<ide>
<ide> env { ENV.x11 }
<ide>
<del> def initialize(name="x11", *tags)
<del> tags.flatten!
<add> def initialize(name="x11", tags=[])
<ide> @name = name
<ide> @min_version = tags.shift if /(\d\.)+\d/ === tags.first
<ide> super(tags)
<ide> def defines_const?(const)
<ide> end
<ide> end
<ide>
<del> def for(name, *tags)
<add> def for(name, tags=[])
<ide> constant = name.capitalize
<ide>
<ide> if defines_const?(constant)
<ide> klass = const_get(constant)
<ide> else
<ide> klass = Class.new(self) do
<del> def initialize(name, *tags) super end
<add> def initialize(name, tags) super end
<ide> end
<ide>
<ide> const_set(constant, klass)
<ide> end
<del> klass.new(name, *tags)
<add> klass.new(name, tags)
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_comparableset.rb
<ide> def test_merging_multiple_dependencies
<ide>
<ide> def test_comparison_prefers_larger
<ide> @set << X11Dependency.new
<del> @set << X11Dependency.new('x11', '2.6')
<add> @set << X11Dependency.new('x11', %w{2.6})
<ide> assert_equal 1, @set.count
<del> assert_equal [X11Dependency.new('x11', '2.6')], @set.to_a
<add> assert_equal [X11Dependency.new('x11', %w{2.6})], @set.to_a
<ide> end
<ide>
<ide> def test_comparison_does_not_merge_smaller
<del> @set << X11Dependency.new('x11', '2.6')
<add> @set << X11Dependency.new('x11', %w{2.6})
<ide> @set << X11Dependency.new
<ide> assert_equal 1, @set.count
<del> assert_equal [X11Dependency.new('x11', '2.6')], @set.to_a
<add> assert_equal [X11Dependency.new('x11', %w{2.6})], @set.to_a
<ide> end
<ide>
<ide> def test_merging_sets
<ide> @set << X11Dependency.new
<ide> @set << Requirement.new
<del> reqs = Set.new [X11Dependency.new('x11', '2.6'), Requirement.new]
<add> reqs = Set.new [X11Dependency.new('x11', %w{2.6}), Requirement.new]
<ide> assert_same @set, @set.merge(reqs)
<ide>
<ide> assert_equal 2, @set.count
<del> assert_equal X11Dependency.new('x11', '2.6'), @set.find {|r| r.is_a? X11Dependency}
<add> assert_equal X11Dependency.new('x11', %w{2.6}), @set.find {|r| r.is_a? X11Dependency}
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_dependency.rb
<ide> def test_interrogation
<ide>
<ide> class DependencyTests < Test::Unit::TestCase
<ide> def test_accepts_single_tag
<del> dep = Dependency.new("foo", "bar")
<add> dep = Dependency.new("foo", %w{bar})
<ide> assert_equal %w{bar}, dep.tags
<ide> end
<ide>
<ide> def test_accepts_multiple_tags
<ide> end
<ide>
<ide> def test_preserves_symbol_tags
<del> dep = Dependency.new("foo", :build)
<add> dep = Dependency.new("foo", [:build])
<ide> assert_equal [:build], dep.tags
<ide> end
<ide>
<ide><path>Library/Homebrew/test/test_dependency_collector.rb
<ide> def test_add_returns_created_dep
<ide> end
<ide>
<ide> def test_dependency_tags
<del> assert Dependency.new('foo', :build).build?
<add> assert Dependency.new('foo', [:build]).build?
<ide> assert Dependency.new('foo', [:build, :optional]).optional?
<ide> assert Dependency.new('foo', [:universal]).options.include? '--universal'
<ide> assert_empty Dependency.new('foo').tags
<ide><path>Library/Homebrew/test/test_requirement.rb
<ide>
<ide> class RequirementTests < Test::Unit::TestCase
<ide> def test_accepts_single_tag
<del> dep = Requirement.new("bar")
<add> dep = Requirement.new(%w{bar})
<ide> assert_equal %w{bar}, dep.tags
<ide> end
<ide>
<ide> def test_accepts_multiple_tags
<ide> dep = Requirement.new(%w{bar baz})
<ide> assert_equal %w{bar baz}.sort, dep.tags.sort
<del> dep = Requirement.new(*%w{bar baz})
<del> assert_equal %w{bar baz}.sort, dep.tags.sort
<ide> end
<ide>
<ide> def test_preserves_symbol_tags
<del> dep = Requirement.new(:build)
<add> dep = Requirement.new([:build])
<ide> assert_equal [:build], dep.tags
<ide> end
<ide>
<ide> def test_accepts_symbol_and_string_tags
<ide> dep = Requirement.new([:build, "bar"])
<ide> assert_equal [:build, "bar"], dep.tags
<del> dep = Requirement.new(:build, "bar")
<del> assert_equal [:build, "bar"], dep.tags
<ide> end
<ide>
<ide> def test_dsl_fatal | 9 |
Python | Python | reduce timeout in test canvas | c57100beb179621f4f8f4f33098d0d748ad54a0e | <ide><path>t/integration/test_canvas.py
<ide> def is_retryable_exception(exc):
<ide> return isinstance(exc, RETRYABLE_EXCEPTIONS)
<ide>
<ide>
<del>TIMEOUT = 120
<add>TIMEOUT = 60
<add>
<add>
<add>flaky = pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<ide>
<ide>
<ide> class test_link_error:
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error_eager(self):
<ide> exception = ExpectedException("Task expected to fail", "test")
<ide> result = fail.apply(args=("test",), link_error=return_exception.s())
<ide> actual = result.get(timeout=TIMEOUT, propagate=False)
<ide> assert actual == exception
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error(self):
<ide> exception = ExpectedException("Task expected to fail", "test")
<ide> result = fail.apply(args=("test",), link_error=return_exception.s())
<ide> actual = result.get(timeout=TIMEOUT, propagate=False)
<ide> assert actual == exception
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error_callback_error_callback_retries_eager(self):
<ide> exception = ExpectedException("Task expected to fail", "test")
<ide> result = fail.apply(
<ide> def test_link_error_callback_error_callback_retries_eager(self):
<ide> )
<ide> assert result.get(timeout=TIMEOUT, propagate=False) == exception
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error_callback_retries(self):
<ide> exception = ExpectedException("Task expected to fail", "test")
<ide> result = fail.apply_async(
<ide> def test_link_error_callback_retries(self):
<ide> )
<ide> assert result.get(timeout=TIMEOUT, propagate=False) == exception
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error_using_signature_eager(self):
<ide> fail = signature('t.integration.tasks.fail', args=("test",))
<ide> retrun_exception = signature('t.integration.tasks.return_exception')
<ide> def test_link_error_using_signature_eager(self):
<ide> assert (fail.apply().get(timeout=TIMEOUT, propagate=False), True) == (
<ide> exception, True)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_link_error_using_signature(self):
<ide> fail = signature('t.integration.tasks.fail', args=("test",))
<ide> retrun_exception = signature('t.integration.tasks.return_exception')
<ide> def test_link_error_using_signature(self):
<ide>
<ide> class test_chain:
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_simple_chain(self, manager):
<ide> c = add.s(4, 4) | add.s(8) | add.s(16)
<ide> assert c().get(timeout=TIMEOUT) == 32
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_single_chain(self, manager):
<ide> c = chain(add.s(3, 4))()
<ide> assert c.get(timeout=TIMEOUT) == 7
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_complex_chain(self, manager):
<ide> c = (
<ide> add.s(2, 2) | (
<ide> def test_complex_chain(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [64, 65, 66, 67]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_group_results_in_chain(self, manager):
<ide> # This adds in an explicit test for the special case added in commit
<ide> # 1e3fcaa969de6ad32b52a3ed8e74281e5e5360e6
<ide> def test_chain_on_error(self, manager):
<ide> with pytest.raises(ExpectedException):
<ide> res.parent.get(propagate=True)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_inside_group_receives_arguments(self, manager):
<ide> c = (
<ide> add.s(5, 6) |
<ide> def test_chain_inside_group_receives_arguments(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [14, 14]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_eager_chain_inside_task(self, manager):
<ide> from .tasks import chain_add
<ide>
<ide> def test_eager_chain_inside_task(self, manager):
<ide>
<ide> chain_add.app.conf.task_always_eager = prev
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_group_chord_group_chain(self, manager):
<ide> from celery.five import bytes_if_py2
<ide>
<ide> def test_group_chord_group_chain(self, manager):
<ide> assert set(redis_messages[4:]) == after_items
<ide> redis_connection.delete('redis-echo')
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_group_result_not_has_cache(self, manager):
<ide> t1 = identity.si(1)
<ide> t2 = identity.si(2)
<ide> def test_group_result_not_has_cache(self, manager):
<ide> result = task.delay()
<ide> assert result.get(timeout=TIMEOUT) == [1, 2, [3, 4]]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_second_order_replace(self, manager):
<ide> from celery.five import bytes_if_py2
<ide>
<ide> def test_second_order_replace(self, manager):
<ide> b'Out A']
<ide> assert redis_messages == expected_messages
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_parent_ids(self, manager, num=10):
<ide> assert_ping(manager)
<ide>
<ide> def test_chain_error_handler_with_eta(self, manager):
<ide> result = c.get()
<ide> assert result == 10
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_groupresult_serialization(self, manager):
<ide> """Test GroupResult is correctly serialized
<ide> to save in the result backend"""
<ide> def test_groupresult_serialization(self, manager):
<ide> assert len(result) == 2
<ide> assert isinstance(result[0][1], list)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_task_a_group_and_a_chord(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_task_a_group_and_a_chord(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == 8
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_chords_as_groups_chained_to_a_task_with_two_tasks(self,
<ide> manager):
<ide> try:
<ide> def test_chain_of_chords_as_groups_chained_to_a_task_with_two_tasks(self,
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == 12
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_chords_with_two_tasks(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_chords_with_two_tasks(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == 12
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_a_chord_and_a_group_with_two_tasks(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_a_chord_and_a_group_with_two_tasks(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [6, 6]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_a_chord_and_a_task_and_a_group(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_a_chord_and_a_task_and_a_group(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [6, 6]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_a_chord_and_two_tasks_and_a_group(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_a_chord_and_two_tasks_and_a_group(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [7, 7]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_of_a_chord_and_three_tasks_and_a_group(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_of_a_chord_and_three_tasks_and_a_group(self, manager):
<ide>
<ide> class test_result_set:
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_result_set(self, manager):
<ide> assert_ping(manager)
<ide>
<ide> rs = ResultSet([add.delay(1, 1), add.delay(2, 2)])
<ide> assert rs.get(timeout=TIMEOUT) == [2, 4]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_result_set_error(self, manager):
<ide> assert_ping(manager)
<ide>
<ide> def test_result_set_error(self, manager):
<ide>
<ide>
<ide> class test_group:
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_ready_with_exception(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_ready_with_exception(self, manager):
<ide> while not result.ready():
<ide> pass
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_empty_group_result(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_empty_group_result(self, manager):
<ide> task = GroupResult.restore(result.id)
<ide> assert task.results == []
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_parent_ids(self, manager):
<ide> assert_ping(manager)
<ide>
<ide> def test_parent_ids(self, manager):
<ide> assert parent_id == expected_parent_id
<ide> assert value == i + 2
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_nested_group(self, manager):
<ide> assert_ping(manager)
<ide>
<ide> def test_nested_group(self, manager):
<ide>
<ide> assert res.get(timeout=TIMEOUT) == [11, 101, 1001, 2001]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_large_group(self, manager):
<ide> assert_ping(manager)
<ide>
<ide> def assert_ping(manager):
<ide>
<ide>
<ide> class test_chord:
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_simple_chord_with_a_delay_in_group_save(self, manager, monkeypatch):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def apply_chord_incr_with_sleep(self, *args, **kwargs):
<ide> result = c()
<ide> assert result.get(timeout=TIMEOUT) == 4
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_redis_subscribed_channels_leak(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_redis_subscribed_channels_leak(self, manager):
<ide> assert channels_after_count == initial_channels_count
<ide> assert set(channels_after) == set(initial_channels)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_replaced_nested_chord(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_replaced_nested_chord(self, manager):
<ide> res1 = c1()
<ide> assert res1.get(timeout=TIMEOUT) == [29, 38]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_add_to_chord(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_add_to_chord(self, manager):
<ide> res = c()
<ide> assert sorted(res.get()) == [0, 5, 6, 7]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_add_chord_to_chord(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_add_chord_to_chord(self, manager):
<ide> res = c()
<ide> assert res.get() == [0, 5 + 6 + 7]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_eager_chord_inside_task(self, manager):
<ide> from .tasks import chord_add
<ide>
<ide> def test_eager_chord_inside_task(self, manager):
<ide>
<ide> chord_add.app.conf.task_always_eager = prev
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_group_chain(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_group_chain(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [12, 13, 14, 15]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> @pytest.mark.xfail(os.environ['TEST_BACKEND'] == 'cache+pylibmc://',
<ide> reason="Not supported yet by the cache backend.",
<ide> strict=True,
<ide> def test_nested_group_chain(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == 11
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_single_task_header(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_empty_header_chord(self, manager):
<ide> res2 = c2()
<ide> assert res2.get(timeout=TIMEOUT) == []
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_nested_chord(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_nested_chord(self, manager):
<ide> res = c()
<ide> assert [[[[3, 3], 4], 5], 6] == res.get(timeout=TIMEOUT)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_parent_ids(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_parent_ids(self, manager):
<ide> )
<ide> self.assert_parentids_chord(g(), expected_root_id)
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_parent_ids__OR(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide> raise pytest.skip('Requires redis result backend.')
<ide> def test_chord_on_error(self, manager):
<ide> assert len([cr for cr in chord_results if cr[2] != states.SUCCESS]
<ide> ) == 1
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_parallel_chords(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_parallel_chords(self, manager):
<ide>
<ide> assert r.get(timeout=TIMEOUT) == [10, 10]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chord_in_chords_with_chains(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chord_in_chords_with_chains(self, manager):
<ide>
<ide> assert r.get(timeout=TIMEOUT) == 4
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_chord_chain_chord(self, manager):
<ide> # test for #2573
<ide> try:
<ide> def test_chord_in_chain_with_args(self, manager):
<ide> res1 = c1.apply(args=(1,))
<ide> assert res1.get(timeout=TIMEOUT) == [1, 1]
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_large_header(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_large_header(self, manager):
<ide> res = c.delay()
<ide> assert res.get(timeout=TIMEOUT) == 499500
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_chain_to_a_chord_with_large_header(self, manager):
<ide> try:
<ide> manager.app.backend.ensure_chords_allowed()
<ide> def test_chain_to_a_chord_with_large_header(self, manager):
<ide> res = c.delay()
<ide> assert res.get(timeout=TIMEOUT) == 1000
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_priority(self, manager):
<ide> c = chain(return_priority.signature(priority=3))()
<ide> assert c.get(timeout=TIMEOUT) == "Priority: 3"
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=1, cause=is_retryable_exception)
<add> @flaky
<ide> def test_priority_chain(self, manager):
<ide> c = return_priority.signature(priority=3) | return_priority.signature(
<ide> priority=5)
<ide><path>t/integration/test_tasks.py
<ide> retry_once_priority, sleeping, ClassBasedAutoRetryTask)
<ide>
<ide>
<add>TIMEOUT = 10
<add>
<add>
<add>flaky = pytest.mark.flaky(reruns=5, reruns_delay=2)
<add>
<add>
<ide> class test_class_based_tasks:
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=2)
<add> @flaky
<ide> def test_class_based_task_retried(self, celery_session_app,
<ide> celery_session_worker):
<ide> task = ClassBasedAutoRetryTask()
<ide> celery_session_app.tasks.register(task)
<ide> res = task.delay()
<del> assert res.get(timeout=10) == 1
<add> assert res.get(timeout=TIMEOUT) == 1
<ide>
<ide>
<ide> class test_tasks:
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=2)
<add> @flaky
<ide> def test_task_accepted(self, manager, sleep=1):
<ide> r1 = sleeping.delay(sleep)
<ide> sleeping.delay(sleep)
<ide> manager.assert_accepted([r1.id])
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=2)
<add> @flaky
<ide> def test_task_retried(self):
<ide> res = retry_once.delay()
<del> assert res.get(timeout=10) == 1 # retried once
<add> assert res.get(timeout=TIMEOUT) == 1 # retried once
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=2)
<add> @flaky
<ide> def test_task_retried_priority(self):
<ide> res = retry_once_priority.apply_async(priority=7)
<del> assert res.get(timeout=10) == 7 # retried once with priority 7
<add> assert res.get(timeout=TIMEOUT) == 7 # retried once with priority 7
<ide>
<del> @pytest.mark.flaky(reruns=5, reruns_delay=2)
<add> @flaky
<ide> def test_unicode_task(self, manager):
<ide> manager.join(
<ide> group(print_unicode.s() for _ in range(5))(),
<del> timeout=10, propagate=True,
<add> timeout=TIMEOUT, propagate=True,
<ide> )
<ide>
<ide> | 2 |
Javascript | Javascript | add more info to invalid hook call error message | 2b93d686e359c7afa299e2ec5cf63160a32a1155 | <ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspection-test.js
<ide> describe('ReactHooksInspection', () => {
<ide> expect(() => {
<ide> ReactDebugTools.inspectHooks(Foo, {}, FakeDispatcherRef);
<ide> }).toThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide>
<ide> expect(getterCalls).toBe(1);
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js
<ide> describe('ReactHooksInspectionIntegration', () => {
<ide> expect(() => {
<ide> ReactDebugTools.inspectHooksOfFiber(childFiber, FakeDispatcherRef);
<ide> }).toThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide>
<ide> expect(getterCalls).toBe(1);
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.internal.js
<ide> describe('ReactDOMServerHooks', () => {
<ide>
<ide> return render(<Counter />);
<ide> },
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide>
<ide> itRenders('multiple times when an updater is called', async render => {
<ide> describe('ReactDOMServerHooks', () => {
<ide>
<ide> return render(<Counter />);
<ide> },
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> });
<ide>
<ide><path>packages/react-dom/src/server/ReactPartialRendererHooks.js
<ide> let currentHookNameInDev: ?string;
<ide> function resolveCurrentlyRenderingComponent(): Object {
<ide> invariant(
<ide> currentlyRenderingComponent !== null,
<del> 'Hooks can only be called inside the body of a function component. ' +
<del> '(https://fb.me/react-invalid-hook-call)',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> if (__DEV__) {
<ide> warning(
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js
<ide> function warnOnHookMismatchInDev(currentHookName: HookType) {
<ide> function throwInvalidHookError() {
<ide> invariant(
<ide> false,
<del> 'Hooks can only be called inside the body of a function component. ' +
<del> '(https://fb.me/react-invalid-hook-call)',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactHooks-test.internal.js
<ide> describe('ReactHooks', () => {
<ide> expect(() => {
<ide> ReactTestRenderer.create(<Example />);
<ide> }).toThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen' +
<add> ' for one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> });
<ide> }
<ide> describe('ReactHooks', () => {
<ide> const root = ReactTestRenderer.create(<MemoApp />);
<ide> // trying to render again should trigger comparison and throw
<ide> expect(() => root.update(<MemoApp />)).toThrow(
<del> 'Hooks can only be called inside the body of a function component',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> // the next round, it does a fresh mount, so should render
<ide> expect(() => root.update(<MemoApp />)).not.toThrow(
<del> 'Hooks can only be called inside the body of a function component',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> // and then again, fail
<ide> expect(() => root.update(<MemoApp />)).toThrow(
<del> 'Hooks can only be called inside the body of a function component',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> });
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.internal.js
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> ReactNoop.render(<BadCounter />);
<ide>
<ide> expect(Scheduler).toFlushAndThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide>
<ide> // Confirm that a subsequent hook works properly.
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide> }
<ide> ReactNoop.render(<Counter />);
<ide> expect(Scheduler).toFlushAndThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide>
<ide> // Confirm that a subsequent hook works properly.
<ide> describe('ReactHooksWithNoopRenderer', () => {
<ide>
<ide> it('throws when called outside the render phase', () => {
<ide> expect(() => useState(0)).toThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> });
<ide>
<ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js
<ide> describe('ReactNewContext', () => {
<ide> }
<ide> ReactNoop.render(<Foo />);
<ide> expect(Scheduler).toFlushAndThrow(
<del> 'Hooks can only be called inside the body of a function component.',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen' +
<add> ' for one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> });
<ide>
<ide><path>packages/react-test-renderer/src/ReactShallowRenderer.js
<ide> class ReactShallowRenderer {
<ide> _validateCurrentlyRenderingComponent() {
<ide> invariant(
<ide> this._rendering && !this._instance,
<del> 'Hooks can only be called inside the body of a function component. ' +
<del> '(https://fb.me/react-invalid-hook-call)',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> }
<ide>
<ide><path>packages/react/src/ReactHooks.js
<ide> function resolveDispatcher() {
<ide> const dispatcher = ReactCurrentDispatcher.current;
<ide> invariant(
<ide> dispatcher !== null,
<del> 'Hooks can only be called inside the body of a function component. ' +
<del> '(https://fb.me/react-invalid-hook-call)',
<add> 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' +
<add> ' one of the following reasons:\n' +
<add> '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' +
<add> '2. You might be breaking the Rules of Hooks\n' +
<add> '3. You might have more than one copy of React in the same app\n' +
<add> 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.',
<ide> );
<ide> return dispatcher;
<ide> } | 10 |
Python | Python | fix t5 error message | 783b0dd5891174922ff6bc9874350063bd9a0135 | <ide><path>src/transformers/models/t5/modeling_t5.py
<ide> def forward(
<ide> if input_ids is not None and inputs_embeds is not None:
<ide> err_msg_prefix = "decoder_" if self.is_decoder else ""
<ide> raise ValueError(
<del> f"You cannot specify both {err_msg_prefix}inputs and {err_msg_prefix}inputs_embeds at the same time"
<add> f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
<ide> )
<ide> elif input_ids is not None:
<ide> input_shape = input_ids.size()
<ide> def forward(
<ide> input_shape = inputs_embeds.size()[:-1]
<ide> else:
<ide> err_msg_prefix = "decoder_" if self.is_decoder else ""
<del> raise ValueError(f"You have to specify either {err_msg_prefix}inputs or {err_msg_prefix}inputs_embeds")
<add> raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
<ide>
<ide> if inputs_embeds is None:
<ide> assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
<ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def call(
<ide> if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None:
<ide> err_msg_prefix = "decoder_" if self.is_decoder else ""
<ide> raise ValueError(
<del> f"You cannot specify both {err_msg_prefix}inputs and {err_msg_prefix}inputs_embeds at the same time"
<add> f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
<ide> )
<ide> elif inputs["input_ids"] is not None:
<ide> input_shape = shape_list(inputs["input_ids"])
<ide> def call(
<ide> input_shape = shape_list(inputs["inputs_embeds"])[:-1]
<ide> else:
<ide> err_msg_prefix = "decoder_" if self.is_decoder else ""
<del> raise ValueError(f"You have to specify either {err_msg_prefix}inputs or {err_msg_prefix}inputs_embeds")
<add> raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
<ide>
<ide> if inputs["inputs_embeds"] is None:
<ide> assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings" | 2 |
Ruby | Ruby | update ruby-macho to 1.2.0 | 99bf57d366b93dad617246dfe10867b6a34ab2b2 | <ide><path>Library/Homebrew/vendor/macho/macho.rb
<ide> # The primary namespace for ruby-macho.
<ide> module MachO
<ide> # release version
<del> VERSION = "1.1.0".freeze
<add> VERSION = "1.2.0".freeze
<ide>
<ide> # Opens the given filename as a MachOFile or FatFile, depending on its magic.
<ide> # @param filename [String] the file being opened
<ide><path>Library/Homebrew/vendor/macho/macho/exceptions.rb
<ide> class ModificationError < MachOError
<ide> # Raised when a Mach-O file modification fails but can be recovered when
<ide> # operating on multiple Mach-O slices of a fat binary in non-strict mode.
<ide> class RecoverableModificationError < ModificationError
<del> # @return [Fixnum, nil] The index of the Mach-O slice of a fat binary for
<add> # @return [Integer, nil] The index of the Mach-O slice of a fat binary for
<ide> # which modification failed or `nil` if not a fat binary. This is used to
<ide> # make the error message more useful.
<ide> attr_accessor :macho_slice
<ide> def initialize
<ide>
<ide> # Raised when a file's magic bytes are not valid Mach-O magic.
<ide> class MagicError < NotAMachOError
<del> # @param num [Fixnum] the unknown number
<add> # @param num [Integer] the unknown number
<ide> def initialize(num)
<ide> super "Unrecognized Mach-O magic: 0x#{"%02x" % num}"
<ide> end
<ide> def initialize
<ide>
<ide> # Raised when the CPU type is unknown.
<ide> class CPUTypeError < MachOError
<del> # @param cputype [Fixnum] the unknown CPU type
<add> # @param cputype [Integer] the unknown CPU type
<ide> def initialize(cputype)
<ide> super "Unrecognized CPU type: 0x#{"%08x" % cputype}"
<ide> end
<ide> end
<ide>
<ide> # Raised when the CPU type/sub-type pair is unknown.
<ide> class CPUSubtypeError < MachOError
<del> # @param cputype [Fixnum] the CPU type of the unknown pair
<del> # @param cpusubtype [Fixnum] the CPU sub-type of the unknown pair
<add> # @param cputype [Integer] the CPU type of the unknown pair
<add> # @param cpusubtype [Integer] the CPU sub-type of the unknown pair
<ide> def initialize(cputype, cpusubtype)
<ide> super "Unrecognized CPU sub-type: 0x#{"%08x" % cpusubtype}" \
<ide> " (for CPU type: 0x#{"%08x" % cputype})"
<ide> def initialize(cputype, cpusubtype)
<ide>
<ide> # Raised when a mach-o file's filetype field is unknown.
<ide> class FiletypeError < MachOError
<del> # @param num [Fixnum] the unknown number
<add> # @param num [Integer] the unknown number
<ide> def initialize(num)
<ide> super "Unrecognized Mach-O filetype code: 0x#{"%02x" % num}"
<ide> end
<ide> end
<ide>
<ide> # Raised when an unknown load command is encountered.
<ide> class LoadCommandError < MachOError
<del> # @param num [Fixnum] the unknown number
<add> # @param num [Integer] the unknown number
<ide> def initialize(num)
<ide> super "Unrecognized Mach-O load command: 0x#{"%02x" % num}"
<ide> end
<ide> def initialize(cmd_sym)
<ide> # is wrong.
<ide> class LoadCommandCreationArityError < MachOError
<ide> # @param cmd_sym [Symbol] the load command's symbol
<del> # @param expected_arity [Fixnum] the number of arguments expected
<del> # @param actual_arity [Fixnum] the number of arguments received
<add> # @param expected_arity [Integer] the number of arguments expected
<add> # @param actual_arity [Integer] the number of arguments received
<ide> def initialize(cmd_sym, expected_arity, actual_arity)
<ide> super "Expected #{expected_arity} arguments for #{cmd_sym} creation," \
<ide> " got #{actual_arity}"
<ide> def initialize(lc)
<ide>
<ide> # Raised when a change at an offset is not valid.
<ide> class OffsetInsertionError < ModificationError
<del> # @param offset [Fixnum] the invalid offset
<add> # @param offset [Integer] the invalid offset
<ide> def initialize(offset)
<ide> super "Insertion at offset #{offset} is not valid"
<ide> end
<ide><path>Library/Homebrew/vendor/macho/macho/fat_file.rb
<ide> def write(filename)
<ide> # @raise [MachOError] if the instance was initialized without a file
<ide> # @note Overwrites all data in the file!
<ide> def write!
<del> if filename.nil?
<del> raise MachOError, "cannot write to a default file when initialized from a binary string"
<del> else
<del> File.open(@filename, "wb") { |f| f.write(@raw_data) }
<del> end
<add> raise MachOError, "no initial file to write to" if filename.nil?
<add> File.open(@filename, "wb") { |f| f.write(@raw_data) }
<ide> end
<ide>
<ide> private
<ide><path>Library/Homebrew/vendor/macho/macho/headers.rb
<ide> module Headers
<ide> # Fat binary header structure
<ide> # @see MachO::FatArch
<ide> class FatHeader < MachOStructure
<del> # @return [Fixnum] the magic number of the header (and file)
<add> # @return [Integer] the magic number of the header (and file)
<ide> attr_reader :magic
<ide>
<del> # @return [Fixnum] the number of fat architecture structures following the header
<add> # @return [Integer] the number of fat architecture structures following the header
<ide> attr_reader :nfat_arch
<ide>
<ide> # always big-endian
<ide> def serialize
<ide> # these, representing one or more internal Mach-O blobs.
<ide> # @see MachO::Headers::FatHeader
<ide> class FatArch < MachOStructure
<del> # @return [Fixnum] the CPU type of the Mach-O
<add> # @return [Integer] the CPU type of the Mach-O
<ide> attr_reader :cputype
<ide>
<del> # @return [Fixnum] the CPU subtype of the Mach-O
<add> # @return [Integer] the CPU subtype of the Mach-O
<ide> attr_reader :cpusubtype
<ide>
<del> # @return [Fixnum] the file offset to the beginning of the Mach-O data
<add> # @return [Integer] the file offset to the beginning of the Mach-O data
<ide> attr_reader :offset
<ide>
<del> # @return [Fixnum] the size, in bytes, of the Mach-O data
<add> # @return [Integer] the size, in bytes, of the Mach-O data
<ide> attr_reader :size
<ide>
<del> # @return [Fixnum] the alignment, as a power of 2
<add> # @return [Integer] the alignment, as a power of 2
<ide> attr_reader :align
<ide>
<ide> # always big-endian
<ide> def serialize
<ide>
<ide> # 32-bit Mach-O file header structure
<ide> class MachHeader < MachOStructure
<del> # @return [Fixnum] the magic number
<add> # @return [Integer] the magic number
<ide> attr_reader :magic
<ide>
<del> # @return [Fixnum] the CPU type of the Mach-O
<add> # @return [Integer] the CPU type of the Mach-O
<ide> attr_reader :cputype
<ide>
<del> # @return [Fixnum] the CPU subtype of the Mach-O
<add> # @return [Integer] the CPU subtype of the Mach-O
<ide> attr_reader :cpusubtype
<ide>
<del> # @return [Fixnum] the file type of the Mach-O
<add> # @return [Integer] the file type of the Mach-O
<ide> attr_reader :filetype
<ide>
<del> # @return [Fixnum] the number of load commands in the Mach-O
<add> # @return [Integer] the number of load commands in the Mach-O
<ide> attr_reader :ncmds
<ide>
<del> # @return [Fixnum] the size of all load commands, in bytes, in the Mach-O
<add> # @return [Integer] the size of all load commands, in bytes, in the Mach-O
<ide> attr_reader :sizeofcmds
<ide>
<del> # @return [Fixnum] the header flags associated with the Mach-O
<add> # @return [Integer] the header flags associated with the Mach-O
<ide> attr_reader :flags
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def magic64?
<ide> Utils.magic64?(magic)
<ide> end
<ide>
<del> # @return [Fixnum] the file's internal alignment
<add> # @return [Integer] the file's internal alignment
<ide> def alignment
<ide> magic32? ? 4 : 8
<ide> end
<ide><path>Library/Homebrew/vendor/macho/macho/load_commands.rb
<ide> module LoadCommands
<ide> 0x2e => :LC_LINKER_OPTIMIZATION_HINT,
<ide> 0x2f => :LC_VERSION_MIN_TVOS,
<ide> 0x30 => :LC_VERSION_MIN_WATCHOS,
<add> 0x31 => :LC_NOTE,
<add> 0x32 => :LC_BUILD_VERSION,
<ide> }.freeze
<ide>
<ide> # association of symbol representations to load command constants
<ide> module LoadCommands
<ide>
<ide> # load commands responsible for loading dylibs
<ide> # @api private
<del> DYLIB_LOAD_COMMANDS = [
<del> :LC_LOAD_DYLIB,
<del> :LC_LOAD_WEAK_DYLIB,
<del> :LC_REEXPORT_DYLIB,
<del> :LC_LAZY_LOAD_DYLIB,
<del> :LC_LOAD_UPWARD_DYLIB,
<add> DYLIB_LOAD_COMMANDS = %i[
<add> LC_LOAD_DYLIB
<add> LC_LOAD_WEAK_DYLIB
<add> LC_REEXPORT_DYLIB
<add> LC_LAZY_LOAD_DYLIB
<add> LC_LOAD_UPWARD_DYLIB
<ide> ].freeze
<ide>
<ide> # load commands that can be created manually via {LoadCommand.create}
<ide> # @api private
<del> CREATABLE_LOAD_COMMANDS = DYLIB_LOAD_COMMANDS + [
<del> :LC_ID_DYLIB,
<del> :LC_RPATH,
<del> :LC_LOAD_DYLINKER,
<add> CREATABLE_LOAD_COMMANDS = DYLIB_LOAD_COMMANDS + %i[
<add> LC_ID_DYLIB
<add> LC_RPATH
<add> LC_LOAD_DYLINKER
<ide> ].freeze
<ide>
<ide> # association of load command symbols to string representations of classes
<ide> module LoadCommands
<ide> :LC_LINKER_OPTIMIZATION_HINT => "LinkeditDataCommand",
<ide> :LC_VERSION_MIN_TVOS => "VersionMinCommand",
<ide> :LC_VERSION_MIN_WATCHOS => "VersionMinCommand",
<add> :LC_NOTE => "LoadCommand",
<add> :LC_BUILD_VERSION => "BuildVersionCommand",
<ide> }.freeze
<ide>
<ide> # association of segment name symbols to names
<ide> class LoadCommand < MachOStructure
<ide> # @return [MachO::MachOView] the raw view associated with the load command
<ide> attr_reader :view
<ide>
<del> # @return [Fixnum] the load command's identifying number
<add> # @return [Integer] the load command's identifying number
<ide> attr_reader :cmd
<ide>
<del> # @return [Fixnum] the size of the load command, in bytes
<add> # @return [Integer] the size of the load command, in bytes
<ide> attr_reader :cmdsize
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def self.create(cmd_sym, *args)
<ide> end
<ide>
<ide> # @param view [MachO::MachOView] the load command's raw view
<del> # @param cmd [Fixnum] the load command's identifying number
<del> # @param cmdsize [Fixnum] the size of the load command in bytes
<add> # @param cmd [Integer] the load command's identifying number
<add> # @param cmdsize [Integer] the size of the load command in bytes
<ide> # @api private
<ide> def initialize(view, cmd, cmdsize)
<ide> @view = view
<ide> def serialize(context)
<ide> [cmd, SIZEOF].pack(format)
<ide> end
<ide>
<del> # @return [Fixnum] the load command's offset in the source file
<add> # @return [Integer] the load command's offset in the source file
<ide> # @deprecated use {#view} instead
<ide> def offset
<ide> view.offset
<ide> def to_s
<ide> # explicit operations on the raw Mach-O data.
<ide> class LCStr
<ide> # @param lc [LoadCommand] the load command
<del> # @param lc_str [Fixnum, String] the offset to the beginning of the
<add> # @param lc_str [Integer, String] the offset to the beginning of the
<ide> # string, or the string itself if not being initialized with a view.
<ide> # @raise [MachO::LCStrMalformedError] if the string is malformed
<ide> # @todo devise a solution such that the `lc_str` parameter is not
<ide> def to_s
<ide> @string
<ide> end
<ide>
<del> # @return [Fixnum] the offset to the beginning of the string in the
<add> # @return [Integer] the offset to the beginning of the string in the
<ide> # load command
<ide> def to_i
<ide> @string_offset
<ide> class SerializationContext
<ide> # @return [Symbol] the endianness of the serialized load command
<ide> attr_reader :endianness
<ide>
<del> # @return [Fixnum] the constant alignment value used to pad the
<add> # @return [Integer] the constant alignment value used to pad the
<ide> # serialized load command
<ide> attr_reader :alignment
<ide>
<ide> def self.context_for(macho)
<ide> end
<ide>
<ide> # @param endianness [Symbol] the endianness of the context
<del> # @param alignment [Fixnum] the alignment of the context
<add> # @param alignment [Integer] the alignment of the context
<ide> # @api private
<ide> def initialize(endianness, alignment)
<ide> @endianness = endianness
<ide> def initialize(endianness, alignment)
<ide> # identifying an object produced by static link editor. Corresponds to
<ide> # LC_UUID.
<ide> class UUIDCommand < LoadCommand
<del> # @return [Array<Fixnum>] the UUID
<add> # @return [Array<Integer>] the UUID
<ide> attr_reader :uuid
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class SegmentCommand < LoadCommand
<ide> # @return [String] the name of the segment
<ide> attr_reader :segname
<ide>
<del> # @return [Fixnum] the memory address of the segment
<add> # @return [Integer] the memory address of the segment
<ide> attr_reader :vmaddr
<ide>
<del> # @return [Fixnum] the memory size of the segment
<add> # @return [Integer] the memory size of the segment
<ide> attr_reader :vmsize
<ide>
<del> # @return [Fixnum] the file offset of the segment
<add> # @return [Integer] the file offset of the segment
<ide> attr_reader :fileoff
<ide>
<del> # @return [Fixnum] the amount to map from the file
<add> # @return [Integer] the amount to map from the file
<ide> attr_reader :filesize
<ide>
<del> # @return [Fixnum] the maximum VM protection
<add> # @return [Integer] the maximum VM protection
<ide> attr_reader :maxprot
<ide>
<del> # @return [Fixnum] the initial VM protection
<add> # @return [Integer] the initial VM protection
<ide> attr_reader :initprot
<ide>
<del> # @return [Fixnum] the number of sections in the segment
<add> # @return [Integer] the number of sections in the segment
<ide> attr_reader :nsects
<ide>
<del> # @return [Fixnum] any flags associated with the segment
<add> # @return [Integer] any flags associated with the segment
<ide> attr_reader :flags
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class DylibCommand < LoadCommand
<ide> # name as an LCStr
<ide> attr_reader :name
<ide>
<del> # @return [Fixnum] the library's build time stamp
<add> # @return [Integer] the library's build time stamp
<ide> attr_reader :timestamp
<ide>
<del> # @return [Fixnum] the library's current version number
<add> # @return [Integer] the library's current version number
<ide> attr_reader :current_version
<ide>
<del> # @return [Fixnum] the library's compatibility version number
<add> # @return [Integer] the library's compatibility version number
<ide> attr_reader :compatibility_version
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class PreboundDylibCommand < LoadCommand
<ide> # name as an LCStr
<ide> attr_reader :name
<ide>
<del> # @return [Fixnum] the number of modules in the library
<add> # @return [Integer] the number of modules in the library
<ide> attr_reader :nmodules
<ide>
<del> # @return [Fixnum] a bit vector of linked modules
<add> # @return [Integer] a bit vector of linked modules
<ide> attr_reader :linked_modules
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class ThreadCommand < LoadCommand
<ide> # initialization routine and an index into the module table for the module
<ide> # that defines the routine. Corresponds to LC_ROUTINES.
<ide> class RoutinesCommand < LoadCommand
<del> # @return [Fixnum] the address of the initialization routine
<add> # @return [Integer] the address of the initialization routine
<ide> attr_reader :init_address
<ide>
<del> # @return [Fixnum] the index into the module table that the init routine
<add> # @return [Integer] the index into the module table that the init routine
<ide> # is defined in
<ide> attr_reader :init_module
<ide>
<ide> def initialize(view, cmd, cmdsize, sub_client)
<ide> # A load command containing the offsets and sizes of the link-edit 4.3BSD
<ide> # "stab" style symbol table information. Corresponds to LC_SYMTAB.
<ide> class SymtabCommand < LoadCommand
<del> # @return [Fixnum] the symbol table's offset
<add> # @return [Integer] the symbol table's offset
<ide> attr_reader :symoff
<ide>
<del> # @return [Fixnum] the number of symbol table entries
<add> # @return [Integer] the number of symbol table entries
<ide> attr_reader :nsyms
<ide>
<ide> # @return the string table's offset
<ide> def initialize(view, cmd, cmdsize, symoff, nsyms, stroff, strsize)
<ide> # A load command containing symbolic information needed to support data
<ide> # structures used by the dynamic link editor. Corresponds to LC_DYSYMTAB.
<ide> class DysymtabCommand < LoadCommand
<del> # @return [Fixnum] the index to local symbols
<add> # @return [Integer] the index to local symbols
<ide> attr_reader :ilocalsym
<ide>
<del> # @return [Fixnum] the number of local symbols
<add> # @return [Integer] the number of local symbols
<ide> attr_reader :nlocalsym
<ide>
<del> # @return [Fixnum] the index to externally defined symbols
<add> # @return [Integer] the index to externally defined symbols
<ide> attr_reader :iextdefsym
<ide>
<del> # @return [Fixnum] the number of externally defined symbols
<add> # @return [Integer] the number of externally defined symbols
<ide> attr_reader :nextdefsym
<ide>
<del> # @return [Fixnum] the index to undefined symbols
<add> # @return [Integer] the index to undefined symbols
<ide> attr_reader :iundefsym
<ide>
<del> # @return [Fixnum] the number of undefined symbols
<add> # @return [Integer] the number of undefined symbols
<ide> attr_reader :nundefsym
<ide>
<del> # @return [Fixnum] the file offset to the table of contents
<add> # @return [Integer] the file offset to the table of contents
<ide> attr_reader :tocoff
<ide>
<del> # @return [Fixnum] the number of entries in the table of contents
<add> # @return [Integer] the number of entries in the table of contents
<ide> attr_reader :ntoc
<ide>
<del> # @return [Fixnum] the file offset to the module table
<add> # @return [Integer] the file offset to the module table
<ide> attr_reader :modtaboff
<ide>
<del> # @return [Fixnum] the number of entries in the module table
<add> # @return [Integer] the number of entries in the module table
<ide> attr_reader :nmodtab
<ide>
<del> # @return [Fixnum] the file offset to the referenced symbol table
<add> # @return [Integer] the file offset to the referenced symbol table
<ide> attr_reader :extrefsymoff
<ide>
<del> # @return [Fixnum] the number of entries in the referenced symbol table
<add> # @return [Integer] the number of entries in the referenced symbol table
<ide> attr_reader :nextrefsyms
<ide>
<del> # @return [Fixnum] the file offset to the indirect symbol table
<add> # @return [Integer] the file offset to the indirect symbol table
<ide> attr_reader :indirectsymoff
<ide>
<del> # @return [Fixnum] the number of entries in the indirect symbol table
<add> # @return [Integer] the number of entries in the indirect symbol table
<ide> attr_reader :nindirectsyms
<ide>
<del> # @return [Fixnum] the file offset to the external relocation entries
<add> # @return [Integer] the file offset to the external relocation entries
<ide> attr_reader :extreloff
<ide>
<del> # @return [Fixnum] the number of external relocation entries
<add> # @return [Integer] the number of external relocation entries
<ide> attr_reader :nextrel
<ide>
<del> # @return [Fixnum] the file offset to the local relocation entries
<add> # @return [Integer] the file offset to the local relocation entries
<ide> attr_reader :locreloff
<ide>
<del> # @return [Fixnum] the number of local relocation entries
<add> # @return [Integer] the number of local relocation entries
<ide> attr_reader :nlocrel
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, ilocalsym, nlocalsym, iextdefsym,
<ide> # A load command containing the offset and number of hints in the two-level
<ide> # namespace lookup hints table. Corresponds to LC_TWOLEVEL_HINTS.
<ide> class TwolevelHintsCommand < LoadCommand
<del> # @return [Fixnum] the offset to the hint table
<add> # @return [Integer] the offset to the hint table
<ide> attr_reader :htoffset
<ide>
<del> # @return [Fixnum] the number of hints in the hint table
<add> # @return [Integer] the number of hints in the hint table
<ide> attr_reader :nhints
<ide>
<ide> # @return [TwolevelHintsTable]
<ide> class TwolevelHintsTable
<ide> attr_reader :hints
<ide>
<ide> # @param view [MachO::MachOView] the view into the current Mach-O
<del> # @param htoffset [Fixnum] the offset of the hints table
<del> # @param nhints [Fixnum] the number of two-level hints in the table
<add> # @param htoffset [Integer] the offset of the hints table
<add> # @param nhints [Integer] the number of two-level hints in the table
<ide> # @api private
<ide> def initialize(view, htoffset, nhints)
<ide> format = Utils.specialize_format("L=#{nhints}", view.endianness)
<ide> def initialize(view, htoffset, nhints)
<ide>
<ide> # An individual two-level namespace lookup hint.
<ide> class TwolevelHint
<del> # @return [Fixnum] the index into the sub-images
<add> # @return [Integer] the index into the sub-images
<ide> attr_reader :isub_image
<ide>
<del> # @return [Fixnum] the index into the table of contents
<add> # @return [Integer] the index into the table of contents
<ide> attr_reader :itoc
<ide>
<del> # @param blob [Fixnum] the 32-bit number containing the lookup hint
<add> # @param blob [Integer] the 32-bit number containing the lookup hint
<ide> # @api private
<ide> def initialize(blob)
<ide> @isub_image = blob >> 24
<ide> def initialize(blob)
<ide> # A load command containing the value of the original checksum for prebound
<ide> # files, or zero. Corresponds to LC_PREBIND_CKSUM.
<ide> class PrebindCksumCommand < LoadCommand
<del> # @return [Fixnum] the checksum or 0
<add> # @return [Integer] the checksum or 0
<ide> attr_reader :cksum
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def serialize(context)
<ide> # LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE,
<ide> # LC_DYLIB_CODE_SIGN_DRS, and LC_LINKER_OPTIMIZATION_HINT.
<ide> class LinkeditDataCommand < LoadCommand
<del> # @return [Fixnum] offset to the data in the __LINKEDIT segment
<add> # @return [Integer] offset to the data in the __LINKEDIT segment
<ide> attr_reader :dataoff
<ide>
<del> # @return [Fixnum] size of the data in the __LINKEDIT segment
<add> # @return [Integer] size of the data in the __LINKEDIT segment
<ide> attr_reader :datasize
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, dataoff, datasize)
<ide> # A load command representing the offset to and size of an encrypted
<ide> # segment. Corresponds to LC_ENCRYPTION_INFO.
<ide> class EncryptionInfoCommand < LoadCommand
<del> # @return [Fixnum] the offset to the encrypted segment
<add> # @return [Integer] the offset to the encrypted segment
<ide> attr_reader :cryptoff
<ide>
<del> # @return [Fixnum] the size of the encrypted segment
<add> # @return [Integer] the size of the encrypted segment
<ide> attr_reader :cryptsize
<ide>
<del> # @return [Fixnum] the encryption system, or 0 if not encrypted yet
<add> # @return [Integer] the encryption system, or 0 if not encrypted yet
<ide> attr_reader :cryptid
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, cryptoff, cryptsize, cryptid)
<ide> # A load command representing the offset to and size of an encrypted
<ide> # segment. Corresponds to LC_ENCRYPTION_INFO_64.
<ide> class EncryptionInfoCommand64 < LoadCommand
<del> # @return [Fixnum] the offset to the encrypted segment
<add> # @return [Integer] the offset to the encrypted segment
<ide> attr_reader :cryptoff
<ide>
<del> # @return [Fixnum] the size of the encrypted segment
<add> # @return [Integer] the size of the encrypted segment
<ide> attr_reader :cryptsize
<ide>
<del> # @return [Fixnum] the encryption system, or 0 if not encrypted yet
<add> # @return [Integer] the encryption system, or 0 if not encrypted yet
<ide> attr_reader :cryptid
<ide>
<del> # @return [Fixnum] 64-bit padding value
<add> # @return [Integer] 64-bit padding value
<ide> attr_reader :pad
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, cryptoff, cryptsize, cryptid, pad)
<ide> # was built to run. Corresponds to LC_VERSION_MIN_MACOSX and
<ide> # LC_VERSION_MIN_IPHONEOS.
<ide> class VersionMinCommand < LoadCommand
<del> # @return [Fixnum] the version X.Y.Z packed as x16.y8.z8
<add> # @return [Integer] the version X.Y.Z packed as x16.y8.z8
<ide> attr_reader :version
<ide>
<del> # @return [Fixnum] the SDK version X.Y.Z packed as x16.y8.z8
<add> # @return [Integer] the SDK version X.Y.Z packed as x16.y8.z8
<ide> attr_reader :sdk
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def sdk_string
<ide> end
<ide> end
<ide>
<add> # A load command containing the minimum OS version on which
<add> # the binary was built for its platform.
<add> # Corresponds to LC_BUILD_VERSION.
<add> class BuildVersionCommand < LoadCommand
<add> # @return [Integer]
<add> attr_reader :platform
<add>
<add> # @return [Integer] the minimum OS version X.Y.Z packed as x16.y8.z8
<add> attr_reader :minos
<add>
<add> # @return [Integer] the SDK version X.Y.Z packed as x16.y8.z8
<add> attr_reader :sdk
<add>
<add> # @return [ToolEntries] tool entries
<add> attr_reader :tool_entries
<add>
<add> # @see MachOStructure::FORMAT
<add> # @api private
<add> FORMAT = "L=6".freeze
<add>
<add> # @see MachOStructure::SIZEOF
<add> # @api private
<add> SIZEOF = 24
<add>
<add> # @api private
<add> def initialize(view, cmd, cmdsize, platform, minos, sdk, ntools)
<add> super(view, cmd, cmdsize)
<add> @platform = platform
<add> @minos = minos
<add> @sdk = sdk
<add> @tool_entries = ToolEntries.new(view, ntools)
<add> end
<add>
<add> # A representation of the tool versions exposed
<add> # by a {BuildVersionCommand} (`LC_BUILD_VERSION`).
<add> class ToolEntries
<add> # @return [Array<Tool>] all tools
<add> attr_reader :tools
<add>
<add> # @param view [MachO::MachOView] the view into the current Mach-O
<add> # @param ntools [Integer] the number of tools
<add> # @api private
<add> def initialize(view, ntools)
<add> format = Utils.specialize_format("L=#{ntools * 2}", view.endianness)
<add> raw_table = view.raw_data[view.offset + 24, ntools * 8]
<add> blobs = raw_table.unpack(format).each_slice(2).to_a
<add>
<add> @tools = blobs.map { |b| Tool.new(*b) }
<add> end
<add>
<add> # An individual tool.
<add> class Tool
<add> # @return [Integer] the enum for the tool
<add> attr_reader :tool
<add>
<add> # @return [Integer] the tool's version number
<add> attr_reader :version
<add>
<add> # @param tool 32-bit integer
<add> # # @param version 32-bit integer
<add> # @api private
<add> def initialize(tool, version)
<add> @tool = tool
<add> @version = version
<add> end
<add> end
<add> end
<add>
<add> # A string representation of the binary's minimum OS version.
<add> # @return [String] a string representing the minimum OS version.
<add> def minos_string
<add> binary = "%032b" % minos
<add> segs = [
<add> binary[0..15], binary[16..23], binary[24..31]
<add> ].map { |s| s.to_i(2) }
<add>
<add> segs.join(".")
<add> end
<add>
<add> # A string representation of the binary's SDK version.
<add> # @return [String] a string representing the SDK version.
<add> def sdk_string
<add> binary = "%032b" % sdk
<add> segs = [
<add> binary[0..15], binary[16..23], binary[24..31]
<add> ].map { |s| s.to_i(2) }
<add>
<add> segs.join(".")
<add> end
<add> end
<add>
<ide> # A load command containing the file offsets and sizes of the new
<ide> # compressed form of the information dyld needs to load the image.
<ide> # Corresponds to LC_DYLD_INFO and LC_DYLD_INFO_ONLY.
<ide> class DyldInfoCommand < LoadCommand
<del> # @return [Fixnum] the file offset to the rebase information
<add> # @return [Integer] the file offset to the rebase information
<ide> attr_reader :rebase_off
<ide>
<del> # @return [Fixnum] the size of the rebase information
<add> # @return [Integer] the size of the rebase information
<ide> attr_reader :rebase_size
<ide>
<del> # @return [Fixnum] the file offset to the binding information
<add> # @return [Integer] the file offset to the binding information
<ide> attr_reader :bind_off
<ide>
<del> # @return [Fixnum] the size of the binding information
<add> # @return [Integer] the size of the binding information
<ide> attr_reader :bind_size
<ide>
<del> # @return [Fixnum] the file offset to the weak binding information
<add> # @return [Integer] the file offset to the weak binding information
<ide> attr_reader :weak_bind_off
<ide>
<del> # @return [Fixnum] the size of the weak binding information
<add> # @return [Integer] the size of the weak binding information
<ide> attr_reader :weak_bind_size
<ide>
<del> # @return [Fixnum] the file offset to the lazy binding information
<add> # @return [Integer] the file offset to the lazy binding information
<ide> attr_reader :lazy_bind_off
<ide>
<del> # @return [Fixnum] the size of the lazy binding information
<add> # @return [Integer] the size of the lazy binding information
<ide> attr_reader :lazy_bind_size
<ide>
<del> # @return [Fixnum] the file offset to the export information
<add> # @return [Integer] the file offset to the export information
<ide> attr_reader :export_off
<ide>
<del> # @return [Fixnum] the size of the export information
<add> # @return [Integer] the size of the export information
<ide> attr_reader :export_size
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, rebase_off, rebase_size, bind_off,
<ide> # A load command containing linker options embedded in object files.
<ide> # Corresponds to LC_LINKER_OPTION.
<ide> class LinkerOptionCommand < LoadCommand
<del> # @return [Fixnum] the number of strings
<add> # @return [Integer] the number of strings
<ide> attr_reader :count
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, count)
<ide>
<ide> # A load command specifying the offset of main(). Corresponds to LC_MAIN.
<ide> class EntryPointCommand < LoadCommand
<del> # @return [Fixnum] the file (__TEXT) offset of main()
<add> # @return [Integer] the file (__TEXT) offset of main()
<ide> attr_reader :entryoff
<ide>
<del> # @return [Fixnum] if not 0, the initial stack size.
<add> # @return [Integer] if not 0, the initial stack size.
<ide> attr_reader :stacksize
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def initialize(view, cmd, cmdsize, entryoff, stacksize)
<ide> # A load command specifying the version of the sources used to build the
<ide> # binary. Corresponds to LC_SOURCE_VERSION.
<ide> class SourceVersionCommand < LoadCommand
<del> # @return [Fixnum] the version packed as a24.b10.c10.d10.e10
<add> # @return [Integer] the version packed as a24.b10.c10.d10.e10
<ide> attr_reader :version
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> def version_string
<ide> # An obsolete load command containing the offset and size of the (GNU style)
<ide> # symbol table information. Corresponds to LC_SYMSEG.
<ide> class SymsegCommand < LoadCommand
<del> # @return [Fixnum] the offset to the symbol segment
<add> # @return [Integer] the offset to the symbol segment
<ide> attr_reader :offset
<ide>
<del> # @return [Fixnum] the size of the symbol segment in bytes
<add> # @return [Integer] the size of the symbol segment in bytes
<ide> attr_reader :size
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class FvmfileCommand < LoadCommand
<ide> # @return [LCStr] the pathname of the file being loaded
<ide> attr_reader :name
<ide>
<del> # @return [Fixnum] the virtual address being loaded at
<add> # @return [Integer] the virtual address being loaded at
<ide> attr_reader :header_addr
<ide>
<ide> # @see MachOStructure::FORMAT
<ide> class FvmlibCommand < LoadCommand
<ide> # @return [LCStr] the library's target pathname
<ide> attr_reader :name
<ide>
<del> # @return [Fixnum] the library's minor version number
<add> # @return [Integer] the library's minor version number
<ide> attr_reader :minor_version
<ide>
<del> # @return [Fixnum] the library's header address
<add> # @return [Integer] the library's header address
<ide> attr_reader :header_addr
<ide>
<ide> # @see MachOStructure::FORMAT
<ide><path>Library/Homebrew/vendor/macho/macho/macho_file.rb
<ide> def command(name)
<ide> alias [] command
<ide>
<ide> # Inserts a load command at the given offset.
<del> # @param offset [Fixnum] the offset to insert at
<add> # @param offset [Integer] the offset to insert at
<ide> # @param lc [LoadCommands::LoadCommand] the load command to insert
<ide> # @param options [Hash]
<ide> # @option options [Boolean] :repopulate (true) whether or not to repopulate
<ide> def write(filename)
<ide> # @raise [MachOError] if the instance was initialized without a file
<ide> # @note Overwrites all data in the file!
<ide> def write!
<del> if @filename.nil?
<del> raise MachOError, "cannot write to a default file when initialized from a binary string"
<del> else
<del> File.open(@filename, "wb") { |f| f.write(@raw_data) }
<del> end
<add> raise MachOError, "no initial file to write to" if @filename.nil?
<add> File.open(@filename, "wb") { |f| f.write(@raw_data) }
<ide> end
<ide>
<ide> private
<ide> def populate_mach_header
<ide> end
<ide>
<ide> # Read just the file's magic number and check its validity.
<del> # @return [Fixnum] the magic
<add> # @return [Integer] the magic
<ide> # @raise [MagicError] if the magic is not valid Mach-O magic
<ide> # @raise [FatBinaryError] if the magic is for a Fat file
<ide> # @api private
<ide> def populate_and_check_magic
<ide> end
<ide>
<ide> # Check the file's CPU type.
<del> # @param cputype [Fixnum] the CPU type
<add> # @param cputype [Integer] the CPU type
<ide> # @raise [CPUTypeError] if the CPU type is unknown
<ide> # @api private
<ide> def check_cputype(cputype)
<ide> raise CPUTypeError, cputype unless Headers::CPU_TYPES.key?(cputype)
<ide> end
<ide>
<ide> # Check the file's CPU type/subtype pair.
<del> # @param cpusubtype [Fixnum] the CPU subtype
<add> # @param cpusubtype [Integer] the CPU subtype
<ide> # @raise [CPUSubtypeError] if the CPU sub-type is unknown
<ide> # @api private
<ide> def check_cpusubtype(cputype, cpusubtype)
<ide> def check_cpusubtype(cputype, cpusubtype)
<ide> end
<ide>
<ide> # Check the file's type.
<del> # @param filetype [Fixnum] the file type
<add> # @param filetype [Integer] the file type
<ide> # @raise [FiletypeError] if the file type is unknown
<ide> # @api private
<ide> def check_filetype(filetype)
<ide> def populate_load_commands
<ide> end
<ide>
<ide> # The low file offset (offset to first section data).
<del> # @return [Fixnum] the offset
<add> # @return [Integer] the offset
<ide> # @api private
<ide> def low_fileoff
<ide> offset = @raw_data.size
<ide> def low_fileoff
<ide> end
<ide>
<ide> # Updates the number of load commands in the raw data.
<del> # @param ncmds [Fixnum] the new number of commands
<add> # @param ncmds [Integer] the new number of commands
<ide> # @return [void]
<ide> # @api private
<ide> def update_ncmds(ncmds)
<ide> def update_ncmds(ncmds)
<ide> end
<ide>
<ide> # Updates the size of all load commands in the raw data.
<del> # @param size [Fixnum] the new size, in bytes
<add> # @param size [Integer] the new size, in bytes
<ide> # @return [void]
<ide> # @api private
<ide> def update_sizeofcmds(size)
<ide><path>Library/Homebrew/vendor/macho/macho/sections.rb
<ide> class Section < MachOStructure
<ide> # pad bytes
<ide> attr_reader :segname
<ide>
<del> # @return [Fixnum] the memory address of the section
<add> # @return [Integer] the memory address of the section
<ide> attr_reader :addr
<ide>
<del> # @return [Fixnum] the size, in bytes, of the section
<add> # @return [Integer] the size, in bytes, of the section
<ide> attr_reader :size
<ide>
<del> # @return [Fixnum] the file offset of the section
<add> # @return [Integer] the file offset of the section
<ide> attr_reader :offset
<ide>
<del> # @return [Fixnum] the section alignment (power of 2) of the section
<add> # @return [Integer] the section alignment (power of 2) of the section
<ide> attr_reader :align
<ide>
<del> # @return [Fixnum] the file offset of the section's relocation entries
<add> # @return [Integer] the file offset of the section's relocation entries
<ide> attr_reader :reloff
<ide>
<del> # @return [Fixnum] the number of relocation entries
<add> # @return [Integer] the number of relocation entries
<ide> attr_reader :nreloc
<ide>
<del> # @return [Fixnum] flags for type and attributes of the section
<add> # @return [Integer] flags for type and attributes of the section
<ide> attr_reader :flags
<ide>
<ide> # @return [void] reserved (for offset or index)
<ide><path>Library/Homebrew/vendor/macho/macho/structure.rb
<ide> class MachOStructure
<ide> FORMAT = "".freeze
<ide>
<ide> # The size of the data structure, in bytes.
<del> # @return [Fixnum] the size, in bytes
<add> # @return [Integer] the size, in bytes
<ide> # @api private
<ide> SIZEOF = 0
<ide>
<del> # @return [Fixnum] the size, in bytes, of the represented structure.
<add> # @return [Integer] the size, in bytes, of the represented structure.
<ide> def self.bytesize
<ide> self::SIZEOF
<ide> end
<ide><path>Library/Homebrew/vendor/macho/macho/tools.rb
<ide> def self.delete_rpath(filename, old_path, options = {})
<ide>
<ide> # Merge multiple Mach-Os into one universal (Fat) binary.
<ide> # @param filename [String] the fat binary to create
<del> # @param files [Array<MachO::MachOFile, MachO::FatFile>] the files to merge
<add> # @param files [Array<String>] the files to merge
<ide> # @return [void]
<ide> def self.merge_machos(filename, *files)
<ide> machos = files.map do |file|
<ide><path>Library/Homebrew/vendor/macho/macho/utils.rb
<ide> module MachO
<ide> # A collection of utility functions used throughout ruby-macho.
<ide> module Utils
<ide> # Rounds a value to the next multiple of the given round.
<del> # @param value [Fixnum] the number being rounded
<del> # @param round [Fixnum] the number being rounded with
<del> # @return [Fixnum] the rounded value
<add> # @param value [Integer] the number being rounded
<add> # @param round [Integer] the number being rounded with
<add> # @return [Integer] the rounded value
<ide> # @see http://www.opensource.apple.com/source/cctools/cctools-870/libstuff/rnd.c
<ide> def self.round(value, round)
<ide> round -= 1
<ide> def self.round(value, round)
<ide>
<ide> # Returns the number of bytes needed to pad the given size to the given
<ide> # alignment.
<del> # @param size [Fixnum] the unpadded size
<del> # @param alignment [Fixnum] the number to alignment the size with
<del> # @return [Fixnum] the number of pad bytes required
<add> # @param size [Integer] the unpadded size
<add> # @param alignment [Integer] the number to alignment the size with
<add> # @return [Integer] the number of pad bytes required
<ide> def self.padding_for(size, alignment)
<ide> round(size, alignment) - size
<ide> end
<ide> def self.specialize_format(format, endianness)
<ide> end
<ide>
<ide> # Packs tagged strings into an aligned payload.
<del> # @param fixed_offset [Fixnum] the baseline offset for the first packed
<add> # @param fixed_offset [Integer] the baseline offset for the first packed
<ide> # string
<del> # @param alignment [Fixnum] the alignment value to use for packing
<add> # @param alignment [Integer] the alignment value to use for packing
<ide> # @param strings [Hash] the labeled strings to pack
<ide> # @return [Array<String, Hash>] the packed string and labeled offsets
<ide> def self.pack_strings(fixed_offset, alignment, strings = {})
<ide> def self.pack_strings(fixed_offset, alignment, strings = {})
<ide> end
<ide>
<ide> # Compares the given number to valid Mach-O magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid Mach-O magic number
<ide> def self.magic?(num)
<ide> Headers::MH_MAGICS.key?(num)
<ide> end
<ide>
<ide> # Compares the given number to valid Fat magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid Fat magic number
<ide> def self.fat_magic?(num)
<ide> num == Headers::FAT_MAGIC
<ide> end
<ide>
<ide> # Compares the given number to valid 32-bit Mach-O magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid 32-bit magic number
<ide> def self.magic32?(num)
<ide> num == Headers::MH_MAGIC || num == Headers::MH_CIGAM
<ide> end
<ide>
<ide> # Compares the given number to valid 64-bit Mach-O magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid 64-bit magic number
<ide> def self.magic64?(num)
<ide> num == Headers::MH_MAGIC_64 || num == Headers::MH_CIGAM_64
<ide> end
<ide>
<ide> # Compares the given number to valid little-endian magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid little-endian magic number
<ide> def self.little_magic?(num)
<ide> num == Headers::MH_CIGAM || num == Headers::MH_CIGAM_64
<ide> end
<ide>
<ide> # Compares the given number to valid big-endian magic numbers.
<del> # @param num [Fixnum] the number being checked
<add> # @param num [Integer] the number being checked
<ide> # @return [Boolean] whether `num` is a valid big-endian magic number
<ide> def self.big_magic?(num)
<ide> num == Headers::MH_CIGAM || num == Headers::MH_CIGAM_64
<ide><path>Library/Homebrew/vendor/macho/macho/view.rb
<ide> class MachOView
<ide> # @return [Symbol] the endianness of the data (`:big` or `:little`)
<ide> attr_reader :endianness
<ide>
<del> # @return [Fixnum] the offset of the relevant data (in {#raw_data})
<add> # @return [Integer] the offset of the relevant data (in {#raw_data})
<ide> attr_reader :offset
<ide>
<ide> # Creates a new MachOView.
<ide> # @param raw_data [String] the raw Mach-O data
<ide> # @param endianness [Symbol] the endianness of the data
<del> # @param offset [Fixnum] the offset of the relevant data
<add> # @param offset [Integer] the offset of the relevant data
<ide> def initialize(raw_data, endianness, offset)
<ide> @raw_data = raw_data
<ide> @endianness = endianness | 11 |
Javascript | Javascript | fix ie8 bug | c027289e38dc2d5dfe69920ec91a09e7fc02471c | <ide><path>moment.js
<ide> ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/],
<ide> ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/],
<ide> ['GGGG-[W]WW', /\d{4}-W\d{2}/],
<del> ['YYYY-DDD', /\d{4}-\d{3}/],
<add> ['YYYY-DDD', /\d{4}-\d{3}/]
<ide> ],
<ide>
<ide> // iso time formats and regexes
<ide> // left zero fill a number
<ide> // see http://jsperf.com/left-zero-filling for performance comparison
<ide> function leftZeroFill(number, targetLength, forceSign) {
<del> var output = Math.abs(number) + '',
<add> var output = '' + Math.abs(number),
<ide> sign = number >= 0;
<ide>
<ide> while (output.length < targetLength) {
<ide>
<ide> //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
<ide> function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
<del> // The only solid way to create an iso date from year is to use
<del> // a string format (Date.UTC handles only years > 1900). Don't ask why
<del> // it doesn't need Z at the end.
<del> var d = new Date(leftZeroFill(year, 6, true) + '-01-01').getUTCDay(),
<del> daysToAdd, dayOfYear;
<add> var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear;
<ide>
<ide> weekday = weekday != null ? weekday : firstDayOfWeek;
<ide> daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0);
<ide><path>test/moment/is_valid.js
<ide> exports.is_valid = {
<ide> test.ok(moment("3:25", ["h:mma", "hh:mma", "H:mm", "HH:mm"]).isValid());
<ide>
<ide> test.done();
<del> },
<add> }
<ide> }; | 2 |
Javascript | Javascript | execute render after $digest cycle | 6f7018d52fa4f9f9c7fa8e3035317d1239efb20f | <ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> optionsExp = attr.ngOptions,
<ide> nullOption = false, // if false, user will not be able to select it (used by ngOptions)
<ide> emptyOption,
<add> renderScheduled = false,
<ide> // we can't just jqLite('<option>') since jqLite is not smart enough
<ide> // to create it in <select> and IE barfs otherwise.
<ide> optionTemplate = jqLite(document.createElement('option')),
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> ctrl.$render = render;
<ide>
<del> scope.$watchCollection(valuesFn, render);
<add> scope.$watchCollection(valuesFn, function () {
<add> if (!renderScheduled) {
<add> scope.$$postDigest(render);
<add> renderScheduled = true;
<add> }
<add> });
<ide> if ( multiple ) {
<del> scope.$watchCollection(function() { return ctrl.$modelValue; }, render);
<add> scope.$watchCollection(function() { return ctrl.$modelValue; }, function () {
<add> if (!renderScheduled) {
<add> scope.$$postDigest(render);
<add> renderScheduled = true;
<add> }
<add> });
<ide> }
<ide>
<ide> function getSelectedSet() {
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide>
<ide> function render() {
<add> renderScheduled = false;
<add>
<ide> // Temporary location for the option groups before we render them
<ide> var optionGroups = {'':[]},
<ide> optionGroupNames = [''], | 1 |
Text | Text | add badges to the top of readme.md | 46bcee0978fe507891a8e3b8892437fafed28c08 | <ide><path>README.md
<ide> # The Algorithms - Python <!-- [](https://travis-ci.org/TheAlgorithms/Python) -->
<del>
<del>[](https://www.paypal.me/TheAlgorithms/100)
<del>[](https://gitter.im/TheAlgorithms)
<del>[](https://gitpod.io/#https://github.com/TheAlgorithms/Python)
<del>
<add>[](https://www.paypal.me/TheAlgorithms/100)
<add>[](https://travis-ci.org/TheAlgorithms/Python)
<add>[](https://lgtm.com/projects/g/TheAlgorithms/Python/alerts)
<add>[](https://gitter.im/TheAlgorithms)
<add>[](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md)
<add>
<add><!--[]( https://www.python.org/downloads) -->
<ide> ### All algorithms implemented in Python (for education)
<ide>
<ide> These implementations are for learning purposes. They may be less efficient than the implementations in the Python standard library.
<ide> Chetan Kaushik
<ide>
<ide> Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
<ide>
<add>[](https://gitpod.io/#https://github.com/TheAlgorithms/Python)
<add>
<ide> ## Community Channel
<ide>
<ide> We're on [Gitter](https://gitter.im/TheAlgorithms)! Please join us. | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.