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 |
|---|---|---|---|---|---|
Python | Python | simplify serializer.fields with @cached_property | 7232586c7caf66f20f56b36f1c6a9c9648eb94a4 | <ide><path>rest_framework/serializers.py
<ide> class Serializer(BaseSerializer, metaclass=SerializerMetaclass):
<ide> 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.')
<ide> }
<ide>
<del> @property
<add> @cached_property
<ide> def fields(self):
<ide> """
<ide> A dictionary of {field_name: field_instance}.
<ide> """
<ide> # `fields` is evaluated lazily. We do this to ensure that we don't
<ide> # have issues importing modules that use ModelSerializers as fields,
<ide> # even if Django's app-loading stage has not yet run.
<del> if not hasattr(self, '_fields'):
<del> self._fields = BindingDict(self)
<del> for key, value in self.get_fields().items():
<del> self._fields[key] = value
<del> return self._fields
<add> fields = BindingDict(self)
<add> for key, value in self.get_fields().items():
<add> fields[key] = value
<add> return fields
<ide>
<ide> @cached_property
<ide> def _writable_fields(self): | 1 |
Javascript | Javascript | log a warning when serialization fails | 00065741d256f487e7e51a3882386da8f2ede5e3 | <ide><path>lib/cache/FileCachePlugin.js
<ide> const path = require("path");
<ide> const createHash = require("../util/createHash");
<ide> const makeSerializable = require("../util/makeSerializable");
<del>const { serializer } = require("../util/serialization");
<add>const { serializer, NOT_SERIALIZABLE } = require("../util/serialization");
<ide>
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("../../declarations/WebpackOptions").FileCacheOptions} FileCacheOptions */
<ide> class Pack {
<ide> this.unserializable = new Set();
<ide> this.used = new Set();
<ide> this.invalid = false;
<add> this.log = 0;
<ide> }
<ide>
<ide> get(identifier) {
<ide> class Pack {
<ide> }
<ide> }
<ide>
<add> setLogLevel(log) {
<add> this.log = log;
<add> }
<add>
<ide> _updateLastAccess() {
<ide> const now = Date.now();
<ide> for (const identifier of this.used) {
<ide> class Pack {
<ide> write(identifier);
<ide> write(data);
<ide> } catch (err) {
<add> if (this.log >= 1 && err !== NOT_SERIALIZABLE) {
<add> console.warn(
<add> `Caching failed for ${identifier}: ${
<add> this.log >= 4 ? err.stack : err
<add> }\nWe will not try to cache this entry again until the cache file is deleted.`
<add> );
<add> }
<ide> rollback(s);
<ide> this.unserializable.add(identifier);
<ide> continue;
<ide> class FileCachePlugin {
<ide> console.warn(`Storing pack...`);
<ide> }
<ide> pack.collectGarbage(1000 * 60 * 60 * 24 * 2);
<add> pack.setLogLevel(log);
<ide> // You might think this breaks all access to the existing pack
<ide> // which are still referenced, but serializing the pack memorizes
<ide> // all data in the pack and makes it no longer need the backing file
<ide><path>lib/serialization/ObjectMiddleware.js
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> }
<ide>
<ide> module.exports = ObjectMiddleware;
<add>module.exports.NOT_SERIALIZABLE = NOT_SERIALIZABLE;
<ide><path>lib/util/serialization.js
<ide> const { register, registerLoader, registerNotSerializable } = ObjectMiddleware;
<ide> exports.register = register;
<ide> exports.registerLoader = registerLoader;
<ide> exports.registerNotSerializable = registerNotSerializable;
<add>exports.NOT_SERIALIZABLE = ObjectMiddleware.NOT_SERIALIZABLE;
<ide> exports.serializer = new Serializer(
<ide> [new ObjectMiddleware(), new BinaryMiddleware(), new FileMiddleware()],
<ide> { | 3 |
Javascript | Javascript | store the rotation in the `pdfhistory` | e135c03123870c3ab4919d6ee74a662b504ea579 | <ide><path>web/app.js
<ide> let PDFViewerApplication = {
<ide>
<ide> if (this.pdfHistory.initialBookmark) {
<ide> this.initialBookmark = this.pdfHistory.initialBookmark;
<add>
<add> this.initialRotation = this.pdfHistory.initialRotation;
<ide> }
<ide> }
<ide>
<ide> let PDFViewerApplication = {
<ide> this.pdfSidebar.setInitialView(sidebarView);
<ide>
<ide> if (this.initialBookmark) {
<add> setRotation(this.initialRotation);
<add> delete this.initialRotation;
<add>
<ide> this.pdfLinkService.setHash(this.initialBookmark);
<ide> this.initialBookmark = null;
<ide> } else if (storedHash) {
<ide><path>web/interfaces.js
<ide> class IPDFLinkService {
<ide> */
<ide> set page(value) {}
<ide>
<add> /**
<add> * @returns {number}
<add> */
<add> get rotation() {}
<add>
<add> /**
<add> * @param {number} value
<add> */
<add> set rotation(value) {}
<add>
<ide> /**
<ide> * @param dest - The PDF destination object.
<ide> */
<ide><path>web/pdf_history.js
<ide> * limitations under the License.
<ide> */
<ide>
<del>import { cloneObj, parseQueryString, waitOnEventOrTimeout } from './ui_utils';
<add>import {
<add> cloneObj, isValidRotation, parseQueryString, waitOnEventOrTimeout
<add>} from './ui_utils';
<ide> import { getGlobalEventBus } from './dom_events';
<ide>
<ide> // Heuristic value used when force-resetting `this._blockHashChange`.
<ide> function parseCurrentHash(linkService) {
<ide> if (!(Number.isInteger(page) && page > 0 && page <= linkService.pagesCount)) {
<ide> page = null;
<ide> }
<del> return { hash, page, };
<add> return { hash, page, rotation: linkService.rotation, };
<ide> }
<ide>
<ide> class PDFHistory {
<ide> class PDFHistory {
<ide>
<ide> this.initialized = false;
<ide> this.initialBookmark = null;
<add> this.initialRotation = null;
<ide>
<ide> this._boundEvents = Object.create(null);
<ide> this._isViewerInPresentationMode = false;
<ide> class PDFHistory {
<ide>
<ide> this.initialized = true;
<ide> this.initialBookmark = null;
<add> this.initialRotation = null;
<ide>
<ide> this._popStateInProgress = false;
<ide> this._blockHashChange = 0;
<ide> class PDFHistory {
<ide> this._position = null;
<ide>
<ide> if (!this._isValidState(state) || resetHistory) {
<del> let { hash, page, } = parseCurrentHash(this.linkService);
<add> let { hash, page, rotation, } = parseCurrentHash(this.linkService);
<ide>
<ide> if (!hash || reInitialized || resetHistory) {
<ide> // Ensure that the browser history is reset on PDF document load.
<ide> class PDFHistory {
<ide> }
<ide> // Ensure that the browser history is initialized correctly when
<ide> // the document hash is present on PDF document load.
<del> this._pushOrReplaceState({ hash, page, }, /* forceReplace = */ true);
<add> this._pushOrReplaceState({ hash, page, rotation, },
<add> /* forceReplace = */ true);
<ide> return;
<ide> }
<ide>
<ide> class PDFHistory {
<ide> let destination = state.destination;
<ide> this._updateInternalState(destination, state.uid,
<ide> /* removeTemporary = */ true);
<add>
<add> if (destination.rotation !== undefined) {
<add> this.initialRotation = destination.rotation;
<add> }
<ide> if (destination.dest) {
<ide> this.initialBookmark = JSON.stringify(destination.dest);
<ide>
<ide> class PDFHistory {
<ide> dest: explicitDest,
<ide> hash,
<ide> page: pageNumber,
<add> rotation: this.linkService.rotation,
<ide> }, forceReplace);
<ide>
<ide> if (!this._popStateInProgress) {
<ide> class PDFHistory {
<ide> `page=${location.pageNumber}` : location.pdfOpenParams.substring(1),
<ide> page: this.linkService.page,
<ide> first: location.pageNumber,
<add> rotation: location.rotation,
<ide> };
<ide>
<ide> if (this._popStateInProgress) {
<ide> class PDFHistory {
<ide> // This case corresponds to the user changing the hash of the document.
<ide> this._currentUid = this._uid;
<ide>
<del> let { hash, page, } = parseCurrentHash(this.linkService);
<del> this._pushOrReplaceState({ hash, page, }, /* forceReplace */ true);
<add> let { hash, page, rotation, } = parseCurrentHash(this.linkService);
<add> this._pushOrReplaceState({ hash, page, rotation, },
<add> /* forceReplace = */ true);
<ide> return;
<ide> }
<ide> if (!this._isValidState(state)) {
<ide> class PDFHistory {
<ide> let destination = state.destination;
<ide> this._updateInternalState(destination, state.uid,
<ide> /* removeTemporary = */ true);
<add>
<add> if (isValidRotation(destination.rotation)) {
<add> this.linkService.rotation = destination.rotation;
<add> }
<ide> if (destination.dest) {
<ide> this.linkService.navigateTo(destination.dest);
<ide> } else if (destination.hash) {
<ide><path>web/pdf_link_service.js
<ide> class PDFLinkService {
<ide> this.pdfViewer.currentPageNumber = value;
<ide> }
<ide>
<add> /**
<add> * @returns {number}
<add> */
<add> get rotation() {
<add> return this.pdfViewer.pagesRotation;
<add> }
<add>
<add> /**
<add> * @param {number} value
<add> */
<add> set rotation(value) {
<add> this.pdfViewer.pagesRotation = value;
<add> }
<add>
<ide> /**
<ide> * @param {string|Array} dest - The named, or explicit, PDF destination.
<ide> */
<ide> class SimpleLinkService {
<ide> * @param {number} value
<ide> */
<ide> set page(value) {}
<add> /**
<add> * @returns {number}
<add> */
<add> get rotation() {
<add> return 0;
<add> }
<add> /**
<add> * @param {number} value
<add> */
<add> set rotation(value) {}
<ide> /**
<ide> * @param dest - The PDF destination object.
<ide> */ | 4 |
Ruby | Ruby | add frameworks helper to formula | 1c12c8b7a22fb9b4dd4b3cff0f3071711e7d6e2d | <ide><path>Library/Homebrew/formula.rb
<ide> def man8; man+'man8' end
<ide> def sbin; prefix+'sbin' end
<ide> def share; prefix+'share' end
<ide>
<add> def frameworks; prefix+'Frameworks' end
<ide> def kext_prefix; prefix+'Library/Extensions' end
<ide>
<ide> # configuration needs to be preserved past upgrades | 1 |
Javascript | Javascript | convert the thumbnail view to es6 syntax | 733a58a31588bb953300bd05bac27325d1766396 | <ide><path>web/pdf_thumbnail_view.js
<ide> import {
<ide> import { getOutputScale, NullL10n } from './ui_utils';
<ide> import { RenderingStates } from './pdf_rendering_queue';
<ide>
<del>var THUMBNAIL_WIDTH = 98; // px
<del>var THUMBNAIL_CANVAS_BORDER_WIDTH = 1; // px
<add>const MAX_NUM_SCALING_STEPS = 3;
<add>const THUMBNAIL_CANVAS_BORDER_WIDTH = 1; // px
<add>const THUMBNAIL_WIDTH = 98; // px
<ide>
<ide> /**
<ide> * @typedef {Object} PDFThumbnailViewOptions
<ide> var THUMBNAIL_CANVAS_BORDER_WIDTH = 1; // px
<ide> * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
<ide> * @property {boolean} disableCanvasToImageConversion - (optional) Don't convert
<ide> * the canvas thumbnails to images. This prevents `toDataURL` calls,
<del> * but increases the overall memory usage. The default value is false.
<add> * but increases the overall memory usage. The default value is `false`.
<ide> * @property {IL10n} l10n - Localization service.
<ide> */
<ide>
<ide> const TempImageFactory = (function TempImageFactoryClosure() {
<ide> })();
<ide>
<ide> /**
<del> * @class
<ide> * @implements {IRenderableView}
<ide> */
<del>var PDFThumbnailView = (function PDFThumbnailViewClosure() {
<add>class PDFThumbnailView {
<ide> /**
<del> * @constructs PDFThumbnailView
<ide> * @param {PDFThumbnailViewOptions} options
<ide> */
<del> function PDFThumbnailView(options) {
<del> var container = options.container;
<del> var id = options.id;
<del> var defaultViewport = options.defaultViewport;
<del> var linkService = options.linkService;
<del> var renderingQueue = options.renderingQueue;
<del> var disableCanvasToImageConversion =
<del> options.disableCanvasToImageConversion || false;
<del>
<add> constructor({ container, id, defaultViewport, linkService, renderingQueue,
<add> disableCanvasToImageConversion = false, l10n = NullL10n, }) {
<ide> this.id = id;
<ide> this.renderingId = 'thumbnail' + id;
<ide> this.pageLabel = null;
<ide> var PDFThumbnailView = (function PDFThumbnailViewClosure() {
<ide> this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
<ide> this.scale = this.canvasWidth / this.pageWidth;
<ide>
<del> this.l10n = options.l10n || NullL10n;
<add> this.l10n = l10n;
<ide>
<del> var anchor = document.createElement('a');
<add> let anchor = document.createElement('a');
<ide> anchor.href = linkService.getAnchorUrl('#page=' + id);
<ide> this.l10n.get('thumb_page_title', { page: id, }, 'Page {{page}}').
<ide> then((msg) => {
<ide> anchor.title = msg;
<ide> });
<del> anchor.onclick = function stopNavigation() {
<add> anchor.onclick = function() {
<ide> linkService.page = id;
<ide> return false;
<ide> };
<ide> this.anchor = anchor;
<ide>
<del> var div = document.createElement('div');
<add> let div = document.createElement('div');
<ide> div.className = 'thumbnail';
<ide> div.setAttribute('data-page-number', this.id);
<ide> this.div = div;
<ide> var PDFThumbnailView = (function PDFThumbnailViewClosure() {
<ide> div.classList.add('selected');
<ide> }
<ide>
<del> var ring = document.createElement('div');
<add> let ring = document.createElement('div');
<ide> ring.className = 'thumbnailSelectionRing';
<del> var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
<add> let borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
<ide> ring.style.width = this.canvasWidth + borderAdjustment + 'px';
<ide> ring.style.height = this.canvasHeight + borderAdjustment + 'px';
<ide> this.ring = ring;
<ide> var PDFThumbnailView = (function PDFThumbnailViewClosure() {
<ide> container.appendChild(anchor);
<ide> }
<ide>
<del> PDFThumbnailView.prototype = {
<del> setPdfPage: function PDFThumbnailView_setPdfPage(pdfPage) {
<del> this.pdfPage = pdfPage;
<del> this.pdfPageRotate = pdfPage.rotate;
<del> var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
<del> this.viewport = pdfPage.getViewport(1, totalRotation);
<del> this.reset();
<del> },
<add> setPdfPage(pdfPage) {
<add> this.pdfPage = pdfPage;
<add> this.pdfPageRotate = pdfPage.rotate;
<add> let totalRotation = (this.rotation + this.pdfPageRotate) % 360;
<add> this.viewport = pdfPage.getViewport(1, totalRotation);
<add> this.reset();
<add> }
<ide>
<del> reset: function PDFThumbnailView_reset() {
<del> this.cancelRendering();
<add> reset() {
<add> this.cancelRendering();
<ide>
<del> this.pageWidth = this.viewport.width;
<del> this.pageHeight = this.viewport.height;
<del> this.pageRatio = this.pageWidth / this.pageHeight;
<add> this.pageWidth = this.viewport.width;
<add> this.pageHeight = this.viewport.height;
<add> this.pageRatio = this.pageWidth / this.pageHeight;
<ide>
<del> this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
<del> this.scale = (this.canvasWidth / this.pageWidth);
<add> this.canvasHeight = (this.canvasWidth / this.pageRatio) | 0;
<add> this.scale = (this.canvasWidth / this.pageWidth);
<ide>
<del> this.div.removeAttribute('data-loaded');
<del> var ring = this.ring;
<del> var childNodes = ring.childNodes;
<del> for (var i = childNodes.length - 1; i >= 0; i--) {
<del> ring.removeChild(childNodes[i]);
<del> }
<del> var borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
<del> ring.style.width = this.canvasWidth + borderAdjustment + 'px';
<del> ring.style.height = this.canvasHeight + borderAdjustment + 'px';
<add> this.div.removeAttribute('data-loaded');
<add> let ring = this.ring;
<add> let childNodes = ring.childNodes;
<add> for (let i = childNodes.length - 1; i >= 0; i--) {
<add> ring.removeChild(childNodes[i]);
<add> }
<add> let borderAdjustment = 2 * THUMBNAIL_CANVAS_BORDER_WIDTH;
<add> ring.style.width = this.canvasWidth + borderAdjustment + 'px';
<add> ring.style.height = this.canvasHeight + borderAdjustment + 'px';
<ide>
<del> if (this.canvas) {
<del> // Zeroing the width and height causes Firefox to release graphics
<del> // resources immediately, which can greatly reduce memory consumption.
<del> this.canvas.width = 0;
<del> this.canvas.height = 0;
<del> delete this.canvas;
<del> }
<del> if (this.image) {
<del> this.image.removeAttribute('src');
<del> delete this.image;
<del> }
<del> },
<add> if (this.canvas) {
<add> // Zeroing the width and height causes Firefox to release graphics
<add> // resources immediately, which can greatly reduce memory consumption.
<add> this.canvas.width = 0;
<add> this.canvas.height = 0;
<add> delete this.canvas;
<add> }
<add> if (this.image) {
<add> this.image.removeAttribute('src');
<add> delete this.image;
<add> }
<add> }
<ide>
<del> update: function PDFThumbnailView_update(rotation) {
<del> if (typeof rotation !== 'undefined') {
<del> this.rotation = rotation;
<del> }
<del> var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
<del> this.viewport = this.viewport.clone({
<del> scale: 1,
<del> rotation: totalRotation,
<del> });
<del> this.reset();
<del> },
<add> update(rotation) {
<add> if (typeof rotation !== 'undefined') {
<add> this.rotation = rotation;
<add> }
<add> let totalRotation = (this.rotation + this.pdfPageRotate) % 360;
<add> this.viewport = this.viewport.clone({
<add> scale: 1,
<add> rotation: totalRotation,
<add> });
<add> this.reset();
<add> }
<ide>
<del> cancelRendering: function PDFThumbnailView_cancelRendering() {
<del> if (this.renderTask) {
<del> this.renderTask.cancel();
<del> this.renderTask = null;
<del> }
<del> this.renderingState = RenderingStates.INITIAL;
<del> this.resume = null;
<del> },
<add> cancelRendering() {
<add> if (this.renderTask) {
<add> this.renderTask.cancel();
<add> this.renderTask = null;
<add> }
<add> this.renderingState = RenderingStates.INITIAL;
<add> this.resume = null;
<add> }
<ide>
<del> /**
<del> * @private
<del> */
<del> _getPageDrawContext:
<del> function PDFThumbnailView_getPageDrawContext(noCtxScale) {
<del> var canvas = document.createElement('canvas');
<del> // Keep the no-thumbnail outline visible, i.e. `data-loaded === false`,
<del> // until rendering/image conversion is complete, to avoid display issues.
<del> this.canvas = canvas;
<add> /**
<add> * @private
<add> */
<add> _getPageDrawContext(noCtxScale = false) {
<add> let canvas = document.createElement('canvas');
<add> // Keep the no-thumbnail outline visible, i.e. `data-loaded === false`,
<add> // until rendering/image conversion is complete, to avoid display issues.
<add> this.canvas = canvas;
<add>
<add> if (typeof PDFJSDev === 'undefined' ||
<add> PDFJSDev.test('MOZCENTRAL || FIREFOX || GENERIC')) {
<add> canvas.mozOpaque = true;
<add> }
<add> let ctx = canvas.getContext('2d', { alpha: false, });
<add> let outputScale = getOutputScale(ctx);
<ide>
<del> if (typeof PDFJSDev === 'undefined' ||
<del> PDFJSDev.test('MOZCENTRAL || FIREFOX || GENERIC')) {
<del> canvas.mozOpaque = true;
<del> }
<del> var ctx = canvas.getContext('2d', { alpha: false, });
<del> var outputScale = getOutputScale(ctx);
<add> canvas.width = (this.canvasWidth * outputScale.sx) | 0;
<add> canvas.height = (this.canvasHeight * outputScale.sy) | 0;
<add> canvas.style.width = this.canvasWidth + 'px';
<add> canvas.style.height = this.canvasHeight + 'px';
<ide>
<del> canvas.width = (this.canvasWidth * outputScale.sx) | 0;
<del> canvas.height = (this.canvasHeight * outputScale.sy) | 0;
<del> canvas.style.width = this.canvasWidth + 'px';
<del> canvas.style.height = this.canvasHeight + 'px';
<add> if (!noCtxScale && outputScale.scaled) {
<add> ctx.scale(outputScale.sx, outputScale.sy);
<add> }
<add> return ctx;
<add> }
<ide>
<del> if (!noCtxScale && outputScale.scaled) {
<del> ctx.scale(outputScale.sx, outputScale.sy);
<del> }
<del> return ctx;
<del> },
<add> /**
<add> * @private
<add> */
<add> _convertCanvasToImage() {
<add> if (!this.canvas) {
<add> return;
<add> }
<add> if (this.renderingState !== RenderingStates.FINISHED) {
<add> return;
<add> }
<add> let id = this.renderingId;
<add> let className = 'thumbnailImage';
<ide>
<del> /**
<del> * @private
<del> */
<del> _convertCanvasToImage: function PDFThumbnailView_convertCanvasToImage() {
<del> if (!this.canvas) {
<del> return;
<del> }
<del> if (this.renderingState !== RenderingStates.FINISHED) {
<del> return;
<del> }
<del> var id = this.renderingId;
<del> var className = 'thumbnailImage';
<del>
<del> if (this.disableCanvasToImageConversion) {
<del> this.canvas.id = id;
<del> this.canvas.className = className;
<del> this.l10n.get('thumb_page_canvas', { page: this.pageId, },
<del> 'Thumbnail of Page {{page}}').then((msg) => {
<del> this.canvas.setAttribute('aria-label', msg);
<del> });
<del>
<del> this.div.setAttribute('data-loaded', true);
<del> this.ring.appendChild(this.canvas);
<del> return;
<del> }
<del> var image = document.createElement('img');
<del> image.id = id;
<del> image.className = className;
<add> if (this.disableCanvasToImageConversion) {
<add> this.canvas.id = id;
<add> this.canvas.className = className;
<ide> this.l10n.get('thumb_page_canvas', { page: this.pageId, },
<del> 'Thumbnail of Page {{page}}').
<del> then((msg) => {
<del> image.setAttribute('aria-label', msg);
<add> 'Thumbnail of Page {{page}}').then((msg) => {
<add> this.canvas.setAttribute('aria-label', msg);
<ide> });
<ide>
<del> image.style.width = this.canvasWidth + 'px';
<del> image.style.height = this.canvasHeight + 'px';
<del>
<del> image.src = this.canvas.toDataURL();
<del> this.image = image;
<del>
<ide> this.div.setAttribute('data-loaded', true);
<del> this.ring.appendChild(image);
<add> this.ring.appendChild(this.canvas);
<add> return;
<add> }
<add> let image = document.createElement('img');
<add> image.id = id;
<add> image.className = className;
<add> this.l10n.get('thumb_page_canvas', { page: this.pageId, },
<add> 'Thumbnail of Page {{page}}').
<add> then((msg) => {
<add> image.setAttribute('aria-label', msg);
<add> });
<ide>
<del> // Zeroing the width and height causes Firefox to release graphics
<del> // resources immediately, which can greatly reduce memory consumption.
<del> this.canvas.width = 0;
<del> this.canvas.height = 0;
<del> delete this.canvas;
<del> },
<add> image.style.width = this.canvasWidth + 'px';
<add> image.style.height = this.canvasHeight + 'px';
<ide>
<del> draw() {
<del> if (this.renderingState !== RenderingStates.INITIAL) {
<del> console.error('Must be in new state before drawing');
<del> return Promise.resolve(undefined);
<del> }
<add> image.src = this.canvas.toDataURL();
<add> this.image = image;
<ide>
<del> this.renderingState = RenderingStates.RUNNING;
<del>
<del> let renderCapability = createPromiseCapability();
<del>
<del> let finishRenderTask = (error) => {
<del> // The renderTask may have been replaced by a new one, so only remove
<del> // the reference to the renderTask if it matches the one that is
<del> // triggering this callback.
<del> if (renderTask === this.renderTask) {
<del> this.renderTask = null;
<del> }
<del>
<del> if (((typeof PDFJSDev === 'undefined' ||
<del> !PDFJSDev.test('PDFJS_NEXT')) && error === 'cancelled') ||
<del> error instanceof RenderingCancelledException) {
<del> renderCapability.resolve(undefined);
<del> return;
<del> }
<del>
<del> this.renderingState = RenderingStates.FINISHED;
<del> this._convertCanvasToImage();
<del>
<del> if (!error) {
<del> renderCapability.resolve(undefined);
<del> } else {
<del> renderCapability.reject(error);
<del> }
<del> };
<del>
<del> let ctx = this._getPageDrawContext();
<del> let drawViewport = this.viewport.clone({ scale: this.scale, });
<del> let renderContinueCallback = (cont) => {
<del> if (!this.renderingQueue.isHighestPriority(this)) {
<del> this.renderingState = RenderingStates.PAUSED;
<del> this.resume = () => {
<del> this.renderingState = RenderingStates.RUNNING;
<del> cont();
<del> };
<del> return;
<del> }
<del> cont();
<del> };
<del>
<del> let renderContext = {
<del> canvasContext: ctx,
<del> viewport: drawViewport,
<del> };
<del> let renderTask = this.renderTask = this.pdfPage.render(renderContext);
<del> renderTask.onContinue = renderContinueCallback;
<del>
<del> renderTask.promise.then(function() {
<del> finishRenderTask(null);
<del> }, function(error) {
<del> finishRenderTask(error);
<del> });
<del> return renderCapability.promise;
<del> },
<add> this.div.setAttribute('data-loaded', true);
<add> this.ring.appendChild(image);
<ide>
<del> setImage: function PDFThumbnailView_setImage(pageView) {
<del> if (this.renderingState !== RenderingStates.INITIAL) {
<del> return;
<add> // Zeroing the width and height causes Firefox to release graphics
<add> // resources immediately, which can greatly reduce memory consumption.
<add> this.canvas.width = 0;
<add> this.canvas.height = 0;
<add> delete this.canvas;
<add> }
<add>
<add> draw() {
<add> if (this.renderingState !== RenderingStates.INITIAL) {
<add> console.error('Must be in new state before drawing');
<add> return Promise.resolve(undefined);
<add> }
<add> this.renderingState = RenderingStates.RUNNING;
<add>
<add> let renderCapability = createPromiseCapability();
<add> let finishRenderTask = (error) => {
<add> // The renderTask may have been replaced by a new one, so only remove
<add> // the reference to the renderTask if it matches the one that is
<add> // triggering this callback.
<add> if (renderTask === this.renderTask) {
<add> this.renderTask = null;
<ide> }
<del> var img = pageView.canvas;
<del> if (!img) {
<add>
<add> if (((typeof PDFJSDev === 'undefined' ||
<add> !PDFJSDev.test('PDFJS_NEXT')) && error === 'cancelled') ||
<add> error instanceof RenderingCancelledException) {
<add> renderCapability.resolve(undefined);
<ide> return;
<ide> }
<del> if (!this.pdfPage) {
<del> this.setPdfPage(pageView.pdfPage);
<del> }
<ide>
<ide> this.renderingState = RenderingStates.FINISHED;
<add> this._convertCanvasToImage();
<ide>
<del> var ctx = this._getPageDrawContext(true);
<del> var canvas = ctx.canvas;
<add> if (!error) {
<add> renderCapability.resolve(undefined);
<add> } else {
<add> renderCapability.reject(error);
<add> }
<add> };
<ide>
<del> if (img.width <= 2 * canvas.width) {
<del> ctx.drawImage(img, 0, 0, img.width, img.height,
<del> 0, 0, canvas.width, canvas.height);
<del> this._convertCanvasToImage();
<add> let ctx = this._getPageDrawContext();
<add> let drawViewport = this.viewport.clone({ scale: this.scale, });
<add> let renderContinueCallback = (cont) => {
<add> if (!this.renderingQueue.isHighestPriority(this)) {
<add> this.renderingState = RenderingStates.PAUSED;
<add> this.resume = () => {
<add> this.renderingState = RenderingStates.RUNNING;
<add> cont();
<add> };
<ide> return;
<ide> }
<del> // drawImage does an awful job of rescaling the image, doing it gradually.
<del> var MAX_NUM_SCALING_STEPS = 3;
<del> var reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
<del> var reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
<del> var reducedImage = TempImageFactory.getCanvas(reducedWidth,
<del> reducedHeight);
<del> var reducedImageCtx = reducedImage.getContext('2d');
<del>
<del> while (reducedWidth > img.width || reducedHeight > img.height) {
<del> reducedWidth >>= 1;
<del> reducedHeight >>= 1;
<del> }
<del> reducedImageCtx.drawImage(img, 0, 0, img.width, img.height,
<del> 0, 0, reducedWidth, reducedHeight);
<del> while (reducedWidth > 2 * canvas.width) {
<del> reducedImageCtx.drawImage(reducedImage,
<del> 0, 0, reducedWidth, reducedHeight,
<del> 0, 0, reducedWidth >> 1, reducedHeight >> 1);
<del> reducedWidth >>= 1;
<del> reducedHeight >>= 1;
<del> }
<del> ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight,
<add> cont();
<add> };
<add>
<add> let renderContext = {
<add> canvasContext: ctx,
<add> viewport: drawViewport,
<add> };
<add> let renderTask = this.renderTask = this.pdfPage.render(renderContext);
<add> renderTask.onContinue = renderContinueCallback;
<add>
<add> renderTask.promise.then(function() {
<add> finishRenderTask(null);
<add> }, function(error) {
<add> finishRenderTask(error);
<add> });
<add> return renderCapability.promise;
<add> }
<add>
<add> setImage(pageView) {
<add> if (this.renderingState !== RenderingStates.INITIAL) {
<add> return;
<add> }
<add> let img = pageView.canvas;
<add> if (!img) {
<add> return;
<add> }
<add> if (!this.pdfPage) {
<add> this.setPdfPage(pageView.pdfPage);
<add> }
<add>
<add> this.renderingState = RenderingStates.FINISHED;
<add>
<add> let ctx = this._getPageDrawContext(true);
<add> let canvas = ctx.canvas;
<add> if (img.width <= 2 * canvas.width) {
<add> ctx.drawImage(img, 0, 0, img.width, img.height,
<ide> 0, 0, canvas.width, canvas.height);
<ide> this._convertCanvasToImage();
<del> },
<add> return;
<add> }
<ide>
<del> get pageId() {
<del> return (this.pageLabel !== null ? this.pageLabel : this.id);
<del> },
<add> // drawImage does an awful job of rescaling the image, doing it gradually.
<add> let reducedWidth = canvas.width << MAX_NUM_SCALING_STEPS;
<add> let reducedHeight = canvas.height << MAX_NUM_SCALING_STEPS;
<add> let reducedImage = TempImageFactory.getCanvas(reducedWidth,
<add> reducedHeight);
<add> let reducedImageCtx = reducedImage.getContext('2d');
<ide>
<del> /**
<del> * @param {string|null} label
<del> */
<del> setPageLabel: function PDFThumbnailView_setPageLabel(label) {
<del> this.pageLabel = (typeof label === 'string' ? label : null);
<add> while (reducedWidth > img.width || reducedHeight > img.height) {
<add> reducedWidth >>= 1;
<add> reducedHeight >>= 1;
<add> }
<add> reducedImageCtx.drawImage(img, 0, 0, img.width, img.height,
<add> 0, 0, reducedWidth, reducedHeight);
<add> while (reducedWidth > 2 * canvas.width) {
<add> reducedImageCtx.drawImage(reducedImage,
<add> 0, 0, reducedWidth, reducedHeight,
<add> 0, 0, reducedWidth >> 1, reducedHeight >> 1);
<add> reducedWidth >>= 1;
<add> reducedHeight >>= 1;
<add> }
<add> ctx.drawImage(reducedImage, 0, 0, reducedWidth, reducedHeight,
<add> 0, 0, canvas.width, canvas.height);
<add> this._convertCanvasToImage();
<add> }
<ide>
<del> this.l10n.get('thumb_page_title', { page: this.pageId, },
<del> 'Page {{page}}').then((msg) => {
<del> this.anchor.title = msg;
<del> });
<add> get pageId() {
<add> return (this.pageLabel !== null ? this.pageLabel : this.id);
<add> }
<ide>
<del> if (this.renderingState !== RenderingStates.FINISHED) {
<del> return;
<del> }
<add> /**
<add> * @param {string|null} label
<add> */
<add> setPageLabel(label) {
<add> this.pageLabel = (typeof label === 'string' ? label : null);
<ide>
<del> this.l10n.get('thumb_page_canvas', { page: this.pageId, },
<del> 'Thumbnail of Page {{page}}').then((ariaLabel) => {
<del> if (this.image) {
<del> this.image.setAttribute('aria-label', ariaLabel);
<del> } else if (this.disableCanvasToImageConversion && this.canvas) {
<del> this.canvas.setAttribute('aria-label', ariaLabel);
<del> }
<del> });
<del> },
<del> };
<add> this.l10n.get('thumb_page_title', { page: this.pageId, },
<add> 'Page {{page}}').then((msg) => {
<add> this.anchor.title = msg;
<add> });
<ide>
<del> PDFThumbnailView.cleanup = function() {
<del> TempImageFactory.destroyCanvas();
<del> };
<add> if (this.renderingState !== RenderingStates.FINISHED) {
<add> return;
<add> }
<ide>
<del> return PDFThumbnailView;
<del>})();
<add> this.l10n.get('thumb_page_canvas', { page: this.pageId, },
<add> 'Thumbnail of Page {{page}}').then((ariaLabel) => {
<add> if (this.image) {
<add> this.image.setAttribute('aria-label', ariaLabel);
<add> } else if (this.disableCanvasToImageConversion && this.canvas) {
<add> this.canvas.setAttribute('aria-label', ariaLabel);
<add> }
<add> });
<add> }
<add>
<add> static cleanup() {
<add> TempImageFactory.destroyCanvas();
<add> }
<add>}
<ide>
<ide> export {
<ide> PDFThumbnailView, | 1 |
Javascript | Javascript | update some bengali translations | ce8f2f11c41fdad6cec51716e6392614468ede7e | <ide><path>src/locale/bn.js
<ide> numberMap = {
<ide> };
<ide>
<ide> export default moment.defineLocale('bn', {
<del> months : 'জানুয়ারী_ফেবুয়ারী_মার্চ_এপ্রিল_মে_জুন_জুলাই_অগাস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
<del> monthsShort : 'জানু_ফেব_মার্চ_এপর_মে_জুন_জুল_অগ_সেপ্ট_অক্টো_নভ_ডিসেম্'.split('_'),
<del> weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পত্তিবার_শুক্রবার_শনিবার'.split('_'),
<del> weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পত্তি_শুক্র_শনি'.split('_'),
<del> weekdaysMin : 'রব_সম_মঙ্গ_বু_ব্রিহ_শু_শনি'.split('_'),
<add> months : 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'),
<add> monthsShort : 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'),
<add> weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'),
<add> weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),
<add> weekdaysMin : 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'),
<ide> longDateFormat : {
<ide> LT : 'A h:mm সময়',
<ide> LTS : 'A h:mm:ss সময়',
<ide> export default moment.defineLocale('bn', {
<ide> doy : 6 // The week that contains Jan 1st is the first week of the year.
<ide> }
<ide> });
<del>
<ide><path>src/test/locale/bn.js
<ide> import moment from '../../moment';
<ide> localeModule('bn');
<ide>
<ide> test('parse', function (assert) {
<del> var tests = 'জানুয়ারী জানু_ফেবুয়ারী ফেব_মার্চ মার্চ_এপ্রিল এপর_মে মে_জুন জুন_জুলাই জুল_অগাস্ট অগ_সেপ্টেম্বর সেপ্ট_অক্টোবর অক্টো_নভেম্বর নভ_ডিসেম্বর ডিসেম্'.split('_'), i;
<add> var tests = 'জানুয়ারী জানু_ফেব্রুয়ারি ফেব_মার্চ মার্চ_এপ্রিল এপ্র_মে মে_জুন জুন_জুলাই জুল_আগস্ট আগ_সেপ্টেম্বর সেপ্ট_অক্টোবর অক্টো_নভেম্বর নভে_ডিসেম্বর ডিসে'.split('_'), i;
<ide> function equalTest(input, mmm, i) {
<ide> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
<ide> }
<ide> test('parse', function (assert) {
<ide>
<ide> test('format', function (assert) {
<ide> var a = [
<del> ['dddd, Do MMMM YYYY, a h:mm:ss সময়', 'রবিবার, ১৪ ফেবুয়ারী ২০১০, দুপুর ৩:২৫:৫০ সময়'],
<add> ['dddd, Do MMMM YYYY, a h:mm:ss সময়', 'রবিবার, ১৪ ফেব্রুয়ারি ২০১০, দুপুর ৩:২৫:৫০ সময়'],
<ide> ['ddd, a h সময়', 'রবি, দুপুর ৩ সময়'],
<del> ['M Mo MM MMMM MMM', '২ ২ ০২ ফেবুয়ারী ফেব'],
<add> ['M Mo MM MMMM MMM', '২ ২ ০২ ফেব্রুয়ারি ফেব'],
<ide> ['YYYY YY', '২০১০ ১০'],
<ide> ['D Do DD', '১৪ ১৪ ১৪'],
<del> ['d do dddd ddd dd', '০ ০ রবিবার রবি রব'],
<add> ['d do dddd ddd dd', '০ ০ রবিবার রবি রবি'],
<ide> ['DDD DDDo DDDD', '৪৫ ৪৫ ০৪৫'],
<ide> ['w wo ww', '৮ ৮ ০৮'],
<ide> ['h hh', '৩ ০৩'],
<ide> test('format', function (assert) {
<ide> ['LT', 'দুপুর ৩:২৫ সময়'],
<ide> ['LTS', 'দুপুর ৩:২৫:৫০ সময়'],
<ide> ['L', '১৪/০২/২০১০'],
<del> ['LL', '১৪ ফেবুয়ারী ২০১০'],
<del> ['LLL', '১৪ ফেবুয়ারী ২০১০, দুপুর ৩:২৫ সময়'],
<del> ['LLLL', 'রবিবার, ১৪ ফেবুয়ারী ২০১০, দুপুর ৩:২৫ সময়'],
<add> ['LL', '১৪ ফেব্রুয়ারি ২০১০'],
<add> ['LLL', '১৪ ফেব্রুয়ারি ২০১০, দুপুর ৩:২৫ সময়'],
<add> ['LLLL', 'রবিবার, ১৪ ফেব্রুয়ারি ২০১০, দুপুর ৩:২৫ সময়'],
<ide> ['l', '১৪/২/২০১০'],
<ide> ['ll', '১৪ ফেব ২০১০'],
<ide> ['lll', '১৪ ফেব ২০১০, দুপুর ৩:২৫ সময়'],
<ide> test('format ordinal', function (assert) {
<ide> });
<ide>
<ide> test('format month', function (assert) {
<del> var expected = 'জানুয়ারী জানু_ফেবুয়ারী ফেব_মার্চ মার্চ_এপ্রিল এপর_মে মে_জুন জুন_জুলাই জুল_অগাস্ট অগ_সেপ্টেম্বর সেপ্ট_অক্টোবর অক্টো_নভেম্বর নভ_ডিসেম্বর ডিসেম্'.split('_'), i;
<add> var expected = 'জানুয়ারী জানু_ফেব্রুয়ারি ফেব_মার্চ মার্চ_এপ্রিল এপ্র_মে মে_জুন জুন_জুলাই জুল_আগস্ট আগ_সেপ্টেম্বর সেপ্ট_অক্টোবর অক্টো_নভেম্বর নভে_ডিসেম্বর ডিসে'.split('_'), i;
<ide> for (i = 0; i < expected.length; i++) {
<ide> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
<ide> }
<ide> });
<ide>
<ide> test('format week', function (assert) {
<del> var expected = 'রবিবার রবি রব_সোমবার সোম সম_মঙ্গলবার মঙ্গল মঙ্গ_বুধবার বুধ বু_বৃহস্পত্তিবার বৃহস্পত্তি ব্রিহ_শুক্রবার শুক্র শু_শনিবার শনি শনি'.split('_'), i;
<add> var expected = 'রবিবার রবি রবি_সোমবার সোম সোম_মঙ্গলবার মঙ্গল মঙ্গ_বুধবার বুধ বুধ_বৃহস্পতিবার বৃহস্পতি বৃহঃ_শুক্রবার শুক্র শুক্র_শনিবার শনি শনি'.split('_'), i;
<ide> for (i = 0; i < expected.length; i++) {
<ide> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
<ide> }
<ide> test('weeks year starting sunday formatted', function (assert) {
<ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '২ ০২ ২', 'Jan 14 2012 should be week 2');
<ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '৩ ০৩ ৩', 'Jan 15 2012 should be week 3');
<ide> });
<del> | 2 |
Python | Python | resolve linting issues | d2795dd26d7483ea0de119ae135eab0a94cf23d8 | <ide><path>rest_framework/fields.py
<ide> def get_component(obj, attr_name):
<ide>
<ide>
<ide> def readable_datetime_formats(formats):
<del> format = ', '.join(formats).replace(ISO_8601,
<del> 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]')
<add> format = ', '.join(formats).replace(
<add> ISO_8601,
<add> 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
<add> )
<ide> return humanize_strptime(format)
<ide>
<ide>
<ide> def attributes(self):
<ide> }
<ide>
<ide>
<del>##### Typed Fields #####
<add># Typed Fields
<ide>
<ide> class BooleanField(WritableField):
<ide> type_name = 'BooleanField'
<ide> class URLField(CharField):
<ide> type_label = 'url'
<ide>
<ide> def __init__(self, **kwargs):
<del> if not 'validators' in kwargs:
<add> if 'validators' not in kwargs:
<ide> kwargs['validators'] = [validators.URLValidator()]
<ide> super(URLField, self).__init__(**kwargs)
<ide>
<ide><path>rest_framework/generics.py
<ide> def get_filter_backends(self):
<ide>
<ide> return filter_backends
<ide>
<del> ########################
<del> ### The following methods provide default implementations
<del> ### that you may want to override for more complex cases.
<add> # The following methods provide default implementations
<add> # that you may want to override for more complex cases.
<ide>
<ide> def get_paginate_by(self, queryset=None):
<ide> """
<ide> def get_object(self, queryset=None):
<ide>
<ide> return obj
<ide>
<del> ########################
<del> ### The following are placeholder methods,
<del> ### and are intended to be overridden.
<del> ###
<del> ### The are not called by GenericAPIView directly,
<del> ### but are used by the mixin methods.
<add> # The following are placeholder methods,
<add> # and are intended to be overridden.
<add> #
<add> # The are not called by GenericAPIView directly,
<add> # but are used by the mixin methods.
<ide>
<ide> def pre_save(self, obj):
<ide> """
<ide> def metadata(self, request):
<ide> return ret
<ide>
<ide>
<del>##########################################################
<del>### Concrete view classes that provide method handlers ###
<del>### by composing the mixin classes with the base view. ###
<del>##########################################################
<add># Concrete view classes that provide method handlers
<add># by composing the mixin classes with the base view.
<ide>
<ide> class CreateAPIView(mixins.CreateModelMixin,
<ide> GenericAPIView):
<ide> def delete(self, request, *args, **kwargs):
<ide> return self.destroy(request, *args, **kwargs)
<ide>
<ide>
<del>##########################
<del>### Deprecated classes ###
<del>##########################
<add># Deprecated classes
<ide>
<ide> class MultipleObjectAPIView(GenericAPIView):
<ide> def __init__(self, *args, **kwargs):
<ide><path>rest_framework/relations.py
<ide> import warnings
<ide>
<ide>
<del>##### Relational fields #####
<del>
<add># Relational fields
<ide>
<ide> # Not actually Writable, but subclasses may need to be.
<ide> class RelatedField(WritableField):
<ide> def initialize(self, parent, field_name):
<ide> else: # Reverse
<ide> self.queryset = manager.field.rel.to._default_manager.all()
<ide>
<del> ### We need this stuff to make form choices work...
<add> # We need this stuff to make form choices work...
<ide>
<ide> def prepare_value(self, obj):
<ide> return self.to_native(obj)
<ide> def _set_choices(self, value):
<ide>
<ide> choices = property(_get_choices, _set_choices)
<ide>
<del> ### Default value handling
<add> # Default value handling
<ide>
<ide> def get_default_value(self):
<ide> default = super(RelatedField, self).get_default_value()
<ide> if self.many and default is None:
<ide> return []
<ide> return default
<ide>
<del> ### Regular serializer stuff...
<add> # Regular serializer stuff...
<ide>
<ide> def field_to_native(self, obj, field_name):
<ide> try:
<ide> def field_from_native(self, data, files, field_name, into):
<ide> into[(self.source or field_name)] = self.from_native(value)
<ide>
<ide>
<del>### PrimaryKey relationships
<add># PrimaryKey relationships
<ide>
<ide> class PrimaryKeyRelatedField(RelatedField):
<ide> """
<ide> def field_to_native(self, obj, field_name):
<ide> return self.to_native(pk)
<ide>
<ide>
<del>### Slug relationships
<del>
<add># Slug relationships
<ide>
<ide> class SlugRelatedField(RelatedField):
<ide> """
<ide> def from_native(self, data):
<ide> raise ValidationError(msg)
<ide>
<ide>
<del>### Hyperlinked relationships
<add># Hyperlinked relationships
<ide>
<ide> class HyperlinkedRelatedField(RelatedField):
<ide> """
<ide><path>rest_framework/renderers.py
<ide> def show_form_for_method(self, view, method, request, obj):
<ide> """
<ide> Returns True if a form should be shown for this method.
<ide> """
<del> if not method in view.allowed_methods:
<add> if method not in view.allowed_methods:
<ide> return # Not a valid method
<ide>
<ide> if not api_settings.FORM_METHOD_OVERRIDE:
<ide><path>rest_framework/request.py
<ide> def _authenticate(self):
<ide> self._not_authenticated()
<ide> raise
<ide>
<del> if not user_auth_tuple is None:
<add> if user_auth_tuple is not None:
<ide> self._authenticator = authenticator
<ide> self._user, self._auth = user_auth_tuple
<ide> return
<ide><path>rest_framework/templatetags/rest_framework.py
<ide> def urlize_quoted_links(text, trim_url_limit=None, nofollow=True, autoescape=Tru
<ide> url = smart_urlquote_wrapper(middle)
<ide> elif simple_url_2_re.match(middle):
<ide> url = smart_urlquote_wrapper('http://%s' % middle)
<del> elif not ':' in middle and simple_email_re.match(middle):
<add> elif ':' not in middle and simple_email_re.match(middle):
<ide> local, domain = middle.rsplit('@', 1)
<ide> try:
<ide> domain = domain.encode('idna').decode('ascii')
<ide><path>tests/conftest.py
<ide> def pytest_configure():
<ide> )
<ide>
<ide> try:
<del> import oauth_provider
<del> import oauth2
<add> import oauth_provider # NOQA
<add> import oauth2 # NOQA
<ide> except ImportError:
<ide> pass
<ide> else:
<ide> def pytest_configure():
<ide> )
<ide>
<ide> try:
<del> import provider
<add> import provider # NOQA
<ide> except ImportError:
<ide> pass
<ide> else:
<ide> def pytest_configure():
<ide>
<ide> # guardian is optional
<ide> try:
<del> import guardian
<add> import guardian # NOQA
<ide> except ImportError:
<ide> pass
<ide> else:
<ide> settings.ANONYMOUS_USER_ID = -1
<ide> settings.AUTHENTICATION_BACKENDS = (
<del> 'django.contrib.auth.backends.ModelBackend', # default
<add> 'django.contrib.auth.backends.ModelBackend',
<ide> 'guardian.backends.ObjectPermissionBackend',
<ide> )
<ide> settings.INSTALLED_APPS += (
<ide><path>tests/test_pagination.py
<ide> def test_max_paginate_by_without_page_size_param(self):
<ide> self.assertEqual(response.data['results'], self.data[:3])
<ide>
<ide>
<del>### Tests for context in pagination serializers
<add># Tests for context in pagination serializers
<ide>
<ide> class CustomField(serializers.Field):
<ide> def to_native(self, value):
<del> if not 'view' in self.context:
<add> if 'view' not in self.context:
<ide> raise RuntimeError("context isn't getting passed into custom field")
<ide> return "value"
<ide>
<ide> class BasicModelSerializer(serializers.Serializer):
<ide>
<ide> def __init__(self, *args, **kwargs):
<ide> super(BasicModelSerializer, self).__init__(*args, **kwargs)
<del> if not 'view' in self.context:
<add> if 'view' not in self.context:
<ide> raise RuntimeError("context isn't getting passed into serializer init")
<ide>
<ide>
<ide> class ListView(generics.ListCreateAPIView):
<ide> self.assertEqual(response.status_code, status.HTTP_200_OK)
<ide>
<ide>
<del>### Tests for custom pagination serializers
<add># Tests for custom pagination serializers
<ide>
<ide> class LinksSerializer(serializers.Serializer):
<ide> next = pagination.NextPageField(source='*')
<ide><path>tests/test_serializer.py
<ide> def test_missing_bool_with_default(self):
<ide> mistaken for not having a default."""
<ide> data = {
<ide> 'title': 'Some action item',
<del> #No 'done' value.
<add> # No 'done' value.
<ide> }
<ide> serializer = ActionItemSerializer(self.actionitem, data=data)
<ide> self.assertEqual(serializer.is_valid(), True)
<ide> def test_create_model_null_field_save(self):
<ide> self.fail('Exception raised on save() after validation passes')
<ide>
<ide>
<del>#test for issue #460
<add># Test for issue #460
<ide> class SerializerPickleTests(TestCase):
<ide> """
<ide> Test pickleability of the output of Serializers
<ide> class Meta:
<ide> callable = serializers.SerializerMethodField('_callable')
<ide>
<ide> def _callable(self, instance):
<del> if not 'context_item' in self.context:
<add> if 'context_item' not in self.context:
<ide> raise RuntimeError("context isn't getting passed into 2nd level nested serializer")
<ide> return "success"
<ide>
<ide> class Meta:
<ide> callable = serializers.SerializerMethodField("_callable")
<ide>
<ide> def _callable(self, instance):
<del> if not 'context_item' in self.context:
<add> if 'context_item' not in self.context:
<ide> raise RuntimeError("context isn't getting passed into 1st level nested serializer")
<ide> return "success"
<ide>
<ide> def test_serializer_metadata(self):
<ide> self.assertEqual(expected, metadata)
<ide>
<ide>
<del>### Regression test for #840
<add># Regression test for #840
<ide>
<ide> class SimpleModel(models.Model):
<ide> text = models.CharField(max_length=100)
<ide> def test_removing_non_model_field_in_validation(self):
<ide> self.assertEqual(serializer.object.text, 'foo')
<ide>
<ide>
<del>### Regression test for #878
<add># Regression test for #878
<ide>
<ide> class SimpleTargetModel(models.Model):
<ide> text = models.CharField(max_length=100)
<ide><path>tests/test_templatetags.py
<ide> class TemplateTagTests(TestCase):
<ide>
<ide> def test_add_query_param_with_non_latin_charactor(self):
<ide> # Ensure we don't double-escape non-latin characters
<del> # that are present in the querystring.
<add> # that are present in the querystring.
<ide> # See #1314.
<ide> request = factory.get("/", {'q': '查询'})
<ide> json_url = add_query_param(request, "format", "json") | 10 |
Javascript | Javascript | require ember-testing if present | e63f618538f783bb6fa100178ad79b690e1dec0d | <ide><path>packages/ember/lib/main.js
<ide> require('ember-extension-support');
<ide> // ES6TODO: resolve this via import once ember-application package is ES6'ed
<ide> requireModule('ember-extension-support');
<ide>
<add>// do this to ensure that Ember.Test is defined properly on the global
<add>// if it is present.
<add>if (Ember.__loader.registry['ember-testing']) {
<add> requireModule('ember-testing');
<add>}
<add>
<ide> /**
<ide> Ember
<ide> | 1 |
Python | Python | add schema and read-only endpoints for pools | 3de68501b7a76dce24bfd8a8b4659eedcf7ac29c | <ide><path>airflow/api_connexion/endpoints/pool_endpoint.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>from flask import request
<ide>
<del># TODO(mik-laj): We have to implement it.
<del># Do you want to help? Please look at: https://github.com/apache/airflow/issues/8131
<add>from airflow.api_connexion import parameters
<add>from airflow.api_connexion.exceptions import NotFound
<add>from airflow.api_connexion.schemas.pool_schema import PoolCollection, pool_collection_schema, pool_schema
<add>from airflow.models.pool import Pool
<add>from airflow.utils.session import provide_session
<ide>
<ide>
<ide> def delete_pool():
<ide> def delete_pool():
<ide> raise NotImplementedError("Not implemented yet.")
<ide>
<ide>
<del>def get_pool():
<add>@provide_session
<add>def get_pool(pool_name, session):
<ide> """
<ide> Get a pool
<ide> """
<del> raise NotImplementedError("Not implemented yet.")
<add> pool_id = pool_name
<add> query = session.query(Pool)
<add> obj = query.filter(Pool.pool == pool_id).one_or_none()
<add>
<add> if obj is None:
<add> raise NotFound("Pool not found")
<add> return pool_schema.dump(obj)
<ide>
<ide>
<del>def get_pools():
<add>@provide_session
<add>def get_pools(session):
<ide> """
<ide> Get all pools
<ide> """
<del> raise NotImplementedError("Not implemented yet.")
<add> offset = request.args.get(parameters.page_offset, 0)
<add> limit = min(int(request.args.get(parameters.page_limit, 100)), 100)
<add>
<add> query = session.query(Pool)
<add> total_entries = query.count()
<add> query_list = query.offset(offset).limit(limit).all()
<add>
<add> return pool_collection_schema.dump(PoolCollection(pools=query_list, total_entries=total_entries)).data
<ide>
<ide>
<ide> def patch_pool():
<ide><path>airflow/api_connexion/exceptions.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<add>
<ide> from connexion import ProblemException
<ide>
<ide>
<ide> class NotFound(ProblemException):
<ide> """Raise when the object cannot be found"""
<ide> def __init__(self, title='Object not found', detail=None):
<ide> super().__init__(status=404, title=title, detail=detail)
<add>
<add>
<add>class BadRequest(ProblemException):
<add> """Raise when the server processes a bad request"""
<add> def __init__(self, title='Bad request', detail=None):
<add> super().__init__(status=400, title=title, detail=detail)
<add>
<add>
<add>class Unauthenticated(ProblemException):
<add> """Raise when the user is not authenticated"""
<add> def __init__(self, title='Unauthorized', detail=None):
<add> super().__init__(status=401, title=title, detail=detail)
<add>
<add>
<add>class PermissionDenied(ProblemException):
<add> """Raise when the user does not have the required permissions"""
<add> def __init__(self, title='Forbidden', detail=None):
<add> super().__init__(status=403, title=title, detail=detail)
<add>
<add>
<add>class AlreadyExists(ProblemException):
<add> """Raise when the object already exists"""
<add> def __init__(self, title='Object already exists', detail=None):
<add> super().__init__(status=409, title=title, detail=detail)
<add>
<add>
<add>class Unknown(ProblemException):
<add> """Returns a response body and status code for HTTP 500 exception"""
<add> def __init__(self, title='Unknown server error', detail=None):
<add> super().__init__(status=500, title=title, detail=detail)
<ide><path>airflow/api_connexion/parameters.py
<ide> # Pagination parameters
<ide> page_offset = "offset"
<ide> page_limit = "limit"
<add>
<add># Database entity fields
<add>dag_id = "dag_id"
<add>pool_id = "pool_id"
<ide><path>airflow/api_connexion/schemas/pool_schema.py
<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>from typing import List, NamedTuple
<add>
<add>from marshmallow import Schema, fields
<add>from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
<add>
<add>from airflow.models.pool import Pool
<add>
<add>
<add>class PoolSchema(SQLAlchemySchema):
<add> """Pool schema"""
<add>
<add> class Meta:
<add> """Meta"""
<add>
<add> model = Pool
<add> load_instance = True
<add> exclude = ("pool",)
<add>
<add> name = auto_field("pool")
<add> slots = auto_field()
<add> occupied_slots = fields.Method("get_occupied_slots", dump_only=True)
<add> running_slots = fields.Method("get_running_slots", dump_only=True)
<add> queued_slots = fields.Method("get_queued_slots", dump_only=True)
<add> open_slots = fields.Method("get_open_slots", dump_only=True)
<add>
<add> @staticmethod
<add> def get_occupied_slots(obj: Pool) -> int:
<add> """
<add> Returns the occupied slots of the pool.
<add> """
<add> return obj.occupied_slots()
<add>
<add> @staticmethod
<add> def get_running_slots(obj: Pool) -> int:
<add> """
<add> Returns the running slots of the pool.
<add> """
<add> return obj.running_slots()
<add>
<add> @staticmethod
<add> def get_queued_slots(obj: Pool) -> int:
<add> """
<add> Returns the queued slots of the pool.
<add> """
<add> return obj.queued_slots()
<add>
<add> @staticmethod
<add> def get_open_slots(obj: Pool) -> int:
<add> """
<add> Returns the open slots of the pool.
<add> """
<add> return obj.open_slots()
<add>
<add>
<add>class PoolCollection(NamedTuple):
<add> """List of Pools with metadata"""
<add>
<add> pools: List[Pool]
<add> total_entries: int
<add>
<add>
<add>class PoolCollectionSchema(Schema):
<add> """Pool Collection schema"""
<add>
<add> pools = fields.List(fields.Nested(PoolSchema))
<add> total_entries = fields.Int()
<add>
<add>
<add>pool_collection_schema = PoolCollectionSchema()
<add>pool_schema = PoolSchema()
<ide><path>tests/api_connexion/endpoints/test_pool_endpoint.py
<ide> # under the License.
<ide> import unittest
<ide>
<del>import pytest
<add>from parameterized import parameterized
<ide>
<add>from airflow.models.pool import Pool
<add>from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.db import clear_db_pools
<ide>
<ide>
<del>class TestPoolEndpoint(unittest.TestCase):
<add>class TestBasePoolEndpoints(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<ide> cls.app = app.create_app(testing=True) # type:ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<add> super().setUp()
<add> clear_db_pools()
<ide>
<add> def tearDown(self) -> None:
<add> clear_db_pools()
<ide>
<del>class TestDeletePool(TestPoolEndpoint):
<del> @pytest.mark.skip(reason="Not implemented yet")
<del> def test_should_response_200(self):
<del> response = self.client.delete("/api/v1/pools/TEST_POOL_NAME")
<del> assert response.status_code == 204
<ide>
<del>
<del>class TestGetPool(TestPoolEndpoint):
<del> @pytest.mark.skip(reason="Not implemented yet")
<del> def test_should_response_200(self):
<del> response = self.client.get("/api/v1/pools/TEST_POOL_NAME")
<del> assert response.status_code == 200
<del>
<del>
<del>class TestGetPools(TestPoolEndpoint):
<del> @pytest.mark.skip(reason="Not implemented yet")
<del> def test_should_response_200(self):
<add>class TestGetPools(TestBasePoolEndpoints):
<add> @provide_session
<add> def test_response_200(self, session):
<add> pool_model = Pool(pool="test_pool_a", slots=3)
<add> session.add(pool_model)
<add> session.commit()
<add> result = session.query(Pool).all()
<add> assert len(result) == 2 # accounts for the default pool as well
<ide> response = self.client.get("/api/v1/pools")
<ide> assert response.status_code == 200
<add> self.assertEqual(
<add> {
<add> "pools": [
<add> {
<add> "name": "default_pool",
<add> "slots": 128,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 128,
<add> },
<add> {
<add> "name": "test_pool_a",
<add> "slots": 3,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 3,
<add> },
<add> ],
<add> "total_entries": 2,
<add> },
<add> response.json,
<add> )
<ide>
<ide>
<del>class TestPatchPool(TestPoolEndpoint):
<del> @pytest.mark.skip(reason="Not implemented yet")
<del> def test_should_response_200(self):
<del> response = self.client.patch("/api/v1/pools/TEST_POOL_NAME")
<add>class TestGetPoolsPagination(TestBasePoolEndpoints):
<add> @parameterized.expand(
<add> [
<add> # Offset test data
<add> ("/api/v1/pools?offset=1", [f"test_pool{i}" for i in range(1, 101)]),
<add> ("/api/v1/pools?offset=3", [f"test_pool{i}" for i in range(3, 103)]),
<add> # Limit test data
<add> ("/api/v1/pools?limit=2", ["default_pool", "test_pool1"]),
<add> ("/api/v1/pools?limit=1", ["default_pool"]),
<add> # Limit and offset test data
<add> (
<add> "/api/v1/pools?limit=120&offset=1",
<add> [f"test_pool{i}" for i in range(1, 101)],
<add> ),
<add> ("/api/v1/pools?limit=2&offset=1", ["test_pool1", "test_pool2"]),
<add> (
<add> "/api/v1/pools?limit=3&offset=2",
<add> ["test_pool2", "test_pool3", "test_pool4"],
<add> ),
<add> ]
<add> )
<add> @provide_session
<add> def test_limit_and_offset(self, url, expected_pool_ids, session):
<add> pools = [Pool(pool=f"test_pool{i}", slots=1) for i in range(1, 121)]
<add> session.add_all(pools)
<add> session.commit()
<add> result = session.query(Pool).count()
<add> self.assertEqual(result, 121) # accounts for default pool as well
<add> response = self.client.get(url)
<ide> assert response.status_code == 200
<add> pool_ids = [pool["name"] for pool in response.json["pools"]]
<add> self.assertEqual(pool_ids, expected_pool_ids)
<ide>
<ide>
<del>class TestPostPool(TestPoolEndpoint):
<del> @pytest.mark.skip(reason="Not implemented yet")
<del> def test_should_response_200(self):
<del> response = self.client.post("/api/v1/pool")
<add>class TestGetPool(TestBasePoolEndpoints):
<add> @provide_session
<add> def test_response_200(self, session):
<add> pool_model = Pool(pool="test_pool_a", slots=3)
<add> session.add(pool_model)
<add> session.commit()
<add> response = self.client.get("/api/v1/pools/test_pool_a")
<ide> assert response.status_code == 200
<add> self.assertEqual(
<add> {
<add> "name": "test_pool_a",
<add> "slots": 3,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 3,
<add> },
<add> response.json,
<add> )
<add>
<add> def test_response_404(self):
<add> response = self.client.get("/api/v1/pools/invalid_pool")
<add> assert response.status_code == 404
<add> self.assertEqual(
<add> {
<add> "detail": None,
<add> "status": 404,
<add> "title": "Pool not found",
<add> "type": "about:blank",
<add> },
<add> response.json,
<add> )
<ide><path>tests/api_connexion/schemas/test_pool_schemas.py
<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>
<add>from airflow.api_connexion.schemas.pool_schema import PoolCollection, pool_collection_schema, pool_schema
<add>from airflow.models.pool import Pool
<add>from airflow.utils.session import provide_session
<add>from tests.test_utils.db import clear_db_pools
<add>
<add>
<add>class TestPoolSchema(unittest.TestCase):
<add> def setUp(self) -> None:
<add> clear_db_pools()
<add>
<add> def tearDown(self) -> None:
<add> clear_db_pools()
<add>
<add> @provide_session
<add> def test_serialize(self, session):
<add> pool_model = Pool(pool="test_pool", slots=2)
<add> session.add(pool_model)
<add> session.commit()
<add> pool_instance = session.query(Pool).filter(Pool.pool == pool_model.pool).first()
<add> serialized_pool = pool_schema.dump(pool_instance)
<add> self.assertEqual(
<add> serialized_pool.data,
<add> {
<add> "name": "test_pool",
<add> "slots": 2,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 2,
<add> },
<add> )
<add>
<add> @provide_session
<add> def test_desearialize(self, session):
<add> pool_dict = {"name": "test_pool", "slots": 3}
<add> deserialized_pool = pool_schema.load(pool_dict, session=session)
<add> self.assertIsInstance(deserialized_pool.data, Pool)
<add>
<add>
<add>class TestPoolCollectionSchema(unittest.TestCase):
<add> def setUp(self) -> None:
<add> clear_db_pools()
<add>
<add> def tearDown(self) -> None:
<add> clear_db_pools()
<add>
<add> def test_serialize(self):
<add> pool_model_a = Pool(pool="test_pool_a", slots=3)
<add> pool_model_b = Pool(pool="test_pool_b", slots=3)
<add> instance = PoolCollection(pools=[pool_model_a, pool_model_b], total_entries=2)
<add> self.assertEqual(
<add> {
<add> "pools": [
<add> {
<add> "name": "test_pool_a",
<add> "slots": 3,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 3,
<add> },
<add> {
<add> "name": "test_pool_b",
<add> "slots": 3,
<add> "occupied_slots": 0,
<add> "running_slots": 0,
<add> "queued_slots": 0,
<add> "open_slots": 3,
<add> },
<add> ],
<add> "total_entries": 2,
<add> },
<add> pool_collection_schema.dump(instance).data,
<add> ) | 6 |
Python | Python | fix optimizer loading | fb0c96f39a1c3f8a2cec8844effab950c6503088 | <ide><path>spacy/language.py
<ide> def update(self, docs, golds, drop=0., sgd=None, losses=None):
<ide> return
<ide> if sgd is None:
<ide> if self._optimizer is None:
<del> self._optimizer = Optimizer(Model.ops, 0.001,
<del> beta1=0.9, beta2=0.0, nesterov=True)
<add> self._optimizer = Adam(Model.ops, 0.001)
<ide> sgd = self._optimizer
<ide> grads = {}
<ide> def get_grads(W, dW, key=None):
<ide> def resume_training(self, **cfg):
<ide> L2 = util.env_opt('L2_penalty', 1e-6)
<ide> max_grad_norm = util.env_opt('grad_norm_clip', 1.)
<ide> self._optimizer = Optimizer(Model.ops, learn_rate, L2=L2, beta1=beta1,
<del> beta2=beta2, eps=eps, nesterov=True)
<add> beta2=beta2, eps=eps)
<ide> self._optimizer.max_grad_norm = max_grad_norm
<ide> self._optimizer.device = device
<ide> return self._optimizer | 1 |
Python | Python | enable the tensorflow backend | c2407fdd88719eed66227815188b5908eca4b3a7 | <ide><path>transformers/pipelines.py
<ide> def __call__(self, *texts, **kwargs):
<ide> texts = [(text['question'], text['context']) for text in texts]
<ide>
<ide> inputs = self.tokenizer.batch_encode_plus(
<del> # texts, add_special_tokens=True, return_tensors='tf' if is_tf_available() else 'pt'
<del> texts, add_special_tokens=True, return_tensors='pt'
<add> texts, add_special_tokens=True, return_tensors='tf' if is_tf_available() else 'pt'
<ide> )
<ide>
<ide> # Remove special_tokens_mask to avoid KeyError
<ide> def __call__(self, *texts, **kwargs):
<ide> # TODO : Harmonize model arguments across all model
<ide> inputs['attention_mask'] = inputs.pop('encoder_attention_mask')
<ide>
<del> # if is_tf_available():
<del> if False:
<add> if is_tf_available():
<ide> # TODO trace model
<ide> start, end = self.model(inputs)
<add> start, end = start.numpy(), end.numpy()
<ide> else:
<ide> import torch
<ide> with torch.no_grad():
<ide> def decode(self, start: np.ndarray, end: np.ndarray, topk: int, max_answer_len:
<ide> # Remove candidate with end < start and end - start > max_answer_len
<ide> candidates = np.tril(np.triu(outer), max_answer_len - 1)
<ide>
<del> # start = np.max(candidates, axis=2).argmax(-1)
<del> # end = np.max(candidates, axis=1).argmax(-1)
<del>
<add> # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
<ide> scores_flat = candidates.flatten()
<ide> if topk == 1:
<ide> idx_sort = [np.argmax(scores_flat)]
<ide> def span_to_answer(self, text: str, start: int, end: int):
<ide> },
<ide> 'question-answering': {
<ide> 'impl': QuestionAnsweringPipeline,
<del> # 'tf': TFAutoModelForQuestionAnswering if is_tf_available() else None,
<add> 'tf': TFAutoModelForQuestionAnswering if is_tf_available() else None,
<ide> 'pt': AutoModelForQuestionAnswering if is_torch_available() else None
<ide> }
<ide> }
<ide> def pipeline(task: str, model, tokenizer: Optional[Union[str, PreTrainedTokenize
<ide> raise KeyError("Unknown task {}, available tasks are {}".format(task, list(SUPPORTED_TASKS.keys())))
<ide>
<ide> targeted_task = SUPPORTED_TASKS[task]
<del> # task, allocator = targeted_task['impl'], targeted_task['tf'] if is_tf_available() else targeted_task['pt']
<del> task, allocator = targeted_task['impl'], targeted_task['pt']
<add> task, allocator = targeted_task['impl'], targeted_task['tf'] if is_tf_available() else targeted_task['pt']
<ide>
<ide> model = allocator.from_pretrained(model)
<ide> return task(model, tokenizer, **kwargs) | 1 |
Python | Python | fix minor typo | fa29f7dd1fd8878368f885c4d62f9b92ff3382ea | <ide><path>rest_framework/serializers.py
<ide> def get_field_names(self, declared_fields, info):
<ide> # If `Meta.exclude` is included, then remove those fields.
<ide> for field_name in exclude:
<ide> assert field_name in fields, (
<del> "The field '{field_name}' was include on serializer "
<add> "The field '{field_name}' was included on serializer "
<ide> "{serializer_class} in the 'exclude' option, but does "
<ide> "not match any model field.".format(
<ide> field_name=field_name, | 1 |
Ruby | Ruby | add vs code to list of fallback editors | 84a7c2ba7d1b45764cc5381f67d63eec1448de9f | <ide><path>Library/Homebrew/utils.rb
<ide> def which_editor
<ide> editor = Homebrew::EnvConfig.editor
<ide> return editor if editor
<ide>
<del> # Find Atom, Sublime Text, Textmate, BBEdit / TextWrangler, or vim
<del> editor = %w[atom subl mate edit vim].find do |candidate|
<add> # Find Atom, Sublime Text, VS Code, Textmate, BBEdit / TextWrangler, or vim
<add> editor = %w[atom subl code mate edit vim].find do |candidate|
<ide> candidate if which(candidate, ENV["HOMEBREW_PATH"])
<ide> end
<ide> editor ||= "vim" | 1 |
Text | Text | move @fishrock123 to a previous releaser | 4d6c861800cc6ac1dc6a0fd9d3a8b0053baec62a | <ide><path>README.md
<ide> GPG keys used to sign Node.js releases:
<ide> `77984A986EBC2AA786BC0F66B01FBB92821C587A`
<ide> * **James M Snell** <jasnell@keybase.io>
<ide> `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1`
<del>* **Jeremiah Senkpiel** <fishrock@keybase.io>
<del>`FD3A5288F042B6850C66B31F09FE44734EB7990E`
<ide> * **Michaël Zasso** <targos@protonmail.com>
<ide> `8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600`
<ide> * **Myles Borins** <myles.borins@gmail.com>
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys B9AE9905FFD7803F25714661B63B535A4C206CA9
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 77984A986EBC2AA786BC0F66B01FBB92821C587A
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1
<del>gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
<ide> use these keys to verify a downloaded file.
<ide>
<ide> Other keys used to sign some previous releases:
<ide>
<add>* **Jeremiah Senkpiel** <fishrock@keybase.io>
<add>`FD3A5288F042B6850C66B31F09FE44734EB7990E`
<ide> * **Chris Dickinson** <christopher.s.dickinson@gmail.com>
<ide> `9554F04D7259F04124DE6B476D5A82AC7E37093B`
<ide> * **Isaac Z. Schlueter** <i@izs.me> | 1 |
Javascript | Javascript | fix 404 for warning urls | bbb272f3aae322bf2b13db862356d78957bafac7 | <ide><path>www/gatsby-node.js
<ide> exports.createPages = async ({graphql, boundActionCreators}) => {
<ide> slug.includes('community/') ||
<ide> slug.includes('contributing/') ||
<ide> slug.includes('docs/') ||
<del> slug.includes('tutorial/')
<add> slug.includes('tutorial/') ||
<add> slug.includes('warnings/')
<ide> ) {
<ide> let template;
<ide> if (slug.includes('blog/')) {
<ide> template = blogTemplate;
<ide> } else if (slug.includes('community/')) {
<ide> template = communityTemplate;
<del> } else if (slug.includes('contributing/') || slug.includes('docs/')) {
<add> } else if (
<add> slug.includes('contributing/') ||
<add> slug.includes('docs/') ||
<add> slug.includes('warnings/')
<add> ) {
<ide> template = docsTemplate;
<ide> } else if (slug.includes('tutorial/')) {
<ide> template = tutorialTemplate;
<ide><path>www/src/layouts/index.js
<ide> class Template extends Component {
<ide> // TODO - is there a better way to check if we need we have a sidebar?
<ide> let layoutHasSidebar = false;
<ide> if (
<del> location.pathname.match(/^\/(docs|tutorial|community|blog|contributing)/)
<add> location.pathname.match(
<add> /^\/(docs|tutorial|community|blog|contributing|warnings)/,
<add> )
<ide> ) {
<ide> layoutHasSidebar = true;
<ide> } | 2 |
Python | Python | update tf whisper doc tests | 8e4ee28e34466ca8355d014e2e1302df6b1e03f9 | <ide><path>src/transformers/models/whisper/modeling_tf_whisper.py
<ide> def call(
<ide> >>> model = TFWhisperModel.from_pretrained("openai/whisper-base")
<ide> >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
<ide> >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
<del> >>> inputs = feature_extractor(
<del> ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="tf"
<del> ... )
<add> >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="tf")
<ide> >>> input_features = inputs.input_features
<ide> >>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id
<ide> >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
<ide> def call(
<ide> >>> model = TFWhisperModel.from_pretrained("openai/whisper-base")
<ide> >>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
<ide> >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
<del> >>> inputs = feature_extractor(
<del> ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="tf"
<del> ... )
<add> >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="tf")
<ide> >>> input_features = inputs.input_features
<ide> >>> decoder_input_ids = tf.convert_to_tensor([[1, 1]]) * model.config.decoder_start_token_id
<ide> >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
<ide> def call(
<ide> >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="tf")
<ide> >>> input_features = inputs.input_features
<ide>
<del> >>> generated_ids = model.generate(inputs=input_features)
<add> >>> generated_ids = model.generate(input_ids=input_features)
<ide>
<ide> >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
<ide> >>> transcription | 1 |
Javascript | Javascript | improve console tests | 7809f386b03d6f2f570fe41060a7ef6e158f5cdb | <ide><path>test/parallel/test-console-assign-undefined.js
<ide> 'use strict';
<ide>
<del>// Should be above require, because code in require read console
<del>// what we are trying to avoid
<del>// set should be earlier than get
<add>// Patch global.console before importing modules that may modify the console
<add>// object.
<ide>
<del>global.console = undefined;
<add>const tmp = global.console;
<add>global.console = 42;
<ide>
<del>// Initially, the `console` variable is `undefined`, since console will be
<del>// lazily loaded in the getter.
<del>
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide>
<del>// global.console's getter is called
<del>// Since the `console` cache variable is `undefined` and therefore false-y,
<del>// the getter still calls NativeModule.require() and returns the object
<del>// obtained from it, instead of returning `undefined` as expected.
<add>// Originally the console had a getter. Test twice to verify it had no side
<add>// effect.
<add>assert.strictEqual(global.console, 42);
<add>assert.strictEqual(global.console, 42);
<ide>
<del>assert.strictEqual(global.console, undefined, 'first read');
<del>assert.strictEqual(global.console, undefined, 'second read');
<add>common.expectsError(
<add> () => console.log('foo'),
<add> {
<add> type: TypeError,
<add> message: 'console.log is not a function'
<add> }
<add>);
<ide>
<ide> global.console = 1;
<del>assert.strictEqual(global.console, 1, 'set true-like primitive');
<add>assert.strictEqual(global.console, 1);
<add>assert.strictEqual(console, 1);
<ide>
<del>global.console = 0;
<del>assert.strictEqual(global.console, 0, 'set false-like primitive, again');
<add>// Reset the console
<add>global.console = tmp;
<add>console.log('foo');
<ide><path>test/parallel/test-console-is-a-namespace.js
<ide> assert.doesNotThrow(() => {
<ide>
<ide> const self = global;
<ide>
<del>/* eslint-disable */
<del>/* The following tests are copied from */
<add>/* eslint-disable quotes, max-len */
<add>
<add>/* The following tests should not be modified as they are copied */
<ide> /* WPT Refs:
<ide> https://github.com/w3c/web-platform-tests/blob/40e451c/console/console-is-a-namespace.any.js
<ide> License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
<ide> test(() => {
<ide> assert_false("Console" in self);
<ide> }, "Console (uppercase, as if it were an interface) must not exist");
<ide>
<add>test(() => {
<add> const prototype1 = Object.getPrototypeOf(console);
<add> const prototype2 = Object.getPrototypeOf(prototype1);
<ide>
<del>// test(() => {
<del>// const prototype1 = Object.getPrototypeOf(console);
<del>// const prototype2 = Object.getPrototypeOf(prototype1);
<add> // This got commented out from the original test because in Node.js all
<add> // functions are declared on the prototype.
<add> // assert_equals(Object.getOwnPropertyNames(prototype1).length, 0, "The [[Prototype]] must have no properties");
<add> assert_equals(prototype2, Object.prototype, "The [[Prototype]]'s [[Prototype]] must be %ObjectPrototype%");
<add>}, "The prototype chain must be correct");
<ide>
<del>// assert_equals(Object.getOwnPropertyNames(prototype1).length, 0, "The [[Prototype]] must have no properties");
<del>// assert_equals(prototype2, Object.prototype, "The [[Prototype]]'s [[Prototype]] must be %ObjectPrototype%");
<del>// }, "The prototype chain must be correct");
<ide> /* eslint-enable */ | 2 |
Python | Python | remove irrelevant code in convolutional | af84a6879d2496f97244474dfe0284b50f2edf28 | <ide><path>keras/layers/convolutional.py
<ide> def get_config(self):
<ide> return {"name": self.__class__.__name__,
<ide> "stride": self.stride,
<ide> "pool_length": self.pool_length,
<del> "ignore_border": self.ignore_border,
<del> "subsample_length": self.subsample_length}
<add> "ignore_border": self.ignore_border}
<ide>
<ide>
<ide> class MaxPooling2D(Layer): | 1 |
Ruby | Ruby | update info on browser connection limits [ci skip] | 0d8b552c684b25c2c8993ddd3430434fec890b16 | <ide><path>actionview/lib/action_view/helpers/asset_url_helper.rb
<ide> module Helpers
<ide> # stylesheet_link_tag("application")
<ide> # # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" />
<ide> #
<del> # Browsers typically open at most two simultaneous connections to a single
<del> # host, which means your assets often have to wait for other assets to finish
<del> # downloading. You can alleviate this by using a <tt>%d</tt> wildcard in the
<del> # +asset_host+. For example, "assets%d.example.com". If that wildcard is
<del> # present Rails distributes asset requests among the corresponding four hosts
<del> # "assets0.example.com", ..., "assets3.example.com". With this trick browsers
<del> # will open eight simultaneous connections rather than two.
<add> # Browsers open a limited number of simulataneous connections to a single
<add> # host. The exact number varies by browser and version. This limit may cause
<add> # some asset downloads to wait for previous assets to finish before they can
<add> # begin. You can use the <tt>%d</tt> wildcard in the +asset_host+ to
<add> # distribute the requests over four hosts. For example,
<add> # <tt>assets%d.example.com<tt> will spread the asset requests over
<add> # "assets0.example.com", ..., "assets3.example.com".
<ide> #
<ide> # image_tag("rails.png")
<ide> # # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" />
<ide> # stylesheet_link_tag("application")
<ide> # # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" />
<ide> #
<del> # To do this, you can either setup four actual hosts, or you can use wildcard
<del> # DNS to CNAME the wildcard to a single asset host. You can read more about
<del> # setting up your DNS CNAME records from your ISP.
<add> # This may improve the asset loading performance of your application.
<add> # It is also possible the combination of additional connection overhead
<add> # (DNS, SSL) and the overall browser connection limits may result in this
<add> # solution being slower. You should be sure to measure your actual
<add> # performance across targeted browers both before and after this change.
<add> #
<add> # To implement the corresponding hosts you can either setup four actual
<add> # hosts or use wildcard DNS to CNAME the wilcard to a single asset host.
<add> # You can read more about setting up your DNS CNAME records from your ISP.
<ide> #
<ide> # Note: This is purely a browser performance optimization and is not meant
<ide> # for server load balancing. See http://www.die.net/musings/page_load_time/
<del> # for background.
<add> # for background and http://www.browserscope.org/?category=network for
<add> # connection limit data.
<ide> #
<ide> # Alternatively, you can exert more control over the asset host by setting
<ide> # +asset_host+ to a proc like this: | 1 |
Mixed | Text | reduce the memory footprint of fixtures accessors | 05d80fc24f03ca5310931eacefdc247a393dd861 | <ide><path>activerecord/CHANGELOG.md
<add>* Reduce the memory footprint of fixtures accessors.
<add>
<add> Until now fixtures accessors were eagerly defined using `define_method`.
<add> So the memory usage was directly dependent of the number of fixtures and
<add> test suites.
<add>
<add> Instead fixtures accessors are now implemented with `method_missing`,
<add> so they incur much less memory and CPU overhead.
<add>
<add> *Jean Boussier*
<add>
<ide> * Fix `config.active_record.destroy_association_async_job` configuration
<ide>
<ide> `config.active_record.destroy_association_async_job` should allow
<ide><path>activerecord/lib/active_record/test_fixtures.rb
<ide> def after_teardown # :nodoc:
<ide> class_attribute :use_instantiated_fixtures, default: false # true, false, or :no_instances
<ide> class_attribute :pre_loaded_fixtures, default: false
<ide> class_attribute :lock_threads, default: true
<add> class_attribute :fixture_sets, default: {}
<ide> end
<ide>
<ide> module ClassMethods
<ide> def fixtures(*fixture_set_names)
<ide>
<ide> def setup_fixture_accessors(fixture_set_names = nil)
<ide> fixture_set_names = Array(fixture_set_names || fixture_table_names)
<del> methods = Module.new do
<add> unless fixture_set_names.empty?
<add> self.fixture_sets = fixture_sets.dup
<ide> fixture_set_names.each do |fs_name|
<del> fs_name = fs_name.to_s
<del> accessor_name = fs_name.tr("/", "_").to_sym
<del>
<del> define_method(accessor_name) do |*fixture_names|
<del> force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
<del> return_single_record = fixture_names.size == 1
<del> fixture_names = @loaded_fixtures[fs_name].fixtures.keys if fixture_names.empty?
<del>
<del> @fixture_cache[fs_name] ||= {}
<del>
<del> instances = fixture_names.map do |f_name|
<del> f_name = f_name.to_s if f_name.is_a?(Symbol)
<del> @fixture_cache[fs_name].delete(f_name) if force_reload
<del>
<del> if @loaded_fixtures[fs_name][f_name]
<del> @fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
<del> else
<del> raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
<del> end
<del> end
<del>
<del> return_single_record ? instances.first : instances
<del> end
<del> private accessor_name
<add> key = fs_name.match?(%r{/}) ? -fs_name.to_s.tr("/", "_") : fs_name
<add> key = -key.to_s if key.is_a?(Symbol)
<add> fs_name = -fs_name.to_s if fs_name.is_a?(Symbol)
<add> fixture_sets[key] = fs_name
<ide> end
<ide> end
<del> include methods
<ide> end
<ide>
<ide> def uses_transaction(*methods)
<ide> def instantiate_fixtures
<ide> def load_instances?
<ide> use_instantiated_fixtures != :no_instances
<ide> end
<add>
<add> def method_missing(name, *args, **kwargs, &block)
<add> if fs_name = fixture_sets[name.to_s]
<add> access_fixture(fs_name, *args, **kwargs, &block)
<add> else
<add> super
<add> end
<add> end
<add>
<add> def respond_to_missing?(name, include_private = false)
<add> if include_private && fixture_sets.key?(name.to_s)
<add> true
<add> else
<add> super
<add> end
<add> end
<add>
<add> def access_fixture(fs_name, *fixture_names)
<add> force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload
<add> return_single_record = fixture_names.size == 1
<add>
<add> fixture_names = @loaded_fixtures[fs_name].fixtures.keys if fixture_names.empty?
<add> @fixture_cache[fs_name] ||= {}
<add>
<add> instances = fixture_names.map do |f_name|
<add> f_name = f_name.to_s if f_name.is_a?(Symbol)
<add> @fixture_cache[fs_name].delete(f_name) if force_reload
<add>
<add> if @loaded_fixtures[fs_name][f_name]
<add> @fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find
<add> else
<add> raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'"
<add> end
<add> end
<add>
<add> return_single_record ? instances.first : instances
<add> end
<ide> end
<ide> end | 2 |
PHP | PHP | port the inflector fixes from to 3.0 | 64fef6a7199e8010375477bbc3c899338b905241 | <ide><path>src/Utility/Inflector.php
<ide> public static function humanize($string, $delimiter = '_')
<ide> $result = static::_cache($cacheKey, $string);
<ide>
<ide> if ($result === false) {
<del> $result = ucwords(str_replace($delimiter, ' ', $string));
<add> $result = explode(' ', str_replace($delimiter, ' ', $string));
<add> foreach ($result as &$word) {
<add> $word = mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
<add> }
<add> $result = implode(' ', $result);
<ide> static::_cache($cacheKey, $string, $result);
<ide> }
<ide>
<ide> public static function delimit($string, $delimiter = '_')
<ide> $result = static::_cache($cacheKey, $string);
<ide>
<ide> if ($result === false) {
<del> $result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', $delimiter . '\\1', $string));
<add> $result = mb_strtolower(preg_replace('/(?<=\\w)([A-Z])/', $delimiter . '\\1', $string));
<ide> static::_cache($cacheKey, $string, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/Utility/InflectorTest.php
<ide> public function testUnderscore()
<ide> $this->assertSame('test_thing_extra', Inflector::underscore('TestThingExtra'));
<ide> $this->assertSame('test_thing_extra', Inflector::underscore('testThingExtra'));
<ide> $this->assertSame('test_this_thing', Inflector::underscore('test-this-thing'));
<add> $this->assertSame(Inflector::underscore('testThingExtrå'), 'test_thing_extrå');
<ide>
<ide> // Identical checks test the cache code path.
<ide> $this->assertSame('test_thing', Inflector::underscore('TestThing'));
<ide> $this->assertSame('test_thing', Inflector::underscore('testThing'));
<ide> $this->assertSame('test_thing_extra', Inflector::underscore('TestThingExtra'));
<ide> $this->assertSame('test_thing_extra', Inflector::underscore('testThingExtra'));
<add> $this->assertSame(Inflector::underscore('testThingExtrå'), 'test_thing_extrå');
<ide>
<ide> // Test stupid values
<ide> $this->assertSame('', Inflector::underscore(''));
<ide> public function testHumanization()
<ide> $this->assertEquals('File Systems', Inflector::humanize('file_systems'));
<ide> $this->assertSame('', Inflector::humanize(null));
<ide> $this->assertSame('', Inflector::humanize(false));
<add> $this->assertSame(Inflector::humanize('hello_wörld'), 'Hello Wörld');
<add> $this->assertSame(Inflector::humanize('福岡_city'), '福岡 City');
<ide> }
<ide>
<ide> /** | 2 |
Go | Go | change return value for validatemountmode | c99ed5ae5d0a9167ead73a798b02600ad40651f2 | <ide><path>daemon/volumes_unix.go
<ide> func parseBindMount(spec string, mountLabel string, config *runconfig.Config) (*
<ide> case 3:
<ide> bind.Destination = arr[1]
<ide> mode := arr[2]
<del> isValid, isRw := volume.ValidateMountMode(mode)
<del> if !isValid {
<add> if !volume.ValidMountMode(mode) {
<ide> return nil, fmt.Errorf("invalid mode for volumes-from: %s", mode)
<ide> }
<del> bind.RW = isRw
<add> bind.RW = volume.ReadWrite(mode)
<ide> // Mode field is used by SELinux to decide whether to apply label
<ide> bind.Mode = mode
<ide> default:
<ide> func parseVolumesFrom(spec string) (string, string, error) {
<ide>
<ide> if len(specParts) == 2 {
<ide> mode = specParts[1]
<del> if isValid, _ := volume.ValidateMountMode(mode); !isValid {
<add> if !volume.ValidMountMode(mode) {
<ide> return "", "", fmt.Errorf("invalid mode for volumes-from: %s", mode)
<ide> }
<ide> }
<ide><path>opts/opts.go
<ide> func validatePath(val string, validateMountMode bool) (string, error) {
<ide> containerPath = splited[0]
<ide> val = path.Clean(containerPath)
<ide> case 2:
<del> if isValid, _ := volume.ValidateMountMode(splited[1]); validateMountMode && isValid {
<add> if isValid := volume.ValidMountMode(splited[1]); validateMountMode && isValid {
<ide> containerPath = splited[0]
<ide> mode = splited[1]
<ide> val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode)
<ide> func validatePath(val string, validateMountMode bool) (string, error) {
<ide> case 3:
<ide> containerPath = splited[1]
<ide> mode = splited[2]
<del> if isValid, _ := volume.ValidateMountMode(splited[2]); validateMountMode && !isValid {
<add> if isValid := volume.ValidMountMode(splited[2]); validateMountMode && !isValid {
<ide> return val, fmt.Errorf("bad mount mode specified : %s", mode)
<ide> }
<ide> val = fmt.Sprintf("%s:%s:%s", splited[0], containerPath, mode)
<ide><path>volume/volume.go
<ide> var roModes = map[string]bool{
<ide> "Z,ro": true,
<ide> }
<ide>
<del>// ValidateMountMode will make sure the mount mode is valid.
<del>// returns if it's a valid mount mode and if it's read-write or not.
<del>func ValidateMountMode(mode string) (bool, bool) {
<del> return roModes[mode] || rwModes[mode], rwModes[mode]
<add>// ValidMountMode will make sure the mount mode is valid.
<add>// returns if it's a valid mount mode or not.
<add>func ValidMountMode(mode string) bool {
<add> return roModes[mode] || rwModes[mode]
<ide> }
<ide>
<del>// ReadWrite tells you if a mode string is a valid read-only mode or not.
<add>// ReadWrite tells you if a mode string is a valid read-write mode or not.
<ide> func ReadWrite(mode string) bool {
<ide> return rwModes[mode]
<ide> } | 3 |
Text | Text | correct the web socket url when creating consumer | 8a1ff2f41440b2ec6855ccf1e26c7b554eb95937 | <ide><path>guides/source/action_cable_overview.md
<ide> WebSocket is opened.
<ide>
<ide> ```js
<ide> // Specify a different URL to connect to
<add>createConsumer('wss://example.com/cable')
<add>// Or when using websockets over HTTP
<ide> createConsumer('https://ws.example.com/cable')
<ide>
<ide> // Use a function to dynamically generate the URL
<ide> createConsumer(getWebSocketURL)
<ide>
<ide> function getWebSocketURL() {
<ide> const token = localStorage.get('auth-token')
<del> return `https://ws.example.com/cable?token=${token}`
<add> return `wss://example.com/cable?token=${token}`
<ide> }
<ide> ```
<ide>
<ide> consumer.subscriptions.create("AppearanceChannel", {
<ide>
<ide> #### Client-Server Interaction
<ide>
<del>1. **Client** connects to the **Server** via `App.cable =
<del>ActionCable.createConsumer("ws://cable.example.com")`. (`cable.js`). The
<add>1. **Client** connects to the **Server** via `createConsumer()`. (`consumer.js`). The
<ide> **Server** identifies this connection by `current_user`.
<ide>
<ide> 2. **Client** subscribes to the appearance channel via | 1 |
Javascript | Javascript | fix shallow dependency resolution | 361f3f30d3ae2b48429a1738d309a2693c4a1038 | <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js
<ide> class ResolutionRequest {
<ide> const visited = Object.create(null);
<ide> visited[entry.hash()] = true;
<ide>
<add> response.pushDependency(entry);
<ide> const collect = (mod) => {
<del> response.pushDependency(mod);
<ide> return mod.getDependencies().then(
<ide> depNames => Promise.all(
<ide> depNames.map(name => this.resolveDependency(mod, name))
<ide> class ResolutionRequest {
<ide> p = p.then(() => {
<ide> if (!visited[modDep.hash()]) {
<ide> visited[modDep.hash()] = true;
<add> response.pushDependency(modDep);
<ide> if (recursive) {
<ide> return collect(modDep);
<ide> }
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> const mocksPattern = /(?:[\\/]|^)__mocks__[\\/]([^\/]+)\.js$/;
<ide> describe('DependencyGraph', function() {
<ide> let defaults;
<ide>
<del> function getOrderedDependenciesAsJSON(dgraph, entry, platform) {
<del> return dgraph.getDependencies(entry, platform)
<add> function getOrderedDependenciesAsJSON(dgraph, entry, platform, recursive = true) {
<add> return dgraph.getDependencies(entry, platform, recursive)
<ide> .then(response => response.finalize())
<ide> .then(({ dependencies }) => Promise.all(dependencies.map(dep => Promise.all([
<ide> dep.getName(),
<ide> describe('DependencyGraph', function() {
<ide> '/**',
<ide> ' * @providesModule a',
<ide> ' */',
<add> 'require("b")',
<add> ].join('\n'),
<add> 'b.js': [
<add> '/**',
<add> ' * @providesModule b',
<add> ' */',
<ide> ].join('\n'),
<ide> },
<ide> });
<ide> describe('DependencyGraph', function() {
<ide> {
<ide> id: 'a',
<ide> path: '/root/a.js',
<add> dependencies: ['b'],
<add> isAsset: false,
<add> isAsset_DEPRECATED: false,
<add> isJSON: false,
<add> isPolyfill: false,
<add> resolution: undefined,
<add> resolveDependency: undefined,
<add> },
<add> {
<add> id: 'b',
<add> path: '/root/b.js',
<ide> dependencies: [],
<ide> isAsset: false,
<ide> isAsset_DEPRECATED: false,
<ide> describe('DependencyGraph', function() {
<ide> });
<ide> });
<ide>
<add> pit('should get shallow dependencies', function() {
<add> var root = '/root';
<add> fs.__setMockFilesystem({
<add> 'root': {
<add> 'index.js': [
<add> '/**',
<add> ' * @providesModule index',
<add> ' */',
<add> 'require("a")',
<add> ].join('\n'),
<add> 'a.js': [
<add> '/**',
<add> ' * @providesModule a',
<add> ' */',
<add> 'require("b")',
<add> ].join('\n'),
<add> 'b.js': [
<add> '/**',
<add> ' * @providesModule b',
<add> ' */',
<add> ].join('\n'),
<add> },
<add> });
<add>
<add> var dgraph = new DependencyGraph({
<add> ...defaults,
<add> roots: [root],
<add> });
<add> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js', null, false).then(function(deps) {
<add> expect(deps)
<add> .toEqual([
<add> {
<add> id: 'index',
<add> path: '/root/index.js',
<add> dependencies: ['a'],
<add> isAsset: false,
<add> isAsset_DEPRECATED: false,
<add> isJSON: false,
<add> isPolyfill: false,
<add> resolution: undefined,
<add> },
<add> {
<add> id: 'a',
<add> path: '/root/a.js',
<add> dependencies: ['b'],
<add> isAsset: false,
<add> isAsset_DEPRECATED: false,
<add> isJSON: false,
<add> isPolyfill: false,
<add> resolution: undefined,
<add> },
<add> ]);
<add> });
<add> });
<add>
<ide> pit('should get dependencies with the correct extensions', function() {
<ide> var root = '/root';
<ide> fs.__setMockFilesystem({ | 2 |
Mixed | Ruby | remove special handling for activerecordstore | 27285e7881daa9ccf8b90be26027e1211722da3e | <ide><path>actionpack/lib/action_dispatch.rb
<ide> module Session
<ide> autoload :CookieStore, "action_dispatch/middleware/session/cookie_store"
<ide> autoload :MemCacheStore, "action_dispatch/middleware/session/mem_cache_store"
<ide> autoload :CacheStore, "action_dispatch/middleware/session/cache_store"
<add>
<add> def self.resolve_store(session_store) # :nodoc:
<add> self.const_get(session_store.to_s.camelize)
<add> rescue NameError
<add> raise <<~ERROR
<add> Unable to resolve session store #{session_store.inspect}.
<add>
<add> #{session_store.inspect} resolves to ActionDispatch::Session::#{session_store.to_s.camelize},
<add> but that class is undefined.
<add>
<add> Is #{session_store.inspect} spelled correctly, and are any necessary gems installed?
<add> ERROR
<add> end
<ide> end
<ide>
<ide> mattr_accessor :test_app
<ide><path>guides/source/action_controller_overview.md
<ide> Your application has a session for each user in which you can store small amount
<ide>
<ide> * [`ActionDispatch::Session::CookieStore`][] - Stores everything on the client.
<ide> * [`ActionDispatch::Session::CacheStore`][] - Stores the data in the Rails cache.
<del>* `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record (requires the `activerecord-session_store` gem).
<ide> * [`ActionDispatch::Session::MemCacheStore`][] - Stores the data in a memcached cluster (this is a legacy implementation; consider using `CacheStore` instead).
<add>* [`ActionDispatch::Session::ActiveRecordStore`][activerecord-session_store] -
<add> Stores the data in a database using Active Record (requires the
<add> [`activerecord-session_store`][activerecord-session_store] gem)
<add>* A custom store or a store provided by a third party gem
<ide>
<ide> All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
<ide>
<ide> Read more about session storage in the [Security Guide](security.html).
<ide> If you need a different session storage mechanism, you can change it in an initializer:
<ide>
<ide> ```ruby
<del># Use the database for sessions instead of the cookie-based default,
<del># which shouldn't be used to store highly confidential information
<del># (create the session table with "rails g active_record:session_migration")
<del># Rails.application.config.session_store :active_record_store
<add>Rails.application.config.session_store :cache_store
<ide> ```
<ide>
<add>See [`config.session_store`](configuring.html#config-session-store) in the
<add>configuration guide for more information.
<add>
<ide> Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:
<ide>
<ide> ```ruby
<ide> NOTE: Changing the secret_key_base when using the `CookieStore` will invalidate
<ide> [`ActionDispatch::Session::CookieStore`]: https://api.rubyonrails.org/classes/ActionDispatch/Session/CookieStore.html
<ide> [`ActionDispatch::Session::CacheStore`]: https://api.rubyonrails.org/classes/ActionDispatch/Session/CacheStore.html
<ide> [`ActionDispatch::Session::MemCacheStore`]: https://api.rubyonrails.org/classes/ActionDispatch/Session/MemCacheStore.html
<add>[activerecord-session_store]: https://github.com/rails/activerecord-session_store
<add>
<ide>
<ide> ### Accessing the Session
<ide>
<ide><path>railties/lib/rails/application/configuration.rb
<ide> def colorize_logging=(val)
<ide>
<ide> # Specifies what class to use to store the session. Possible values
<ide> # are +:cache_store+, +:cookie_store+, +:mem_cache_store+, a custom
<del> # store, or +:disabled+. +:disabled+ tells Rails not to deal with
<add> # store, or +:disabled+. +:disabled+ tells \Rails not to deal with
<ide> # sessions.
<ide> #
<ide> # Additional options will be set as +session_options+:
<ide> def colorize_logging=(val)
<ide> # config.session_store :my_custom_store
<ide> def session_store(new_session_store = nil, **options)
<ide> if new_session_store
<del> if new_session_store == :active_record_store
<del> begin
<del> ActionDispatch::Session::ActiveRecordStore
<del> rescue NameError
<del> raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \
<del> "Please add `activerecord-session_store` to your Gemfile to use it."
<del> end
<del> end
<del>
<ide> @session_store = new_session_store
<ide> @session_options = options || {}
<ide> else
<ide> case @session_store
<ide> when :disabled
<ide> nil
<del> when :active_record_store
<del> ActionDispatch::Session::ActiveRecordStore
<ide> when Symbol
<del> ActionDispatch::Session.const_get(@session_store.to_s.camelize)
<add> ActionDispatch::Session.resolve_store(@session_store)
<ide> else
<ide> @session_store
<ide> end
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> ActionDispatch::Session.send :remove_const, :ActiveRecordStore
<ide> end
<ide>
<del> test "config.session_store with :active_record_store without activerecord-session_store gem" do
<add> test "config.session_store with unknown store raises helpful error" do
<ide> e = assert_raise RuntimeError do
<ide> make_basic_app do |application|
<del> application.config.session_store :active_record_store
<add> application.config.session_store :unknown_store
<ide> end
<ide> end
<del> assert_match(/activerecord-session_store/, e.message)
<add>
<add> assert_match(/Unable to resolve session store :unknown_store/, e.message)
<ide> end
<ide>
<ide> test "default session store initializer does not overwrite the user defined session store even if it is disabled" do | 4 |
Ruby | Ruby | use lib helper | 24d8791dfbf21c5f536f555e6ccb8ee9d6ba19c0 | <ide><path>Library/Homebrew/keg_fix_install_names.rb
<ide> def install_names_for file, options, reject_proc=default_reject_proc
<ide> end
<ide>
<ide> def find_dylib name
<del> (join 'lib').find do |pn|
<del> break pn if pn.basename == Pathname.new(name)
<del> end
<add> lib.find { |pn| break pn if pn.basename == Pathname.new(name) }
<ide> end
<ide>
<ide> def mach_o_files
<ide> def libtool_files
<ide> libtool_files = []
<ide>
<ide> # find .la files, which are stored in lib/
<del> la_dir = self/'lib'
<del> la_dir.find do |pn|
<add> lib.find do |pn|
<ide> next if pn.symlink? or pn.directory? or pn.extname != '.la'
<ide> libtool_files << pn
<ide> end | 1 |
Ruby | Ruby | reuse available belongs_to? method | 3ef8d536855075c6b7f1b15d150b701f63d1111c | <ide><path>activerecord/lib/active_record/associations/has_many_through_association.rb
<ide> def build_record(attributes)
<ide> end
<ide>
<ide> def target_reflection_has_associated_record?
<del> !(through_reflection.macro == :belongs_to && owner[through_reflection.foreign_key].blank?)
<add> !(through_reflection.belongs_to? && owner[through_reflection.foreign_key].blank?)
<ide> end
<ide>
<ide> def update_through_counter?(method)
<ide><path>activerecord/lib/active_record/associations/through_association.rb
<ide> def construct_join_attributes(*records)
<ide> # Note: this does not capture all cases, for example it would be crazy to try to
<ide> # properly support stale-checking for nested associations.
<ide> def stale_state
<del> if through_reflection.macro == :belongs_to
<add> if through_reflection.belongs_to?
<ide> owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s
<ide> end
<ide> end
<ide>
<ide> def foreign_key_present?
<del> through_reflection.macro == :belongs_to &&
<del> !owner[through_reflection.foreign_key].nil?
<add> through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil?
<ide> end
<ide>
<ide> def ensure_mutable
<ide><path>activerecord/lib/active_record/relation/calculations.rb
<ide> def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
<ide>
<ide> if group_attrs.first.respond_to?(:to_sym)
<ide> association = @klass._reflect_on_association(group_attrs.first.to_sym)
<del> associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
<add> associated = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations
<ide> group_fields = Array(associated ? association.foreign_key : group_attrs)
<ide> else
<ide> group_fields = group_attrs | 3 |
Text | Text | add xray goals | 83ad524ddf5b693b286e028e64dde409c953abb5 | <ide><path>docs/focus/2018-02-12.md
<ide> - Use fuzzy-finder support internally in our day-to-day workflows to assess usability
<ide> - Treesitter
<ide> - Xray
<add> * @nathansobo (and @as-cii part time) will be focusing the next 12 weeks on a prototype for [a new Electron-based text editor](https://github.com/atom/xray). The goal is to explore the viability of radical performance improvements that could be possible if we make breaking changes to Atom's APIs. At the end of the 12 weeks, we will reassess our plans based on what we have managed to learn and accomplish.
<add> * Week 1 of 12
<add> * Clarify and document goals for the next 12 weeks.
<add> * Ensure that the guide matches our current plans.
<add> * Refine WebGL based text rendering.
<add> * Make sure ASCII text renders correctly without being clipped
<add> * Render text correctly on high DPI displays
<add> * Use correct API for texture atlas updates
<add> * Add mouse-wheel scrolling support
<add> * Non-ASCII rendering, using the HarfBuzz text shaping library to detect combining characters
<add> * Stretch goal: Switch document encoding to UTF-8 for memory compactness and support multi-byte-aware character indexing. | 1 |
Python | Python | add trunc test | b2d4064b4dc4373d8a94d7b1b87eab3f75f430f3 | <ide><path>numpy/core/tests/test_ufunc.py
<ide> def test_all_ufunc(self) :
<ide> n 1 log1p flts + M
<ide> n 1 sqrt flts + M real x < 0 raises error
<ide> n 1 ceil real + M
<add> n 1 trunc real + M
<ide> n 1 floor real + M
<ide> n 1 fabs real + M
<ide> n 1 rint flts + M | 1 |
Ruby | Ruby | check `tap_audit_exception` only if tap is present | 55cc1eb8b098283cd280cf91974890fadcf808f4 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_binary_arches(formula)
<ide> end
<ide> mismatches -= compatible_universal_binaries
<ide>
<del> universal_binaries_expected = tap_audit_exception(:universal_binary_allowlist, formula.name)
<add> universal_binaries_expected =
<add> formula.tap.present? && tap_audit_exception(:universal_binary_allowlist, formula.name)
<ide> return if mismatches.empty? && universal_binaries_expected
<ide>
<ide> s = "" | 1 |
Ruby | Ruby | add broken test, revealing test helper flaw | cad8be3278923c926df2424b7a22be489ed03ded | <ide><path>Library/Homebrew/test/cask/config_spec.rb
<ide> end
<ide>
<ide> context "when installing a cask and then adding a global default dir" do
<del> let(:config) { described_class.new(default: { appdir: "/default/path/before/adding/fontdir" }) }
<add> let(:config) {
<add> json = <<~EOS
<add> {
<add> "default": {
<add> "appdir": "/default/path/before/adding/fontdir"
<add> },
<add> "env": {},
<add> "explicit": {}
<add> }
<add> EOS
<add> described_class.from_json(json)
<add> }
<ide>
<ide> describe "#appdir" do
<ide> it "honors metadata of the installed cask" do | 1 |
Python | Python | fix view_name argument to hyperlinkedidentityfield | 2a89cb4fb7aac72a02ad17704553fe7dfb3ea10e | <ide><path>rest_framework/fields.py
<ide> class HyperlinkedIdentityField(Field):
<ide> def __init__(self, *args, **kwargs):
<ide> # TODO: Make this mandatory
<ide> self.view_name = kwargs.pop('view_name', None)
<del> super(HyperlinkedRelatedField, self).__init__(*args, **kwargs)
<add> super(HyperlinkedIdentityField, self).__init__(*args, **kwargs)
<ide>
<ide> def field_to_native(self, obj, field_name):
<ide> request = self.context.get('request', None) | 1 |
Java | Java | update copyright date | fba92c012042a48443a169cf3f42dabb542aa8c1 | <ide><path>spring-test/src/main/java/org/springframework/mock/env/MockEnvironment.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/cache/DefaultCacheAwareContextLoaderDelegate.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/transaction/TestContextTransactionUtils.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/context/web/socket/MockServerContainerContextCustomizer.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/web/client/response/DefaultResponseCreator.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 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><path>spring-test/src/main/java/org/springframework/test/web/servlet/client/AbstractMockMvcServerSpec.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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. | 9 |
PHP | PHP | add hints for artisan facade methods | 00d1aeb38f319f6621cbda88f6f90c445880af3f | <ide><path>src/Illuminate/Support/Facades/Artisan.php
<ide> use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
<ide>
<ide> /**
<del> * @method static int handle(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output = null)
<del> * @method static int call(string $command, array $parameters = [], $outputBuffer = null)
<del> * @method static int queue(string $command, array $parameters = [])
<add> * @method static int handle(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface|null $output = null)
<add> * @method static int call(string $command, array $parameters = [], \Symfony\Component\Console\Output\OutputInterface|null $outputBuffer = null)
<add> * @method static \Illuminate\Foundation\Bus\PendingDispatch queue(string $command, array $parameters = [])
<ide> * @method static array all()
<ide> * @method static string output()
<add> * @method static void terminate(\Symfony\Component\Console\Input\InputInterface $input, int $status)
<ide> *
<ide> * @see \Illuminate\Contracts\Console\Kernel
<ide> */ | 1 |
Text | Text | fix errors in sample code comments | 3bd6d8d7f544164728ff4cfd2c37cff4877a8cb1 | <ide><path>doc/api/buffer.md
<ide> console.log(buf.readDoubleBE(0));
<ide> console.log(buf.readDoubleLE(0));
<ide> // Prints: 5.447603722011605e-270
<ide> console.log(buf.readDoubleLE(1));
<del>// Throws an exception: RangeError: Index out of range
<del>console.log(buf.readDoubleLE(1, true));
<del>// Warning: reads passed end of buffer!
<del>// This will result in a segmentation fault! Don't do this!
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readFloatBE(offset)
<ide> console.log(buf.readFloatBE(0));
<ide> console.log(buf.readFloatLE(0));
<ide> // Prints: 1.539989614439558e-36
<ide> console.log(buf.readFloatLE(1));
<del>// Throws an exception: RangeError: Index out of range
<del>console.log(buf.readFloatLE(1, true));
<del>// Warning: reads passed end of buffer!
<del>// This will result in a segmentation fault! Don't do this!
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readInt8(offset)
<ide> console.log(buf.readInt8(0));
<ide> console.log(buf.readInt8(1));
<ide> // Prints: 5
<ide> console.log(buf.readInt8(2));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readInt16BE(offset)
<ide> console.log(buf.readInt16BE(0));
<ide> console.log(buf.readInt16LE(0));
<ide> // Prints: 1280
<ide> console.log(buf.readInt16LE(1));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readInt32BE(offset)
<ide> console.log(buf.readInt32BE(0));
<ide> console.log(buf.readInt32LE(0));
<ide> // Prints: 83886080
<ide> console.log(buf.readInt32LE(1));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readIntBE(offset, byteLength)
<ide> console.log(buf.readIntLE(0, 6).toString(16));
<ide> console.log(buf.readIntBE(0, 6).toString(16));
<ide> // Prints: 1234567890ab
<ide> console.log(buf.readIntBE(1, 6).toString(16));
<del>// Throws ERR_INDEX_OUT_OF_RANGE:
<add>// Throws ERR_INDEX_OUT_OF_RANGE
<ide> console.log(buf.readIntBE(1, 0).toString(16));
<del>// Throws ERR_OUT_OF_RANGE:
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readUInt8(offset)
<ide> console.log(buf.readUInt8(0));
<ide> console.log(buf.readUInt8(1));
<ide> // Prints: 254
<ide> console.log(buf.readUInt8(2));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readUInt16BE(offset)
<ide> console.log(buf.readUInt16BE(1).toString(16));
<ide> console.log(buf.readUInt16LE(1).toString(16));
<ide> // Prints: 5634
<ide> console.log(buf.readUInt16LE(2).toString(16));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readUInt32BE(offset)
<ide> console.log(buf.readUInt32BE(0).toString(16));
<ide> console.log(buf.readUInt32LE(0).toString(16));
<ide> // Prints: 78563412
<ide> console.log(buf.readUInt32LE(1).toString(16));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.readUIntBE(offset, byteLength)
<ide> console.log(buf.readUIntBE(0, 6).toString(16));
<ide> console.log(buf.readUIntLE(0, 6).toString(16));
<ide> // Prints: ab9078563412
<ide> console.log(buf.readUIntBE(1, 6).toString(16));
<del>// Throws an exception: RangeError: Index out of range
<add>// Throws ERR_OUT_OF_RANGE
<ide> ```
<ide>
<ide> ### buf.slice([start[, end]])
<ide> console.log(buf1);
<ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]);
<ide>
<ide> buf2.swap16();
<del>// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits
<add>// Throws ERR_INVALID_BUFFER_SIZE
<ide> ```
<ide>
<ide> ### buf.swap32()
<ide> console.log(buf1);
<ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]);
<ide>
<ide> buf2.swap32();
<del>// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits
<add>// Throws ERR_INVALID_BUFFER_SIZE
<ide> ```
<ide>
<ide> ### buf.swap64()
<ide> console.log(buf1);
<ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]);
<ide>
<ide> buf2.swap64();
<del>// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits
<add>// Throws ERR_INVALID_BUFFER_SIZE
<ide> ```
<ide>
<ide> Note that JavaScript cannot encode 64-bit integers. This method is intended | 1 |
PHP | PHP | add missing deprecation note | 945ff040408273986b27f773563c0cf4856e443d | <ide><path>src/Database/Expression/ValuesExpression.php
<ide> public function getValues()
<ide> * Sets the values to be inserted. If no params are passed, then it returns
<ide> * the currently stored values
<ide> *
<add> * @deprecated 3.4.0 Use setValues()/getValues() instead.
<ide> * @param array|null $values Array with values to be inserted.
<ide> * @return array|self
<ide> */ | 1 |
Javascript | Javascript | add spec for settings | aaa4127332ae858ae5d3ea40d1fcfbbe9c3ef5b0 | <ide><path>Libraries/Settings/NativeSettingsManager.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +getConstants: () => {|
<add> settings: Object,
<add> |};
<add> +setValues: (values: Object) => void;
<add> +deleteValues: (values: Array<string>) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.getEnforcing<Spec>('SettingsManager');
<ide><path>Libraries/Settings/Settings.ios.js
<ide> 'use strict';
<ide>
<ide> const RCTDeviceEventEmitter = require('../EventEmitter/RCTDeviceEventEmitter');
<del>const RCTSettingsManager = require('../BatchedBridge/NativeModules')
<del> .SettingsManager;
<add>import NativeSettingsManager from './NativeSettingsManager';
<ide>
<ide> const invariant = require('invariant');
<ide>
<ide> const subscriptions: Array<{keys: Array<string>, callback: ?Function}> = [];
<ide>
<ide> const Settings = {
<del> _settings: RCTSettingsManager && RCTSettingsManager.settings,
<add> _settings:
<add> NativeSettingsManager && NativeSettingsManager.getConstants().settings,
<ide>
<ide> get(key: string): mixed {
<ide> return this._settings[key];
<ide> },
<ide>
<ide> set(settings: Object) {
<ide> this._settings = Object.assign(this._settings, settings);
<del> RCTSettingsManager.setValues(settings);
<add> NativeSettingsManager.setValues(settings);
<ide> },
<ide>
<ide> watchKeys(keys: string | Array<string>, callback: Function): number { | 2 |
Ruby | Ruby | allow 'brew install' on relative paths | 2e340625f83ad73ede4b9d1c15f8e5951fbe29fe | <ide><path>Library/Homebrew/formula.rb
<ide> def self.factory name
<ide> install_type = :from_url
<ide> else
<ide> # Check if this is a name or pathname
<del> path = Pathname.new(name)
<del> if path.absolute?
<del> # For absolute paths, just require the path
<add> if name.include? "/"
<add> # For paths, just require the path
<ide> require name
<add> path = Pathname.new(name)
<ide> name = path.stem
<ide> install_type = :from_path
<ide> target_file = path.to_s | 1 |
Text | Text | reorganize examples folder readme | 3c19add103066bc58970810e32050051ac1a7399 | <ide><path>examples/README.md
<ide> # Keras examples directory
<ide>
<del>[addition_rnn.py](addition_rnn.py)
<del>Implementation of sequence to sequence learning for performing addition of two numbers (as strings).
<add>## Vision models examples
<ide>
<del>[antirectifier.py](antirectifier.py)
<del>Demonstrates how to write custom layers for Keras.
<del>
<del>[babi_memnn.py](babi_memnn.py)
<del>Trains a memory network on the bAbI dataset for reading comprehension.
<add>[mnist_mlp.py](mnist_mlp.py)
<add>Trains a simple deep multi-layer perceptron on the MNIST dataset.
<ide>
<del>[babi_rnn.py](babi_rnn.py)
<del>Trains a two-branch recurrent network on the bAbI dataset for reading comprehension.
<add>[mnist_cnn.py](mnist_cnn.py)
<add>Trains a simple convnet on the MNIST dataset.
<ide>
<ide> [cifar10_cnn.py](cifar10_cnn.py)
<ide> Trains a simple deep CNN on the CIFAR10 small images dataset.
<ide>
<del>[conv_filter_visualization.py](conv_filter_visualization.py)
<del>Visualization of the filters of VGG16, via gradient ascent in input space.
<add>[cifar10_resnet.py](cifar10_resnet.py)
<add>Trains a ResNet on the CIFAR10 small images dataset.
<ide>
<ide> [conv_lstm.py](conv_lstm.py)
<ide> Demonstrates the use of a convolutional LSTM network.
<ide>
<del>[deep_dream.py](deep_dream.py)
<del>Deep Dreams in Keras.
<del>
<ide> [image_ocr.py](image_ocr.py)
<ide> Trains a convolutional stack followed by a recurrent stack and a CTC logloss function to perform optical character recognition (OCR).
<ide>
<add>[mnist_acgan.py](mnist_acgan.py)
<add>Implementation of AC-GAN (Auxiliary Classifier GAN) on the MNIST dataset
<add>
<add>[mnist_hierarchical_rnn.py](mnist_hierarchical_rnn.py)
<add>Trains a Hierarchical RNN (HRNN) to classify MNIST digits.
<add>
<add>[mnist_siamese.py](mnist_siamese.py)
<add>Trains a Siamese multi-layer perceptron on pairs of digits from the MNIST dataset.
<add>
<add>[mnist_swwae.py](mnist_swwae.py)
<add>Trains a Stacked What-Where AutoEncoder built on residual blocks on the MNIST dataset.
<add>
<add>[mnist_transfer_cnn.py](mnist_transfer_cnn.py)
<add>Transfer learning toy example.
<add>
<add>----
<add>
<add>## Text & sequences examples
<add>
<add>[addition_rnn.py](addition_rnn.py)
<add>Implementation of sequence to sequence learning for performing addition of two numbers (as strings).
<add>
<add>[babi_rnn.py](babi_rnn.py)
<add>Trains a two-branch recurrent network on the bAbI dataset for reading comprehension.
<add>
<add>[babi_memnn.py](babi_memnn.py)
<add>Trains a memory network on the bAbI dataset for reading comprehension.
<add>
<ide> [imdb_bidirectional_lstm.py](imdb_bidirectional_lstm.py)
<ide> Trains a Bidirectional LSTM on the IMDB sentiment classification task.
<ide>
<ide> Trains a FastText model on the IMDB sentiment classification task.
<ide> [imdb_lstm.py](imdb_lstm.py)
<ide> Trains an LSTM model on the IMDB sentiment classification task.
<ide>
<del>[lstm_text_generation.py](lstm_text_generation.py)
<del>Generates text from Nietzsche's writings.
<del>
<ide> [lstm_stateful.py](lstm_stateful.py)
<ide> Demonstrates how to use stateful RNNs to model long sequences efficiently.
<ide>
<del>[mnist_acgan.py](mnist_acgan.py)
<del>Implementation of AC-GAN ( Auxiliary Classifier GAN ) on the MNIST dataset
<del>
<del>[mnist_cnn.py](mnist_cnn.py)
<del>Trains a simple convnet on the MNIST dataset.
<del>
<del>[mnist_hierarchical_rnn.py](mnist_hierarchical_rnn.py)
<del>Trains a Hierarchical RNN (HRNN) to classify MNIST digits.
<del>
<del>[mnist_irnn.py](mnist_irnn.py)
<del>Reproduction of the IRNN experiment with pixel-by-pixel sequential MNIST in "A Simple Way to Initialize Recurrent Networks of Rectified Linear Units" by Le et al.
<del>
<del>[mnist_mlp.py](mnist_mlp.py)
<del>Trains a simple deep multi-layer perceptron on the MNIST dataset.
<add>[pretrained_word_embeddings.py](pretrained_word_embeddings.py)
<add>Loads pre-trained word embeddings (GloVe embeddings) into a frozen Keras Embedding layer, and uses it to train a text classification model on the 20 Newsgroup dataset.
<ide>
<del>[mnist_net2net.py](mnist_net2net.py)
<del>Reproduction of the Net2Net experiment with MNIST in "Net2Net: Accelerating Learning via Knowledge Transfer".
<add>[reuters_mlp.py](reuters_mlp.py)
<add>Trains and evaluate a simple MLP on the Reuters newswire topic classification task.
<ide>
<del>[mnist_siamese_graph.py](mnist_siamese_graph.py)
<del>Trains a Siamese multi-layer perceptron on pairs of digits from the MNIST dataset.
<add>----
<ide>
<del>[mnist_sklearn_wrapper.py](mnist_sklearn_wrapper.py)
<del>Demonstrates how to use the sklearn wrapper.
<add>## Generative models examples
<ide>
<del>[mnist_swwae.py](mnist_swwae.py)
<del>Trains a Stacked What-Where AutoEncoder built on residual blocks on the MNIST dataset.
<add>[lstm_text_generation.py](lstm_text_generation.py)
<add>Generates text from Nietzsche's writings.
<ide>
<del>[mnist_tfrecord.py](mnist_tfrecord.py)
<del>MNIST dataset with TFRecords, the standard TensorFlow data format.
<add>[conv_filter_visualization.py](conv_filter_visualization.py)
<add>Visualization of the filters of VGG16, via gradient ascent in input space.
<ide>
<del>[mnist_transfer_cnn.py](mnist_transfer_cnn.py)
<del>Transfer learning toy example.
<add>[deep_dream.py](deep_dream.py)
<add>Deep Dreams in Keras.
<ide>
<ide> [neural_doodle.py](neural_doodle.py)
<ide> Neural doodle.
<ide>
<ide> [neural_style_transfer.py](neural_style_transfer.py)
<ide> Neural style transfer.
<ide>
<del>[pretrained_word_embeddings.py](pretrained_word_embeddings.py)
<del>Loads pre-trained word embeddings (GloVe embeddings) into a frozen Keras Embedding layer, and uses it to train a text classification model on the 20 Newsgroup dataset.
<del>
<del>[reuters_mlp.py](reuters_mlp.py)
<del>Trains and evaluate a simple MLP on the Reuters newswire topic classification task.
<del>
<del>[reuters_mlp_relu_vs_selu.py](reuters_mlp_relu_vs_selu.py)
<del>Compares self-normalizing MLPs with regular MLPs.
<del>
<ide> [variational_autoencoder.py](variational_autoencoder.py)
<ide> Demonstrates how to build a variational autoencoder.
<ide>
<ide> [variational_autoencoder_deconv.py](variational_autoencoder_deconv.py)
<ide> Demonstrates how to build a variational autoencoder with Keras using deconvolution layers.
<add>
<add>----
<add>
<add>## Examples demonstrating specific Keras functionality
<add>
<add>[antirectifier.py](antirectifier.py)
<add>Demonstrates how to write custom layers for Keras.
<add>
<add>[mnist_sklearn_wrapper.py](mnist_sklearn_wrapper.py)
<add>Demonstrates how to use the sklearn wrapper.
<add>
<add>[mnist_irnn.py](mnist_irnn.py)
<add>Reproduction of the IRNN experiment with pixel-by-pixel sequential MNIST in "A Simple Way to Initialize Recurrent Networks of Rectified Linear Units" by Le et al.
<add>
<add>[mnist_net2net.py](mnist_net2net.py)
<add>Reproduction of the Net2Net experiment with MNIST in "Net2Net: Accelerating Learning via Knowledge Transfer".
<add>
<add>[reuters_mlp_relu_vs_selu.py](reuters_mlp_relu_vs_selu.py)
<add>Compares self-normalizing MLPs with regular MLPs.
<add>
<add>[mnist_tfrecord.py](mnist_tfrecord.py)
<add>MNIST dataset with TFRecords, the standard TensorFlow data format. | 1 |
Javascript | Javascript | fix skew transformation | b850af7a394275588585e0a07c30ab225e0269fe | <ide><path>Libraries/Utilities/MatrixMath.js
<ide> var MatrixMath = {
<ide> },
<ide>
<ide> reuseSkewXCommand: function(matrixCommand, radians) {
<del> matrixCommand[4] = Math.sin(radians);
<del> matrixCommand[5] = Math.cos(radians);
<add> matrixCommand[4] = Math.tan(radians);
<ide> },
<ide>
<ide> reuseSkewYCommand: function(matrixCommand, radians) {
<del> matrixCommand[0] = Math.cos(radians);
<del> matrixCommand[1] = Math.sin(radians);
<add> matrixCommand[1] = Math.tan(radians);
<ide> },
<ide>
<ide> multiplyInto: function(out, a, b) { | 1 |
Text | Text | fix wrong output titile for docker volume ls | 43023a5428062829c16725e5833da763fc19353a | <ide><path>docs/extend/index.md
<ide> started without error.
<ide> ```bash
<ide> $ docker volume ls
<ide>
<del> DRIVER NAME
<add> DRIVER VOLUME NAME
<ide> vieux/sshfs sshvolume
<ide> ```
<ide>
<ide><path>docs/reference/commandline/volume_ls.md
<ide> regardless of its value.
<ide> ```bash
<ide> $ docker volume ls --filter label=is-timelord
<ide>
<del>DRIVER NAME
<add>DRIVER VOLUME NAME
<ide> local daleks
<ide> local the-doctor
<ide> ```
<ide> Filtering on both `key` *and* `value` of the label, produces the expected result
<ide> ```bash
<ide> $ docker volume ls --filter label=is-timelord=yes
<ide>
<del>DRIVER NAME
<add>DRIVER VOLUME NAME
<ide> local the-doctor
<ide> ```
<ide>
<ide> should be met;
<ide> ```bash
<ide> $ docker volume ls --filter label=is-timelord=yes --filter label=is-timelord=no
<ide>
<del>DRIVER NAME
<add>DRIVER VOLUME NAME
<ide> ```
<ide>
<ide> ### name | 2 |
Python | Python | support none num_boxes and refactor serving | 3abc1d1c8d4ff6a84bbe5592f42f37844990616d | <ide><path>official/vision/beta/modeling/maskrcnn_model.py
<ide> def call(self,
<ide>
<ide> model_mask_outputs = self._call_mask_outputs(
<ide> model_box_outputs=model_outputs,
<del> features=intermediate_outputs['features'],
<add> features=model_outputs['decoder_features'],
<ide> current_rois=intermediate_outputs['current_rois'],
<ide> matched_gt_indices=intermediate_outputs['matched_gt_indices'],
<ide> matched_gt_boxes=intermediate_outputs['matched_gt_boxes'],
<ide> def call(self,
<ide> model_outputs.update(model_mask_outputs)
<ide> return model_outputs
<ide>
<add> def _get_backbone_and_decoder_features(self, images):
<add>
<add> backbone_features = self.backbone(images)
<add> if self.decoder:
<add> features = self.decoder(backbone_features)
<add> else:
<add> features = backbone_features
<add> return backbone_features, features
<add>
<ide> def _call_box_outputs(
<ide> self, images: tf.Tensor,
<ide> image_shape: tf.Tensor,
<ide> def _call_box_outputs(
<ide> model_outputs = {}
<ide>
<ide> # Feature extraction.
<del> backbone_features = self.backbone(images)
<del> if self.decoder:
<del> features = self.decoder(backbone_features)
<del> else:
<del> features = backbone_features
<add> (backbone_features,
<add> decoder_features) = self._get_backbone_and_decoder_features(images)
<ide>
<ide> # Region proposal network.
<del> rpn_scores, rpn_boxes = self.rpn_head(features)
<add> rpn_scores, rpn_boxes = self.rpn_head(decoder_features)
<ide>
<ide> model_outputs.update({
<ide> 'backbone_features': backbone_features,
<del> 'decoder_features': features,
<add> 'decoder_features': decoder_features,
<ide> 'rpn_boxes': rpn_boxes,
<ide> 'rpn_scores': rpn_scores
<ide> })
<ide> def _call_box_outputs(
<ide> (class_outputs, box_outputs, model_outputs, matched_gt_boxes,
<ide> matched_gt_classes, matched_gt_indices,
<ide> current_rois) = self._run_frcnn_head(
<del> features=features,
<add> features=decoder_features,
<ide> rois=current_rois,
<ide> gt_boxes=gt_boxes,
<ide> gt_classes=gt_classes,
<ide> def _call_box_outputs(
<ide> 'matched_gt_boxes': matched_gt_boxes,
<ide> 'matched_gt_indices': matched_gt_indices,
<ide> 'matched_gt_classes': matched_gt_classes,
<del> 'features': features,
<ide> 'current_rois': current_rois,
<ide> }
<ide> return (model_outputs, intermediate_outputs)
<ide> def _call_mask_outputs(
<ide> current_rois = model_outputs['detection_boxes']
<ide> roi_classes = model_outputs['detection_classes']
<ide>
<del> # Mask RoI align.
<del> mask_roi_features = self.mask_roi_aligner(features, current_rois)
<del>
<del> # Mask head.
<del> raw_masks = self.mask_head([mask_roi_features, roi_classes])
<add> mask_logits, mask_probs = self._features_to_mask_outputs(
<add> features, current_rois, roi_classes)
<ide>
<ide> if training:
<ide> model_outputs.update({
<del> 'mask_outputs': raw_masks,
<add> 'mask_outputs': mask_logits,
<ide> })
<ide> else:
<ide> model_outputs.update({
<del> 'detection_masks': tf.math.sigmoid(raw_masks),
<add> 'detection_masks': mask_probs,
<ide> })
<ide> return model_outputs
<ide>
<ide> def _run_frcnn_head(self, features, rois, gt_boxes, gt_classes, training,
<ide> return (class_outputs, box_outputs, model_outputs, matched_gt_boxes,
<ide> matched_gt_classes, matched_gt_indices, rois)
<ide>
<add> def _features_to_mask_outputs(self, features, rois, roi_classes):
<add> # Mask RoI align.
<add> mask_roi_features = self.mask_roi_aligner(features, rois)
<add>
<add> # Mask head.
<add> raw_masks = self.mask_head([mask_roi_features, roi_classes])
<add>
<add> return raw_masks, tf.nn.sigmoid(raw_masks)
<add>
<ide> @property
<ide> def checkpoint_items(
<ide> self) -> Mapping[str, Union[tf.keras.Model, tf.keras.layers.Layer]]:
<ide><path>official/vision/beta/ops/spatial_transform_ops.py
<ide> def _feature_bilinear_interpolation(features, kernel_y, kernel_x):
<ide> [batch_size, num_boxes, output_size, output_size, num_filters].
<ide>
<ide> """
<del> batch_size, num_boxes, output_size, _, num_filters = (
<del> features.get_shape().as_list())
<del> if batch_size is None:
<del> batch_size = tf.shape(features)[0]
<add> features_shape = tf.shape(features)
<add> batch_size, num_boxes, output_size, num_filters = (
<add> features_shape[0], features_shape[1], features_shape[2],
<add> features_shape[4])
<add>
<ide> output_size = output_size // 2
<ide> kernel_y = tf.reshape(kernel_y, [batch_size, num_boxes, output_size * 2, 1])
<ide> kernel_x = tf.reshape(kernel_x, [batch_size, num_boxes, 1, output_size * 2])
<ide> def _compute_grid_positions(boxes, boundaries, output_size, sample_offset):
<ide> box_grid_y0y1: Tensor of size [batch_size, boxes, output_size, 2]
<ide> box_grid_x0x1: Tensor of size [batch_size, boxes, output_size, 2]
<ide> """
<del> batch_size, num_boxes, _ = boxes.get_shape().as_list()
<add> boxes_shape = tf.shape(boxes)
<add> batch_size, num_boxes = boxes_shape[0], boxes_shape[1]
<ide> if batch_size is None:
<ide> batch_size = tf.shape(boxes)[0]
<ide> box_grid_x = []
<ide> def multilevel_crop_and_resize(features,
<ide> levels = list(features.keys())
<ide> min_level = int(min(levels))
<ide> max_level = int(max(levels))
<add> features_shape = tf.shape(features[str(min_level)])
<ide> batch_size, max_feature_height, max_feature_width, num_filters = (
<del> features[str(min_level)].get_shape().as_list())
<del> if batch_size is None:
<del> batch_size = tf.shape(features[str(min_level)])[0]
<del> _, num_boxes, _ = boxes.get_shape().as_list()
<add> features_shape[0], features_shape[1], features_shape[2],
<add> features_shape[3])
<add>
<add> num_boxes = tf.shape(boxes)[1]
<ide>
<ide> # Stack feature pyramid into a features_all of shape
<ide> # [batch_size, levels, height, width, num_filters].
<ide><path>official/vision/beta/projects/deepmac_maskrcnn/modeling/maskrcnn_model.py
<ide> def call(self,
<ide>
<ide> model_mask_outputs = self._call_mask_outputs(
<ide> model_box_outputs=model_outputs,
<del> features=intermediate_outputs['features'],
<add> features=model_outputs['decoder_features'],
<ide> current_rois=intermediate_outputs['current_rois'],
<ide> matched_gt_indices=intermediate_outputs['matched_gt_indices'],
<ide> matched_gt_boxes=intermediate_outputs['matched_gt_boxes'],
<ide><path>official/vision/beta/serving/detection.py
<ide> # Lint as: python3
<ide> """Detection input and model functions for serving/inference."""
<ide>
<add>from typing import Mapping, Text
<ide> import tensorflow as tf
<ide>
<ide> from official.vision.beta import configs
<ide> def _build_inputs(self, image):
<ide>
<ide> return image, anchor_boxes, image_info
<ide>
<del> def serve(self, images: tf.Tensor):
<del> """Cast image to float and run inference.
<add> def preprocess(self, images: tf.Tensor) -> (
<add> tf.Tensor, Mapping[Text, tf.Tensor], tf.Tensor):
<add> """Preprocess inputs to be suitable for the model.
<ide>
<ide> Args:
<del> images: uint8 Tensor of shape [batch_size, None, None, 3]
<add> images: The images tensor.
<ide> Returns:
<del> Tensor holding detection output logits.
<add> images: The images tensor cast to float.
<add> anchor_boxes: Dict mapping anchor levels to anchor boxes.
<add> image_info: Tensor containing the details of the image resizing.
<add>
<ide> """
<ide> model_params = self.params.task.model
<ide> with tf.device('cpu:0'):
<ide> def serve(self, images: tf.Tensor):
<ide> image_info_spec),
<ide> parallel_iterations=32))
<ide>
<add> return images, anchor_boxes, image_info
<add>
<add> def serve(self, images: tf.Tensor):
<add> """Cast image to float and run inference.
<add>
<add> Args:
<add> images: uint8 Tensor of shape [batch_size, None, None, 3]
<add> Returns:
<add> Tensor holding detection output logits.
<add> """
<add>
<add> images, anchor_boxes, image_info = self.preprocess(images)
<ide> input_image_shape = image_info[:, 1, :]
<ide>
<ide> # To overcome keras.Model extra limitation to save a model with layers that | 4 |
Ruby | Ruby | use alias_method instead of an extra ivar | 7b550b9486b53f8987e18a2e27b7e8c137391a94 | <ide><path>Library/Homebrew/requirement.rb
<ide> class Requirement
<ide> include Dependable
<ide>
<del> attr_reader :tags, :name, :option_name
<add> attr_reader :tags, :name
<add> alias_method :option_name, :name
<ide>
<ide> def initialize(tags=[])
<ide> @tags = tags
<ide> @tags << :build if self.class.build
<ide> @name ||= infer_name
<del> @option_name = @name
<ide> end
<ide>
<ide> # The message to show when the requirement is not met. | 1 |
Go | Go | fix inability to detach service | bc4160be3869f96b701f2e7bff8579be5be2b085 | <ide><path>libnetwork/client/service.go
<ide> func (cli *NetworkCli) CmdServiceDetach(chain string, args ...string) error {
<ide> return err
<ide> }
<ide>
<add> sandboxID, err := lookupSandboxID(cli, containerID)
<add> if err != nil {
<add> return err
<add> }
<add>
<ide> serviceID, err := lookupServiceID(cli, nn, sn)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> _, _, err = readBody(cli.call("DELETE", "/services/"+serviceID+"/backend/"+containerID, nil, nil))
<add> _, _, err = readBody(cli.call("DELETE", "/services/"+serviceID+"/backend/"+sandboxID, nil, nil))
<ide> if err != nil {
<ide> return err
<ide> } | 1 |
Javascript | Javascript | remove unused variable | 9f2f56dd40528a1b620860e13adc80eba970b573 | <ide><path>test/sequential/test-http-writable-true-after-close.js
<ide> const server = createServer(common.mustCall((req, res) => {
<ide> }));
<ide> }).listen(0, () => {
<ide> external = get(`http://127.0.0.1:${server.address().port}`);
<del> external.on('error', common.mustCall((err) => {
<add> external.on('error', common.mustCall(() => {
<ide> server.close();
<ide> internal.close();
<ide> })); | 1 |
Javascript | Javascript | remove duplicate character in regex group | 8a7c2e50f1885d514686071f52ec98b68473cf8b | <ide><path>scripts/rollup/build.js
<ide> function getPlugins(
<ide> // Remove 'use strict' from individual source files.
<ide> {
<ide> transform(source) {
<del> return source.replace(/['"]use strict['"']/g, '');
<add> return source.replace(/['"]use strict["']/g, '');
<ide> },
<ide> },
<ide> // Turn __DEV__ and process.env checks into constants. | 1 |
Javascript | Javascript | fix arguments order in napi test_exception | c03c6e920f03a6be69612a46355dad36c948c5b4 | <ide><path>test/addons-napi/test_exception/test.js
<ide> const test_exception = (function() {
<ide>
<ide> // Test that the native side successfully captures the exception
<ide> let returnedError = test_exception.returnException(throwTheError);
<del> assert.strictEqual(theError, returnedError);
<add> assert.strictEqual(returnedError, theError);
<ide>
<ide> // Test that the native side passes the exception through
<ide> assert.throws( | 1 |
PHP | PHP | fix doc block errors | 4af26371435d7be5ec0f0cdbbf92c1cdcdc1c3f4 | <ide><path>src/View/Form/EntityContext.php
<ide> *
<ide> * - `entity` The entity this context is operating on.
<ide> * - `table` Either the ORM\Table instance to fetch schema/validators
<del> * from, an array of table instances in the case of an form spanning
<add> * from, an array of table instances in the case of a form spanning
<ide> * multiple entities, or the name(s) of the table.
<ide> * If this is null the table name(s) will be determined using conventions.
<ide> * - `validator` Either the Validation\Validator to use, or the name of the
<ide> protected function _getEntity($path) {
<ide> *
<ide> * @param mixed $target The entity/array/collection to fetch $field from.
<ide> * @param string $field The next field to fetch.
<del> * @return mixed.
<add> * @return mixed
<ide> */
<ide> protected function _getProp($target, $field) {
<ide> if (is_array($target) || $target instanceof Traversable) {
<ide> public function attributes($field) {
<ide> $parts = explode('.', $field);
<ide> list($entity, $prop) = $this->_getEntity($parts);
<ide> if (!$entity) {
<del> return null;
<add> return [];
<ide> }
<ide> $table = $this->_getTable($prop);
<ide> $column = $table->schema()->column(array_pop($parts)); | 1 |
Python | Python | add links to source code in documentation | 0f86b45918bc68821905f6ac0894874eef564fed | <ide><path>docs/autogen.py
<ide> def get_method_signature(method):
<ide> return st + ')'
<ide>
<ide>
<del>def class_to_link(cls):
<add>def class_to_docs_link(cls):
<ide> module_name = cls.__module__
<ide> assert module_name[:6] == 'keras.'
<ide> module_name = module_name[6:]
<ide> link = ROOT + module_name.replace('.', '/') + '#' + cls.__name__.lower()
<ide> return link
<ide>
<ide>
<add>def class_to_source_link(cls):
<add> module_name = cls.__module__
<add> assert module_name[:6] == 'keras.'
<add> path = module_name.replace('.', '/')
<add> path += '.py'
<add> line = inspect.getsourcelines(cls)[-1]
<add> link = 'https://github.com/fchollet/keras/blob/master/' + path + '#L' + str(line)
<add> return '[[source]](' + link + ')'
<add>
<add>
<ide> def code_snippet(snippet):
<ide> result = '```python\n'
<ide> result += snippet + '\n'
<ide> def process_method_docstring(docstring):
<ide> methods_not_defined_here.append((method, defined_by))
<ide>
<ide> blocks = []
<add> blocks.append('<span style="float:right;">' + class_to_source_link(cls) + '</span>')
<ide> blocks.append('# ' + cls.__name__ + '\n')
<ide> blocks.append(code_snippet(class_signature))
<ide> docstring = cls.__doc__
<ide> def process_method_docstring(docstring):
<ide> signature = get_method_signature(method)
<ide> method_module_name = method.__module__
<ide> signature = signature.replace(method_module_name + '.', '')
<del> link = '[' + defined_by.__name__ + '](' + class_to_link(defined_by) + ')'
<add> link = '[' + defined_by.__name__ + '](' + class_to_docs_link(defined_by) + ')'
<ide> blocks.append(code_snippet(signature))
<ide> blocks.append('Defined by ' + link + '.\n')
<ide> | 1 |
Javascript | Javascript | fix benchmark for url | f3257dd3ead29e620b2bc096d54b07b12ec5c5a3 | <ide><path>benchmark/url/legacy-vs-whatwg-url-searchparams-parse.js
<ide> const common = require('../common.js');
<ide> const { URLSearchParams } = require('url');
<ide> const querystring = require('querystring');
<del>const inputs = require('../fixtures/url-inputs.js').searchParams;
<add>const searchParams = require('../fixtures/url-inputs.js').searchParams;
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> type: Object.keys(inputs),
<add> searchParam: Object.keys(searchParams),
<ide> method: ['legacy', 'whatwg'],
<ide> n: [1e6]
<ide> });
<ide> function useLegacy(n, input) {
<ide> bench.end(n);
<ide> }
<ide>
<del>function useWHATWG(n, input) {
<del> new URLSearchParams(input);
<add>function useWHATWG(n, param) {
<add> new URLSearchParams(param);
<ide> bench.start();
<ide> for (var i = 0; i < n; i += 1) {
<del> new URLSearchParams(input);
<add> new URLSearchParams(param);
<ide> }
<ide> bench.end(n);
<ide> }
<ide>
<del>function main({ type, n, method }) {
<del> const input = inputs[type];
<del> if (!input) {
<del> throw new Error(`Unknown input type "${type}"`);
<add>function main({ searchParam, n, method }) {
<add> const param = searchParams[searchParam];
<add> if (!param) {
<add> throw new Error(`Unknown search parameter type "${searchParam}"`);
<ide> }
<ide>
<ide> switch (method) {
<ide> case 'legacy':
<del> useLegacy(n, input);
<add> useLegacy(n, param);
<ide> break;
<ide> case 'whatwg':
<del> useWHATWG(n, input);
<add> useWHATWG(n, param);
<ide> break;
<ide> default:
<ide> throw new Error(`Unknown method ${method}`);
<ide><path>benchmark/url/legacy-vs-whatwg-url-searchparams-serialize.js
<ide> const common = require('../common.js');
<ide> const { URLSearchParams } = require('url');
<ide> const querystring = require('querystring');
<del>const inputs = require('../fixtures/url-inputs.js').searchParams;
<add>const searchParams = require('../fixtures/url-inputs.js').searchParams;
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> type: Object.keys(inputs),
<add> searchParam: Object.keys(searchParams),
<ide> method: ['legacy', 'whatwg'],
<ide> n: [1e6]
<ide> });
<ide> function useLegacy(n, input, prop) {
<ide> bench.end(n);
<ide> }
<ide>
<del>function useWHATWG(n, input, prop) {
<del> const obj = new URLSearchParams(input);
<add>function useWHATWG(n, param, prop) {
<add> const obj = new URLSearchParams(param);
<ide> obj.toString();
<ide> bench.start();
<ide> for (var i = 0; i < n; i += 1) {
<ide> function useWHATWG(n, input, prop) {
<ide> bench.end(n);
<ide> }
<ide>
<del>function main({ type, n, method }) {
<del> const input = inputs[type];
<del> if (!input) {
<del> throw new Error(`Unknown input type "${type}"`);
<add>function main({ searchParam, n, method }) {
<add> const param = searchParams[searchParam];
<add> if (!param) {
<add> throw new Error(`Unknown search parameter type "${searchParam}"`);
<ide> }
<ide>
<ide> switch (method) {
<ide> case 'legacy':
<del> useLegacy(n, input);
<add> useLegacy(n, param);
<ide> break;
<ide> case 'whatwg':
<del> useWHATWG(n, input);
<add> useWHATWG(n, param);
<ide> break;
<ide> default:
<ide> throw new Error(`Unknown method ${method}`);
<ide><path>benchmark/url/url-searchparams-iteration.js
<ide> const assert = require('assert');
<ide> const { URLSearchParams } = require('url');
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> method: ['forEach', 'iterator'],
<add> loopMethod: ['forEach', 'iterator'],
<ide> n: [1e6]
<ide> });
<ide>
<ide> function iterator(n) {
<ide> assert.strictEqual(noDead[1], '3rd');
<ide> }
<ide>
<del>function main({ method, n }) {
<del> switch (method) {
<add>function main({ loopMethod, n }) {
<add> switch (loopMethod) {
<ide> case 'forEach':
<ide> forEach(n);
<ide> break;
<ide> case 'iterator':
<ide> iterator(n);
<ide> break;
<ide> default:
<del> throw new Error(`Unknown method ${method}`);
<add> throw new Error(`Unknown method ${loopMethod}`);
<ide> }
<ide> }
<ide><path>benchmark/url/url-searchparams-read.js
<ide> const common = require('../common.js');
<ide> const { URLSearchParams } = require('url');
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> method: ['get', 'getAll', 'has'],
<add> accessMethod: ['get', 'getAll', 'has'],
<ide> param: ['one', 'two', 'three', 'nonexistent'],
<ide> n: [2e7]
<ide> });
<ide>
<ide> const str = 'one=single&two=first&three=first&two=2nd&three=2nd&three=3rd';
<ide>
<del>function main({ method, param, n }) {
<add>function main({ accessMethod, param, n }) {
<ide> const params = new URLSearchParams(str);
<del> const fn = params[method];
<del> if (!fn)
<del> throw new Error(`Unknown method ${method}`);
<add> if (!params[accessMethod])
<add> throw new Error(`Unknown method ${accessMethod}`);
<ide>
<ide> bench.start();
<ide> for (var i = 0; i < n; i += 1)
<del> fn(param);
<add> params[accessMethod](param);
<ide> bench.end(n);
<ide> }
<ide><path>benchmark/url/whatwg-url-idna.js
<ide> const common = require('../common.js');
<ide> const { domainToASCII, domainToUnicode } = require('url');
<ide>
<del>const inputs = {
<add>const domains = {
<ide> empty: {
<ide> ascii: '',
<ide> unicode: ''
<ide> const inputs = {
<ide> };
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> input: Object.keys(inputs),
<add> domain: Object.keys(domains),
<ide> to: ['ascii', 'unicode'],
<ide> n: [5e6]
<ide> });
<ide>
<del>function main({ n, to, input }) {
<del> const value = inputs[input][to];
<add>function main({ n, to, domain }) {
<add> const value = domains[domain][to];
<ide> const method = to === 'ascii' ? domainToASCII : domainToUnicode;
<ide>
<ide> bench.start();
<ide><path>test/parallel/test-benchmark-url.js
<add>'use strict';
<add>
<add>require('../common');
<add>
<add>const runBenchmark = require('../common/benchmark');
<add>
<add>runBenchmark('url',
<add> [
<add> 'method=legacy',
<add> 'loopMethod=forEach',
<add> 'accessMethod=get',
<add> 'type=short',
<add> 'searchParam=noencode',
<add> 'href=short',
<add> 'input=short',
<add> 'domain=empty',
<add> 'path=up',
<add> 'to=ascii',
<add> 'prop=href',
<add> 'n=1',
<add> ],
<add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); | 6 |
Text | Text | use space instead of tab | 344ccf2d454a43d9b0f93a63f567c0fcff310d62 | <ide><path>src/ORM/README.md
<ide> class ArticlesTable extends Table
<ide> public function initialize()
<ide> {
<ide> $this->setEntityClass(Article::class);
<del> $this->belongsTo('Users', ['className' => UsersTable::class]);
<add> $this->belongsTo('Users', ['className' => UsersTable::class]);
<ide> }
<ide> }
<ide> ``` | 1 |
Ruby | Ruby | eliminate runtime conditional | 175e92c9ac674536ad6c54937b54ef2e77217f08 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> class Mapper
<ide> class Constraints < Endpoint #:nodoc:
<ide> attr_reader :app, :constraints
<ide>
<del> def initialize(app, constraints, dispatcher_p)
<add> SERVE = ->(app, req) { app.serve req }
<add> CALL = ->(app, req) { app.call req.env }
<add>
<add> def initialize(app, constraints, strategy)
<ide> # Unwrap Constraints objects. I don't actually think it's possible
<ide> # to pass a Constraints object to this constructor, but there were
<ide> # multiple places that kept testing children of this object. I
<ide> def initialize(app, constraints, dispatcher_p)
<ide> app = app.app
<ide> end
<ide>
<del> @dispatcher = dispatcher_p
<add> @strategy = strategy
<ide>
<ide> @app, @constraints, = app, constraints
<ide> end
<ide>
<del> def dispatcher?; @dispatcher; end
<add> def dispatcher?; @strategy == SERVE; end
<ide>
<ide> def matches?(req)
<ide> @constraints.all? do |constraint|
<ide> def matches?(req)
<ide> def serve(req)
<ide> return [ 404, {'X-Cascade' => 'pass'}, [] ] unless matches?(req)
<ide>
<del> if dispatcher?
<del> @app.serve req
<del> else
<del> @app.call req.env
<del> end
<add> @strategy.call @app, req
<ide> end
<ide>
<ide> private
<ide> def add_request_method(via, conditions)
<ide>
<ide> def app(blocks)
<ide> if to.respond_to?(:call)
<del> Constraints.new(to, blocks, false)
<add> Constraints.new(to, blocks, Constraints::CALL)
<ide> elsif blocks.any?
<del> Constraints.new(dispatcher(defaults), blocks, true)
<add> Constraints.new(dispatcher(defaults), blocks, Constraints::SERVE)
<ide> else
<ide> dispatcher(defaults)
<ide> end | 1 |
Text | Text | update installation instructions (see #727) | 853130bcf8c55b5b50d32ac8ca004abdb5fa8cc7 | <ide><path>examples/keras_parikh_entailment/README.md
<ide> First, install [Keras](https://keras.io/), [spaCy](https://spacy.io) and the spa
<ide> English models (about 1GB of data):
<ide>
<ide> ```bash
<del>pip install keras spacy
<add>pip install https://github.com/fchollet/keras/archive/master.zip
<add>pip install spacy
<ide> python -m spacy.en.download
<ide> ```
<ide>
<del>You'll also want to get keras working on your GPU. This will depend on your
<add>⚠️ **Important:** In order for the example to run, you'll need to install Keras from
<add>the master branch (and not via `pip install keras`). For more info on this, see
<add>[#727](https://github.com/explosion/spaCy/issues/727).
<add>
<add>You'll also want to get Keras working on your GPU. This will depend on your
<ide> set up, so you're mostly on your own for this step. If you're using AWS, try the
<ide> [NVidia AMI](https://aws.amazon.com/marketplace/pp/B00FYCDDTE). It made things pretty easy.
<ide> | 1 |
Javascript | Javascript | add test for d3.event re-export on node. related | 17fbf8d4b16ed19303d71dee4881d871bddbc037 | <ide><path>test/d3-test.js
<ide> var tape = require("tape"),
<ide> d3 = require("../"),
<add> d3Selection = require("d3-selection"),
<ide> testExports = require("./test-exports");
<ide>
<ide> tape("version matches package.json", function(test) {
<ide> test.equal(d3.version, require("../package.json").version);
<ide> test.end();
<ide> });
<ide>
<add>tape("d3.event is a getter for d3Selection.event", function(test) {
<add> test.equal(d3.event, null);
<add> try {
<add> d3Selection.event = 42;
<add> test.equal(d3.event, 42);
<add> } finally {
<add> d3Selection.event = null;
<add> }
<add> test.end();
<add>});
<add>
<ide> for (var dependency in require("../package.json").dependencies) {
<ide> testExports(dependency);
<ide> } | 1 |
Go | Go | fix image filter | 5ee69eb470316eead3af20725de54d3c47a47a62 | <ide><path>daemon/images.go
<ide> func (daemon *Daemon) Images(filterArgs, filter string, all bool) ([]*types.Imag
<ide> return nil, fmt.Errorf("Invalid filter 'dangling=%s'", imageFilters.Get("dangling"))
<ide> }
<ide> }
<del>
<ide> if danglingOnly {
<ide> allImages = daemon.imageStore.Heads()
<ide> } else {
<ide> func (daemon *Daemon) Images(filterArgs, filter string, all bool) ([]*types.Imag
<ide> }
<ide> if newImage.RepoDigests == nil && newImage.RepoTags == nil {
<ide> if all || len(daemon.imageStore.Children(id)) == 0 {
<add>
<add> if imageFilters.Include("dangling") && !danglingOnly {
<add> //dangling=false case, so dangling image is not needed
<add> continue
<add> }
<ide> if filter != "" { // skip images with no references if filtering by tag
<ide> continue
<ide> }
<ide><path>integration-cli/docker_cli_images_test.go
<ide> func (s *DockerSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *check.C) {
<ide> out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=true")
<ide> // Expect one dangling image
<ide> c.Assert(strings.Count(out, imageID), checker.Equals, 1)
<add>
<add> out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=false")
<add> //dangling=false would not include dangling images
<add> c.Assert(out, checker.Not(checker.Contains), imageID)
<add>
<add> out, _ = dockerCmd(c, "images")
<add> //docker images still include dangling images
<add> c.Assert(out, checker.Contains, imageID)
<add>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestImagesWithIncorrectFilter(c *check.C) { | 2 |
Python | Python | add additional assertion | 53e5cf48c7469b01548f0c36ba870a7fd5c5f55b | <ide><path>libcloud/test/storage/test_local.py
<ide> def test_objects_success(self):
<ide> objects = self.driver.list_container_objects(container=container)
<ide> self.assertEqual(len(objects), 5)
<ide>
<add> prefix = os.path.join('path', 'invalid')
<add> objects = self.driver.list_container_objects(container=container,
<add> prefix=prefix)
<add> self.assertEqual(len(objects), 0)
<add>
<ide> prefix = os.path.join('path', 'to')
<ide> objects = self.driver.list_container_objects(container=container,
<ide> prefix=prefix) | 1 |
Javascript | Javascript | fix some mmdloader bugs | 0eaa2c674298858bdb5be7bd002c36d7e84bbe14 | <ide><path>examples/js/loaders/MMDLoader.js
<ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress
<ide> m.skinning = geometry.bones.length > 0 ? true : false;
<ide> m.morphTargets = geometry.morphTargets.length > 0 ? true : false;
<ide> m.lights = true;
<del> m.side = p.side;
<add> m.side = ( model.metadata.format === 'pmx' && ( p2.flag & 0x1 ) === 1 ) ? THREE.DoubleSide : p.side;
<ide> m.transparent = p.transparent;
<ide> m.fog = true;
<ide>
<ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress
<ide> alpha: p2.edgeColor[ 3 ]
<ide> };
<ide>
<del> if ( m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
<add> if ( ( p2.flag & 0x10 ) === 0 || m.outlineParameters.thickness === 0.0 ) m.outlineParameters.visible = false;
<ide>
<ide> m.uniforms.celShading.value = 1;
<ide>
<ide> THREE.MMDLoader.prototype.leftToRightModel = function ( model ) {
<ide>
<ide> var m = model.morphs[ i ];
<ide>
<del> if ( model.metadata.format === 'pmx' ) {
<del>
<del> if ( m.type === 1 ) {
<add> if ( model.metadata.format === 'pmx' && m.type !== 1 ) {
<ide>
<del> m = m.elements;
<del>
<del> } else {
<del>
<del> continue;
<del>
<del> }
<add> // TODO: implement
<add> continue;
<ide>
<ide> }
<ide>
<del> for ( var j = 0; j < m.elementCount; j++ ) {
<add> for ( var j = 0; j < m.elements.length; j++ ) {
<ide>
<ide> helper.leftToRightVector3( m.elements[ j ].position );
<ide> | 1 |
Text | Text | add v3.14.0-beta.5 to changelog | acc2e37274dc398fe38713fe27b3fa97fcddece9 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.14.0-beta.5 (October 14, 2019)
<add>
<add>- [#18476](https://github.com/emberjs/ember.js/pull/18476) [BUGFIX] Ensure model can be observed by sync observers
<add>- [#18458](https://github.com/emberjs/ember.js/pull/18458) [BUGFIX] Using query params helper outside of link-to
<add>
<ide> ### v3.14.0-beta.4 (October 7, 2019)
<ide>
<ide> - [#18462](https://github.com/emberjs/ember.js/pull/18462) [BUGFIX] Prevents observer re-entry | 1 |
Text | Text | use new vips syntax for named variant examples | b6766b847bee0bff9500bf74fed42b07563a1c8d | <ide><path>guides/source/active_storage_overview.md
<ide> You can configure specific variants per attachment by calling the `variant` meth
<ide> ```ruby
<ide> class User < ApplicationRecord
<ide> has_one_attached :avatar do |attachable|
<del> attachable.variant :thumb, resize: "100x100"
<add> attachable.variant :thumb, resize_to_limit: [100, 100]
<ide> end
<ide> end
<ide> ```
<ide> Configuring specific variants is done the same way as `has_one_attached`, by cal
<ide> ```ruby
<ide> class Message < ApplicationRecord
<ide> has_many_attached :images do |attachable|
<del> attachable.variant :thumb, resize: "100x100"
<add> attachable.variant :thumb, resize_to_limit: [100, 100]
<ide> end
<ide> end
<ide> ``` | 1 |
PHP | PHP | add more context about invalid subqueries | ab5ee8aa5b8d1fb9e2d1acd7bf7a6962e7db2581 | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function fromRaw($expression, $bindings = [])
<ide> *
<ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query
<ide> * @return array
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<ide> protected function createSub($query)
<ide> {
<ide> protected function createSub($query)
<ide> *
<ide> * @param mixed $query
<ide> * @return array
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<ide> protected function parseSub($query)
<ide> {
<ide> protected function parseSub($query)
<ide> } elseif (is_string($query)) {
<ide> return [$query, []];
<ide> } else {
<del> throw new InvalidArgumentException;
<add> throw new InvalidArgumentException(
<add> 'The subquery must be an instance of Closure or Builder, or a string.'
<add> );
<ide> }
<ide> }
<ide>
<ide> public function leftJoinWhere($table, $first, $operator, $second)
<ide> * @param string|null $operator
<ide> * @param string|null $second
<ide> * @return \Illuminate\Database\Query\Builder|static
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<ide> public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
<ide> {
<ide> public function rightJoinWhere($table, $first, $operator, $second)
<ide> * @param string|null $operator
<ide> * @param string|null $second
<ide> * @return \Illuminate\Database\Query\Builder|static
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<ide> public function rightJoinSub($query, $as, $first, $operator = null, $second = null)
<ide> {
<ide> public function insertGetId(array $values, $sequence = null)
<ide> * @param array $columns
<ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query
<ide> * @return int
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<ide> public function insertUsing(array $columns, $query)
<ide> {
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testJoinSub()
<ide> $expected .= 'inner join (select * from "contacts" where "name" = ?) as "sub2" on "users"."id" = "sub2"."user_id"';
<ide> $this->assertEquals($expected, $builder->toSql());
<ide> $this->assertEquals(['foo', 1, 'bar'], $builder->getRawBindings()['join']);
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->from('users')->joinSub(['foo'], 'sub', 'users.id', '=', 'sub.id');
<ide> }
<ide>
<ide> public function testJoinSubWithPrefix()
<ide> public function testLeftJoinSub()
<ide> $builder = $this->getBuilder();
<ide> $builder->from('users')->leftJoinSub($this->getBuilder()->from('contacts'), 'sub', 'users.id', '=', 'sub.id');
<ide> $this->assertSame('select * from "users" left join (select * from "contacts") as "sub" on "users"."id" = "sub"."id"', $builder->toSql());
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->from('users')->leftJoinSub(['foo'], 'sub', 'users.id', '=', 'sub.id');
<ide> }
<ide>
<ide> public function testRightJoinSub()
<ide> {
<ide> $builder = $this->getBuilder();
<ide> $builder->from('users')->rightJoinSub($this->getBuilder()->from('contacts'), 'sub', 'users.id', '=', 'sub.id');
<ide> $this->assertSame('select * from "users" right join (select * from "contacts") as "sub" on "users"."id" = "sub"."id"', $builder->toSql());
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->from('users')->rightJoinSub(['foo'], 'sub', 'users.id', '=', 'sub.id');
<ide> }
<ide>
<ide> public function testRawExpressionsInSelect()
<ide> function (Builder $query) {
<ide> $this->assertEquals(1, $result);
<ide> }
<ide>
<add> public function testInsertUsingInvalidSubquery()
<add> {
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->from('table1')->insertUsing(['foo'], ['bar']);
<add> }
<add>
<ide> public function testInsertOrIgnoreMethod()
<ide> {
<ide> $this->expectException(RuntimeException::class);
<ide> public function testSubSelect()
<ide> $builder->selectSub($subBuilder, 'sub');
<ide> $this->assertEquals($expectedSql, $builder->toSql());
<ide> $this->assertEquals($expectedBindings, $builder->getBindings());
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getPostgresBuilder();
<add> $builder->selectSub(['foo'], 'sub');
<ide> }
<ide>
<ide> public function testSqlServerWhereDate()
<ide> public function testFromSub()
<ide> }, 'sessions')->where('bar', '<', '10');
<ide> $this->assertSame('select * from (select max(last_seen_at) as last_seen_at from "user_sessions" where "foo" = ?) as "sessions" where "bar" < ?', $builder->toSql());
<ide> $this->assertEquals(['1', '10'], $builder->getBindings());
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->fromSub(['invalid'], 'sessions')->where('bar', '<', '10');
<ide> }
<ide>
<ide> public function testFromSubWithPrefix()
<ide> public function testFromSubWithoutBindings()
<ide> $query->select(new Raw('max(last_seen_at) as last_seen_at'))->from('user_sessions');
<ide> }, 'sessions');
<ide> $this->assertSame('select * from (select max(last_seen_at) as last_seen_at from "user_sessions") as "sessions"', $builder->toSql());
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $builder = $this->getBuilder();
<add> $builder->fromSub(['invalid'], 'sessions');
<ide> }
<ide>
<ide> public function testFromRaw() | 2 |
PHP | PHP | handle nested options in multi-checkbox widget | 709b54e9c9b4abdcd5c2379b452127a918d5accb | <ide><path>src/View/Widget/MultiCheckboxWidget.php
<ide> class MultiCheckboxWidget implements WidgetInterface
<ide> * - `checkboxWrapper` Renders the containing div/element for
<ide> * a checkbox and its label. Accepts the `input`, and `label`
<ide> * variables.
<add> * - `fieldset` Renders the fieldset for grouped inputs.
<add> * - `legend` Renders the legend element for grouped inputs.
<ide> *
<ide> * @param \Cake\View\StringTemplate $templates Templates list.
<ide> * @param \Cake\View\Widget\LabelWidget $label Label widget instance.
<ide> public function render(array $data, ContextInterface $context)
<ide> 'idPrefix' => null,
<ide> 'templateVars' => []
<ide> ];
<del> $out = [];
<ide> $this->_idPrefix = $data['idPrefix'];
<ide> $this->_clearIds();
<add> return implode('', $this->_renderInputs($data, $context));
<add> }
<add>
<add> protected function _renderInputs($data, $context)
<add> {
<add> $out = [];
<ide> foreach ($data['options'] as $key => $val) {
<add> // Grouped inputs in a fieldset.
<add> if (is_string($key) && is_array($val) && !isset($val['text'], $val['value'])) {
<add> $inputs = $this->_renderInputs(['options' => $val] + $data, $context);
<add> $legend = $this->_templates->format('legend', ['text' => $key]);
<add> $out[] = $this->_templates->format('fieldset', [
<add> 'content' => $legend . implode('', $inputs)
<add> ]);
<add> continue;
<add> }
<add>
<add> // Standard inputs.
<ide> $checkbox = [
<ide> 'value' => $key,
<ide> 'text' => $val,
<ide> public function render(array $data, ContextInterface $context)
<ide> if (empty($checkbox['id'])) {
<ide> $checkbox['id'] = $this->_id($checkbox['name'], $checkbox['value']);
<ide> }
<del>
<ide> $out[] = $this->_renderInput($checkbox, $context);
<ide> }
<del> return implode('', $out);
<add> return $out;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Widget/MultiCheckboxWidgetTest.php
<ide> public function setUp()
<ide> 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>',
<ide> 'label' => '<label{{attrs}}>{{text}}</label>',
<ide> 'checkboxWrapper' => '<div class="checkbox">{{input}}{{label}}</div>',
<add> 'fieldset' => '<fieldset{{attrs}}>{{content}}</fieldset>',
<add> 'legend' => '<legend>{{text}}</legend>',
<ide> ];
<ide> $this->templates = new StringTemplate($templates);
<ide> $this->context = $this->getMock('Cake\View\Form\ContextInterface');
<ide> public function testRenderTemplateVars()
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> }
<add>
<add> /**
<add> * Test render with groupings.
<add> *
<add> * @return void
<add> */
<add> public function testRenderGrouped()
<add> {
<add> $label = new LabelWidget($this->templates);
<add> $input = new MultiCheckboxWidget($this->templates, $label);
<add> $data = [
<add> 'name' => 'Tags[id]',
<add> 'options' => [
<add> 'Group 1' => [
<add> 1 => 'CakePHP',
<add> ],
<add> 'Group 2' => [
<add> 2 => 'Development',
<add> ]
<add> ]
<add> ];
<add> $result = $input->render($data, $this->context);
<add> $expected = [
<add> '<fieldset',
<add> '<legend', 'Group 1', '/legend',
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 1,
<add> 'id' => 'tags-id-1',
<add> ]],
<add> ['label' => ['for' => 'tags-id-1']],
<add> 'CakePHP',
<add> '/label',
<add> '/div',
<add> '/fieldset',
<add>
<add> '<fieldset',
<add> '<legend', 'Group 2', '/legend',
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 2,
<add> 'id' => 'tags-id-2',
<add> ]],
<add> ['label' => ['for' => 'tags-id-2']],
<add> 'Development',
<add> '/label',
<add> '/div',
<add> '/fieldset',
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<add>
<add> /**
<add> * Test render with partial groupings.
<add> *
<add> * @return void
<add> */
<add> public function testRenderPartialGrouped()
<add> {
<add> $label = new LabelWidget($this->templates);
<add> $input = new MultiCheckboxWidget($this->templates, $label);
<add> $data = [
<add> 'name' => 'Tags[id]',
<add> 'options' => [
<add> 1 => 'PHP',
<add> 'Group 1' => [
<add> 2 => 'CakePHP',
<add> ],
<add> 3 => 'Development',
<add> ]
<add> ];
<add> $result = $input->render($data, $this->context);
<add> $expected = [
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 1,
<add> 'id' => 'tags-id-1',
<add> ]],
<add> ['label' => ['for' => 'tags-id-1']],
<add> 'PHP',
<add> '/label',
<add> '/div',
<add>
<add> '<fieldset',
<add> '<legend', 'Group 1', '/legend',
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 2,
<add> 'id' => 'tags-id-2',
<add> ]],
<add> ['label' => ['for' => 'tags-id-2']],
<add> 'CakePHP',
<add> '/label',
<add> '/div',
<add> '/fieldset',
<add>
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 3,
<add> 'id' => 'tags-id-3',
<add> ]],
<add> ['label' => ['for' => 'tags-id-3']],
<add> 'Development',
<add> '/label',
<add> '/div',
<add> ];
<add> $this->assertHtml($expected, $result);
<add> }
<ide> } | 2 |
Ruby | Ruby | simplify conditions within apply_join_dependency | 1dcb1ccc9d3d4f41e8f1a76ff3465f708189dd2f | <ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def apply_join_dependency(relation, join_dependency)
<ide> relation = association.join_relation(relation)
<ide> end
<ide>
<del> limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
<del>
<del> if !limitable_reflections && relation.limit_value
<del> limited_id_condition = construct_limited_ids_condition(relation)
<del> relation = relation.where(limited_id_condition)
<add> if using_limitable_reflections?(join_dependency.reflections)
<add> relation
<add> else
<add> relation = relation.where(construct_limited_ids_condition(relation)) if relation.limit_value
<add> relation.except(:limit, :offset)
<ide> end
<del>
<del> relation = relation.except(:limit, :offset) unless limitable_reflections
<del>
<del> relation
<ide> end
<ide>
<ide> def construct_limited_ids_condition(relation) | 1 |
Javascript | Javascript | fix ordinalmonth testing | 69be3663c8c9b5092b2440ace7006eac103faa49 | <ide><path>src/test/locale/ko.js
<ide> test('format', function (assert) {
<ide> var a = [
<ide> ['YYYY년 MMMM Do dddd a h:mm:ss', '2010년 2월 14일 일요일 오후 3:25:50'],
<ide> ['ddd A h', '일 오후 3'],
<del> ['M Mo MM MMMM MMM', '2 2일 02 2월 2월'],
<add> ['M Mo MM MMMM MMM', '2 2월 02 2월 2월'],
<ide> ['YYYY YY', '2010 10'],
<ide> ['D Do DD', '14 14일 14'],
<ide> ['d do dddd ddd dd', '0 0일 일요일 일 일'], | 1 |
Text | Text | expand canvas article from a stub | f2e384ce68dcaba357c2e10a836c50feb066f08d | <ide><path>guide/english/html/elements/canvas-tag/index.md
<ide> title: Canvas Tag
<ide> ---
<ide> ## Canvas Tag
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/html/elements/canvas-tag/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>You can use a canvas to draw and animate graphics. The drawings are done with JavaScript, so you will want to have an id in order to select the canvas.
<add>```html
<add><canvas id="canvas" width="200px" height="200px">
<add></canvas>
<add>```
<add>Once you've made your canvas, you need to find it and make a drawing object.
<add>```javascript
<add>// Find canvas
<add>var canvas = document.getElementById("canvas");
<add>// Make drawing object
<add>var drawOnCanvas = canvas.getContext("2d");
<add>// Draw a rectangle on the canvas!
<add>drawOnCanvas.fillRect(50, 50, 150, 100);
<add>```
<add>Now you can use this drawing object to draw on your canvas. There are several methods and attributes you can use for your drawing, including `rect()`, `fillStyle`, and many more.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<del>
<add><a href="https://www.w3schools.com/graphics/canvas_reference.asp">Canvas Reference</a>
<ide> | 1 |
PHP | PHP | fix cs error | 67cd7218e78e068c3d8024ee55776ef8dafb25ca | <ide><path>src/Core/PluginInterface.php
<ide> */
<ide> namespace Cake\Core;
<ide>
<del>
<ide> /**
<ide> * Plugin Interface
<ide> */
<ide><path>src/Utility/Crypto/OpenSsl.php
<ide> */
<ide> namespace Cake\Utility\Crypto;
<ide>
<del>
<ide> /**
<ide> * OpenSSL implementation of crypto features for Cake\Utility\Security
<ide> * | 2 |
Text | Text | remove problematic example from readme | d214f41afad2c51c8873a01632f962194f0a0c62 | <ide><path>README.md
<ide> nonetheless.
<ide> arbitrary JavaScript code. That is already the highest level of privilege
<ide> possible.
<ide>
<del>- [#12141](https://github.com/nodejs/node/pull/12141): _buffer: zero fill
<del> Buffer(num) by default_. The documented `Buffer()` behavior was prone to
<del> [misuse](https://snyk.io/blog/exploiting-buffer/). It has since changed. It
<del> was not deemed serious enough to fix in older releases and breaking API
<del> stability.
<del>
<ide> ### Private disclosure preferred
<ide>
<ide> - [CVE-2016-7099](https://nodejs.org/en/blog/vulnerability/september-2016-security-releases/): | 1 |
Javascript | Javascript | add test for | d2698d182271c77bc5bca44a9cee625d9372301f | <ide><path>test/simple/test-http-client-agent.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var http = require('http');
<add>
<add>var name = 'localhost:' + common.PORT;
<add>var max = 3;
<add>var count = 0;
<add>
<add>var server = http.Server(function(req, res) {
<add> if (req.url === '/0') {
<add> setTimeout(function() {
<add> res.writeHead(200);
<add> res.end('Hello, World!');
<add> }, 100);
<add> } else {
<add> res.writeHead(200);
<add> res.end('Hello, World!');
<add> }
<add>});
<add>server.listen(common.PORT, function() {
<add> for (var i = 0; i < max; ++i) {
<add> request(i);
<add> }
<add>});
<add>
<add>function request(i) {
<add> var req = http.get({
<add> port: common.PORT,
<add> path: '/' + i
<add> }, function(res) {
<add> var socket = req.socket;
<add> socket.on('close', function() {
<add> ++count;
<add> assert.equal(http.globalAgent.sockets[name].length, max - count);
<add> assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1);
<add> if (count === max) {
<add> server.close();
<add> }
<add> });
<add> });
<add>}
<add>
<add>process.on('exit', function() {
<add> assert.equal(count, max);
<add>}); | 1 |
Python | Python | fix tr_loss rescaling factor using global_step | 87b9ec3843f7f9a81253075f92c9e6537ecefe1c | <ide><path>examples/run_classifier.py
<ide> def main():
<ide> else:
<ide> loss.backward()
<ide>
<del> tr_loss += loss.item() * args.gradient_accumulation_steps
<add> tr_loss += loss.item()
<ide> nb_tr_examples += input_ids.size(0)
<ide> nb_tr_steps += 1
<ide> if (step + 1) % args.gradient_accumulation_steps == 0:
<ide> def main():
<ide> elif output_mode == "regression":
<ide> preds = np.squeeze(preds)
<ide> result = compute_metrics(task_name, preds, all_label_ids.numpy())
<del> loss = tr_loss/nb_tr_steps if args.do_train else None
<add> loss = tr_loss/global_step if args.do_train else None
<ide>
<ide> result['eval_loss'] = eval_loss
<ide> result['global_step'] = global_step
<ide> def main():
<ide> preds = preds[0]
<ide> preds = np.argmax(preds, axis=1)
<ide> result = compute_metrics(task_name, preds, all_label_ids.numpy())
<del> loss = tr_loss/nb_tr_steps if args.do_train else None
<add> loss = tr_loss/global_step if args.do_train else None
<ide>
<ide> result['eval_loss'] = eval_loss
<ide> result['global_step'] = global_step
<ide><path>examples/run_swag.py
<ide> def main():
<ide> loss = loss * args.loss_scale
<ide> if args.gradient_accumulation_steps > 1:
<ide> loss = loss / args.gradient_accumulation_steps
<del> tr_loss += loss.item() * args.gradient_accumulation_steps
<add> tr_loss += loss.item()
<ide> nb_tr_examples += input_ids.size(0)
<ide> nb_tr_steps += 1
<ide>
<ide> def main():
<ide> result = {'eval_loss': eval_loss,
<ide> 'eval_accuracy': eval_accuracy,
<ide> 'global_step': global_step,
<del> 'loss': tr_loss/nb_tr_steps}
<add> 'loss': tr_loss/global_step}
<ide>
<ide> output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
<ide> with open(output_eval_file, "w") as writer: | 2 |
Ruby | Ruby | log instrumentation name for exists? queries | 618300f05a71bf728d9495c8f8226a8724c5a023 | <ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def exists?(id = nil)
<ide> else
<ide> relation = relation.where(table[primary_key].eq(id)) if id
<ide> end
<del>
<del> connection.select_value(relation.to_sql) ? true : false
<add>
<add> connection.select_value(relation.to_sql, "#{name} Exists") ? true : false
<ide> end
<ide>
<ide> protected
<ide><path>activerecord/test/cases/log_subscriber_test.rb
<ide> def test_basic_query_logging
<ide> assert_match(/SELECT .*?FROM .?developers.?/i, @logger.logged(:debug).last)
<ide> end
<ide>
<add> def test_exists_query_logging
<add> Developer.exists? 1
<add> wait
<add> assert_equal 1, @logger.logged(:debug).size
<add> assert_match(/Developer Exists/, @logger.logged(:debug).last)
<add> assert_match(/SELECT .*?FROM .?developers.?/i, @logger.logged(:debug).last)
<add> end
<add>
<ide> def test_cached_queries
<ide> ActiveRecord::Base.cache do
<ide> Developer.all | 2 |
Python | Python | add test utils for temp file and temp dir | 9692c98f5715f91e1e10fdae1f218035557c6c95 | <ide><path>spacy/tests/util.py
<ide>
<ide> from ..tokens import Doc
<ide> from ..attrs import ORTH, POS, HEAD, DEP
<add>from ..compat import path2str
<ide>
<ide> import pytest
<ide> import numpy
<add>import tempfile
<add>import shutil
<add>import contextlib
<add>from pathlib import Path
<ide>
<ide>
<ide> MODELS = {}
<ide> def load_test_model(model):
<ide> return MODELS[model]
<ide>
<ide>
<add>@contextlib.contextmanager
<add>def make_tempfile(mode='r'):
<add> f = tempfile.TemporaryFile(mode=mode)
<add> yield f
<add> f.close()
<add>
<add>
<add>@contextlib.contextmanager
<add>def make_tempdir():
<add> d = Path(tempfile.mkdtemp())
<add> yield d
<add> shutil.rmtree(path2str(d))
<add>
<add>
<ide> def get_doc(vocab, words=[], pos=None, heads=None, deps=None, tags=None, ents=None):
<ide> """Create Doc object from given vocab, words and annotations."""
<ide> pos = pos or [''] * len(words) | 1 |
Text | Text | add missing whitespace | 73cf859e26608e1310c07df789553fa2b6cd1f8b | <ide><path>docs/api-guide/permissions.md
<ide> This permission is suitable if you want your API to only be accessible to regist
<ide>
<ide> ## IsAdminUser
<ide>
<del>The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff`is `True` in which case permission will be allowed.
<add>The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
<ide>
<ide> This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.
<ide> | 1 |
PHP | PHP | use container contract | 6980562a507693630bc7572c9756c0dee4a0ce7c | <ide><path>src/Illuminate/Database/Connectors/ConnectionFactory.php
<ide> <?php namespace Illuminate\Database\Connectors;
<ide>
<ide> use PDO;
<del>use Illuminate\Container\Container;
<add>use Illuminate\Contracts\Container\Container;
<ide> use Illuminate\Database\MySqlConnection;
<ide> use Illuminate\Database\SQLiteConnection;
<ide> use Illuminate\Database\PostgresConnection;
<ide> class ConnectionFactory {
<ide> /**
<ide> * The IoC container instance.
<ide> *
<del> * @var \Illuminate\Container\Container
<add> * @var \Illuminate\Contracts\Container\Container
<ide> */
<ide> protected $container;
<ide>
<ide> /**
<ide> * Create a new connection factory instance.
<ide> *
<del> * @param \Illuminate\Container\Container $container
<add> * @param \Illuminate\Contracts\Container\Container $container
<ide> * @return void
<ide> */
<ide> public function __construct(Container $container) | 1 |
Javascript | Javascript | remove the opacity css hook | 865469f5e60f55feb28469bb0a7526dd22f04b4e | <ide><path>src/css.js
<ide> jQuery.extend( {
<ide>
<ide> // Add in style property hooks for overriding the default
<ide> // behavior of getting and setting a style property
<del> cssHooks: {
<del> opacity: {
<del> get: function( elem, computed ) {
<del> if ( computed ) {
<del>
<del> // We should always get a number back from opacity
<del> var ret = curCSS( elem, "opacity" );
<del> return ret === "" ? "1" : ret;
<del> }
<del> }
<del> }
<del> },
<add> cssHooks: {},
<ide>
<ide> // Get and set the style property on a DOM Node
<ide> style: function( elem, name, value, extra ) { | 1 |
Java | Java | improve invocablehandlermethod error handling | 1051fe7bee67f17e284d4f8cb144242bdaf27b31 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/invocation/InvocableHandlerMethod.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> protected Object doInvoke(Object... args) throws Exception {
<ide> }
<ide> catch (IllegalArgumentException ex) {
<ide> assertTargetBean(getBridgedMethod(), getBean(), args);
<del> String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument");
<add> String text = (ex.getMessage() == null || ex.getCause() instanceof NullPointerException)
<add> ? "Illegal argument": ex.getMessage();
<ide> throw new IllegalStateException(formatInvokeError(text, args), ex);
<ide> }
<ide> catch (InvocationTargetException ex) {
<ide><path>spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java
<ide> protected Object doInvoke(Object... args) throws Exception {
<ide> }
<ide> catch (IllegalArgumentException ex) {
<ide> assertTargetBean(method, getBean(), args);
<del> String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument");
<add> String text = (ex.getMessage() == null || ex.getCause() instanceof NullPointerException)
<add> ? "Illegal argument": ex.getMessage();
<ide> throw new IllegalStateException(formatInvokeError(text, args), ex);
<ide> }
<ide> catch (InvocationTargetException ex) { | 2 |
Text | Text | fix embeddedappios documentation | 16a29b0b8701697372ed40dfa4874d66edb6f77c | <ide><path>docs/EmbeddedAppIOS.md
<ide> NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.b
<ide> // curl http://localhost:8081/index.ios.bundle -o main.jsbundle
<ide> RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
<ide> moduleName: @"SimpleApp"
<add> initialProperties:nil
<ide> launchOptions:nil];
<ide> ```
<ide> | 1 |
Javascript | Javascript | remove unnecessary changes | 34d90b9bbd070455f0ca4b46016559b48b495e0c | <ide><path>examples/counter/containers/App.js
<ide> import React from 'react';
<ide> import CounterApp from './CounterApp';
<del>import { createStore } from 'redux/index';
<add>import { createStore } from 'redux';
<ide> import { Provider } from 'redux/react';
<ide> import * as reducers from '../reducers';
<ide>
<ide><path>examples/counter/containers/CounterApp.js
<ide> import React from 'react';
<del>import { bindActionCreators } from 'redux/index';
<add>import { bindActionCreators } from 'redux';
<ide> import { connect } from 'redux/react';
<ide> import Counter from '../components/Counter';
<ide> import * as CounterActions from '../actions/CounterActions';
<ide><path>examples/todomvc/containers/App.js
<ide> import React from 'react';
<ide> import TodoApp from './TodoApp';
<del>import { createStore, composeReducers } from 'redux/index';
<add>import { createStore } from 'redux';
<ide> import { Provider } from 'redux/react';
<ide> import * as reducers from '../reducers';
<ide>
<del>const reducer = composeReducers(reducers);
<del>const store = createStore(reducer);
<add>const store = createStore(reducers);
<ide>
<ide> export default class App {
<ide> render() {
<ide><path>examples/todomvc/containers/TodoApp.js
<ide> import React from 'react';
<del>import { bindActionCreators } from 'redux/index';
<add>import { bindActionCreators } from 'redux';
<ide> import { Connector } from 'redux/react';
<ide> import Header from '../components/Header';
<ide> import MainSection from '../components/MainSection'; | 4 |
Mixed | Ruby | fix method string#upcase_first | f2489f493b794ee83a86e746b6240031acb8994e | <ide><path>activesupport/CHANGELOG.md
<ide> * Add `String#upcase_first` method.
<ide>
<del> *Glauco Custódio*
<add> *Glauco Custódio*, *bogdanvlviv*
<ide>
<ide> * Prevent `Marshal.load` from looping infinitely when trying to autoload a constant
<ide> which resolves to a different name.
<ide><path>activesupport/lib/active_support/core_ext/string/inflections.rb
<ide> def humanize(options = {})
<ide>
<ide> # Converts just the first character to uppercase.
<ide> #
<del> # 'what a Lovely Day'.upcase_first # => "What a Lovely Day"
<add> # 'what a Lovely Day'.upcase_first # => "What a Lovely Day"
<add> # 'w'.upcase_first # => "W"
<add> # ''.upcase_first # => ""
<ide> def upcase_first
<ide> ActiveSupport::Inflector.upcase_first(self)
<ide> end
<ide><path>activesupport/lib/active_support/inflector/methods.rb
<ide> def humanize(lower_case_and_underscored_word, options = {})
<ide>
<ide> # Converts just the first character to uppercase.
<ide> #
<del> # 'what a Lovely Day'.upcase_first # => "What a Lovely Day"
<add> # upcase_first('what a Lovely Day') # => "What a Lovely Day"
<add> # upcase_first('w') # => "W"
<add> # upcase_first('') # => ""
<ide> def upcase_first(string)
<del> string[0].upcase.concat(string[1..-1])
<add> string.length > 0 ? string[0].upcase.concat(string[1..-1]) : ''
<ide> end
<ide>
<ide> # Capitalizes all the words and replaces some characters in the string to
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def test_upcase_first
<ide> assert_equal "What a Lovely Day", "what a Lovely Day".upcase_first
<ide> end
<ide>
<add> def test_upcase_first_with_one_char
<add> assert_equal "W", "w".upcase_first
<add> end
<add>
<add> def test_upcase_first_with_empty_string
<add> assert_equal "", "".upcase_first
<add> end
<add>
<ide> def test_camelize
<ide> CamelToUnderscore.each do |camel, underscore|
<ide> assert_equal(camel, underscore.camelize) | 4 |
Text | Text | use null instead of '' in ternary expression | b74e53c3ca730f1997dbfb53555348aeaa6db2ee | <ide><path>docs/tips/03-if-else-in-JSX.md
<ide> React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
<ide> That's not valid JS. You probably want to make use of a ternary expression:
<ide>
<ide> ```js
<del>ReactDOM.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);
<add>ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);
<ide> ```
<ide>
<ide> If a ternary expression isn't robust enough, you can use `if` statements outside of your JSX to determine which components should be used: | 1 |
Java | Java | correct the javadoc for exchangeresult.geturl() | bc2e1b375e399c0cc6300c32351458110eee6d4f | <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/ExchangeResult.java
<ide> public HttpMethod getMethod() {
<ide> }
<ide>
<ide> /**
<del> * Return the request headers that were sent to the server.
<add> * Return the URI of the request.
<ide> */
<ide> public URI getUrl() {
<ide> return this.request.getURI(); | 1 |
Javascript | Javascript | fix frisian locale tests | 894ab4f845977c3c9bce2262befb225ffed341e4 | <ide><path>test/locale/fy.js
<ide> exports['locale:fy'] = {
<ide> },
<ide>
<ide> 'parse' : function (test) {
<del> var tests = 'jannewaris jan._febrewaris feb._maart mrt._april apr._maaie mai._juny jun._july jul._augustus aug._septimber sep._oktober okt._novimber nov._desimber dec.'.split('_'), i;
<add> var tests = 'jannewaris jan._febrewaris feb._maart mrt._april apr._maaie mai._juny jun._july jul._augustus aug._septimber sep._oktober okt._novimber nov._desimber des.'.split('_'), i;
<ide> function equalTest(input, mmm, i) {
<ide> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
<ide> } | 1 |
Javascript | Javascript | add doc for native event in doc | da850be6f0e0452b92e10a787d85b67b315b690c | <ide><path>Libraries/vendor/react/browser/eventPlugins/PanResponder.js
<ide> var currentCentroidY = TouchHistoryMath.currentCentroidY;
<ide> * It provides a predictable wrapper of the responder handlers provided by the
<ide> * [gesture responder system](/react-native/docs/gesture-responder-system.html).
<ide> * For each handler, it provides a new `gestureState` object alongside the
<del> * normal event.
<add> * native event object:
<add> *
<add> * ```
<add> * onPanResponderMove: (event, gestureState) => {}
<add> * ```
<add> *
<add> * A native event is a synthetic touch event with the following form:
<add> *
<add> * - `nativeEvent`
<add> * + `changedTouches` - Array of all touch events that have changed since the last event
<add> * + `identifier` - The ID of the touch
<add> * + `locationX` - The X position of the touch, relative to the element
<add> * + `locationY` - The Y position of the touch, relative to the element
<add> * + `pageX` - The X position of the touch, relative to the root element
<add> * + `pageY` - The Y position of the touch, relative to the root element
<add> * + `target` - The node id of the element receiving the touch event
<add> * + `timestamp` - A time identifier for the touch, useful for velocity calculation
<add> * + `touches` - Array of all current touches on the screen
<ide> *
<ide> * A `gestureState` object has the following:
<ide> * | 1 |
Javascript | Javascript | use process.browser instead of env probing | 04ce3e7174e67b8bcc8749ecc2bb437edc953fb3 | <ide><path>examples/with-mobx/pages/_app.js
<ide> class MyMobxApp extends App {
<ide>
<ide> constructor(props) {
<ide> super(props)
<del> const isServer = typeof window === 'undefined'
<add> const isServer = !process.browser;
<ide> this.mobxStore = isServer
<ide> ? props.initialMobxState
<ide> : initializeStore(props.initialMobxState)
<ide><path>examples/with-mobx/store.js
<ide> import { action, observable } from 'mobx'
<ide> import { useStaticRendering } from 'mobx-react'
<ide>
<del>const isServer = typeof window === 'undefined'
<add>const isServer = !process.browser
<ide> useStaticRendering(isServer)
<ide>
<ide> class Store {
<ide> class Store {
<ide> }
<ide>
<ide> let store = null
<del>export function initializeStore(initialData) {
<add>
<add>export function initializeStore (initialData) {
<ide> // Always make a new store if server, otherwise state is shared between requests
<ide> if (isServer) {
<ide> return new Store(isServer, initialData) | 2 |
Go | Go | remove dependency on image | 9be1ec60d4d4fe63d5ef6e1ec36c585b548a00d0 | <ide><path>builder/builder.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/daemon"
<del> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<ide> type Backend interface {
<ide> // TODO: use digest reference instead of name
<ide>
<ide> // GetImage looks up a Docker image referenced by `name`.
<del> GetImage(name string) (*image.Image, error)
<add> GetImage(name string) (Image, error)
<ide> // Pull tells Docker to pull image referenced by `name`.
<del> Pull(name string) (*image.Image, error)
<add> Pull(name string) (Image, error)
<ide> // ContainerWsAttachWithLogs attaches to container.
<ide> ContainerWsAttachWithLogs(name string, cfg *daemon.ContainerWsAttachWithLogsConfig) error
<ide> // ContainerCreate creates a new Docker container and returns potential warnings
<ide><path>builder/dockerfile/dispatchers.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/builder"
<ide> derr "github.com/docker/docker/errors"
<del> "github.com/docker/docker/image"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/nat"
<ide> "github.com/docker/docker/pkg/signal"
<ide> func from(b *Builder, args []string, attributes map[string]bool, original string
<ide> }
<ide>
<ide> var (
<del> image *image.Image
<add> image builder.Image
<ide> err error
<ide> )
<ide> // TODO: don't use `name`, instead resolve it to a digest
<ide><path>builder/dockerfile/internals.go
<ide> import (
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builder/dockerfile/parser"
<ide> "github.com/docker/docker/daemon"
<del> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/httputils"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> func containsWildcards(name string) bool {
<ide> return false
<ide> }
<ide>
<del>func (b *Builder) processImageFrom(img *image.Image) error {
<del> b.image = img.ID().String()
<add>func (b *Builder) processImageFrom(img builder.Image) error {
<add> b.image = img.ID()
<ide>
<ide> if img.Config != nil {
<del> b.runConfig = img.Config
<add> b.runConfig = img.Config()
<ide> }
<ide>
<ide> // The default path will be blank on Windows (set by HCS)
<ide><path>builder/image.go
<add>package builder
<add>
<add>import "github.com/docker/docker/runconfig"
<add>
<add>// Image represents a Docker image used by the builder.
<add>type Image interface {
<add> ID() string
<add> Config() *runconfig.Config
<add>}
<ide><path>daemon/daemonbuilder/builder.go
<ide> type Docker struct {
<ide> var _ builder.Backend = Docker{}
<ide>
<ide> // Pull tells Docker to pull image referenced by `name`.
<del>func (d Docker) Pull(name string) (*image.Image, error) {
<add>func (d Docker) Pull(name string) (builder.Image, error) {
<ide> ref, err := reference.ParseNamed(name)
<ide> if err != nil {
<ide> return nil, err
<ide> func (d Docker) Pull(name string) (*image.Image, error) {
<ide> if err := d.Daemon.PullImage(ref, nil, pullRegistryAuth, ioutils.NopWriteCloser(d.OutOld)); err != nil {
<ide> return nil, err
<ide> }
<add> return d.GetImage(name)
<add>}
<ide>
<del> return d.Daemon.GetImage(name)
<add>// GetImage looks up a Docker image referenced by `name`.
<add>func (d Docker) GetImage(name string) (builder.Image, error) {
<add> img, err := d.Daemon.GetImage(name)
<add> if err != nil {
<add> return nil, err
<add> }
<add> return imgWrap{img}, nil
<ide> }
<ide>
<ide> // ContainerUpdateCmd updates Path and Args for the container with ID cID.
<ide> func (d Docker) ContainerUpdateCmd(cID string, cmd []string) error {
<ide> return nil
<ide> }
<ide>
<del>// Retain retains an image avoiding it to be removed or overwritten until a corresponding Release() call.
<del>func (d Docker) Retain(sessionID, imgID string) {
<del> // FIXME: This will be solved with tags in client-side builder
<del> //d.Daemon.Graph().Retain(sessionID, imgID)
<del>}
<del>
<del>// Release releases a list of images that were retained for the time of a build.
<del>func (d Docker) Release(sessionID string, activeImages []string) {
<del> // FIXME: This will be solved with tags in client-side builder
<del> //d.Daemon.Graph().Release(sessionID, activeImages...)
<del>}
<del>
<ide> // BuilderCopy copies/extracts a source FileInfo to a destination path inside a container
<ide> // specified by a container object.
<ide> // TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
<ide><path>daemon/daemonbuilder/image.go
<add>package daemonbuilder
<add>
<add>import (
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/runconfig"
<add>)
<add>
<add>type imgWrap struct {
<add> inner *image.Image
<add>}
<add>
<add>func (img imgWrap) ID() string {
<add> return string(img.inner.ID())
<add>}
<add>
<add>func (img imgWrap) Config() *runconfig.Config {
<add> return img.inner.Config
<add>} | 6 |
Javascript | Javascript | use sourcemapdevtool default | dd2c4de1cef7c29df9da3a6fb9e5ec1b31c6430d | <ide><path>lib/WebpackOptionsApply.js
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> new ModuleInfoHeaderPlugin().apply(compiler);
<ide> }
<ide>
<del> if (options.devtool && options.devtool.includes("source-map")) {
<del> const hidden = options.devtool.includes("hidden");
<del> const inline = options.devtool.includes("inline");
<del> const evalWrapped = options.devtool.includes("eval");
<del> const cheap = options.devtool.includes("cheap");
<del> const moduleMaps = options.devtool.includes("module");
<del> const noSources = options.devtool.includes("nosources");
<del> const Plugin = evalWrapped
<del> ? require("./EvalSourceMapDevToolPlugin")
<del> : require("./SourceMapDevToolPlugin");
<del> new Plugin({
<del> filename: inline ? null : options.output.sourceMapFilename,
<del> moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
<del> fallbackModuleFilenameTemplate:
<del> options.output.devtoolFallbackModuleFilenameTemplate,
<del> append: hidden ? false : "\n//# source" + "MappingURL=[url]",
<del> module: moduleMaps ? true : cheap ? false : true,
<del> columns: cheap ? false : true,
<del> noSources: noSources,
<del> namespace: options.output.devtoolNamespace
<del> }).apply(compiler);
<del> } else if (options.devtool && options.devtool.includes("eval")) {
<del> const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
<del> new EvalDevToolModulePlugin({
<del> moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
<del> namespace: options.output.devtoolNamespace
<del> }).apply(compiler);
<add> if (options.devtool) {
<add> if (options.devtool.includes("source-map")) {
<add> const hidden = options.devtool.includes("hidden");
<add> const inline = options.devtool.includes("inline");
<add> const evalWrapped = options.devtool.includes("eval");
<add> const cheap = options.devtool.includes("cheap");
<add> const moduleMaps = options.devtool.includes("module");
<add> const noSources = options.devtool.includes("nosources");
<add> const Plugin = evalWrapped
<add> ? require("./EvalSourceMapDevToolPlugin")
<add> : require("./SourceMapDevToolPlugin");
<add> new Plugin({
<add> filename: inline ? null : options.output.sourceMapFilename,
<add> moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
<add> fallbackModuleFilenameTemplate:
<add> options.output.devtoolFallbackModuleFilenameTemplate,
<add> append: hidden ? false : undefined,
<add> module: moduleMaps ? true : cheap ? false : true,
<add> columns: cheap ? false : true,
<add> noSources: noSources,
<add> namespace: options.output.devtoolNamespace
<add> }).apply(compiler);
<add> } else if (options.devtool.includes("eval")) {
<add> const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
<add> new EvalDevToolModulePlugin({
<add> moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
<add> namespace: options.output.devtoolNamespace
<add> }).apply(compiler);
<add> }
<ide> }
<ide>
<ide> new JavascriptModulesPlugin().apply(compiler); | 1 |
Javascript | Javascript | add test case | d6f4ccca8ec2ceef1a9929b3222c3164f61302cb | <ide><path>test/configCases/externals/this/index.js
<add>afterEach(done => {
<add> (function() { delete this.EXTERNAL_TEST_GLOBAL; })();
<add> done();
<add>});
<add>
<add>it("should import an external value assigned to global this", function() {
<add> (function() { this.EXTERNAL_TEST_GLOBAL = 42; })();
<add> // eslint-disable-next-line node/no-missing-require
<add> const result = require("external");
<add> expect(result).toBe(42);
<add>});
<ide><path>test/configCases/externals/this/webpack.config.js
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> optimization: {
<add> concatenateModules: true
<add> },
<add> externals: {
<add> external: "this EXTERNAL_TEST_GLOBAL"
<add> }
<add>}; | 2 |
Ruby | Ruby | remove nonexistent adapter | f5ae2894c34d72bbf9c358ccedf5dfd20d7641fd | <ide><path>activejob/lib/active_job/queue_adapters.rb
<ide> module ActiveJob
<ide> # | Sneakers | Yes | Yes | No | Queue | Queue | No |
<ide> # | Sucker Punch | Yes | Yes | No | No | No | No |
<ide> # | Active Job Inline | No | Yes | N/A | N/A | N/A | N/A |
<del> # | Active Job | Yes | Yes | Yes | No | No | No |
<ide> #
<ide> # ==== Async
<ide> # | 1 |
Python | Python | remove duplicated code in quicklook plugin | 7dfe1f41390389f0d0a42d1da1d3ce3f745ff538 | <ide><path>glances/plugins/glances_quicklook.py
<ide> def msg_curse(self, args=None, max_width=10):
<ide> msg = '{0:3}{1} '.format(key.upper(), cpu['cpu_number'])
<ide> else:
<ide> msg = '{0:4} '.format(cpu['cpu_number'])
<del> ret.append(self.curse_add_line(msg))
<del> ret.append(self.curse_add_line(bar.pre_char, decoration='BOLD'))
<del> ret.append(self.curse_add_line(str(bar), self.get_views(key=key, option='decoration')))
<del> ret.append(self.curse_add_line(bar.post_char, decoration='BOLD'))
<del> ret.append(self.curse_add_line(' '))
<del> ret.append(self.curse_new_line())
<add> ret.extend(self._msg_create_line(msg, bar, key))
<ide> else:
<ide> bar.percent = self.stats[key]
<ide> msg = '{0:4} '.format(key.upper())
<del> ret.append(self.curse_add_line(msg))
<del> ret.append(self.curse_add_line(bar.pre_char, decoration='BOLD'))
<del> ret.append(self.curse_add_line(str(bar), self.get_views(key=key, option='decoration')))
<del> ret.append(self.curse_add_line(bar.post_char, decoration='BOLD'))
<del> ret.append(self.curse_add_line(' '))
<del> ret.append(self.curse_new_line())
<add> ret.extend(self._msg_create_line(msg, bar, key))
<ide>
<ide> # Return the message with decoration
<ide> return ret
<ide>
<add> def _msg_create_line(self, msg, bar, key):
<add> """Create a new line to the Quickview"""
<add> ret = []
<add>
<add> ret.append(self.curse_add_line(msg))
<add> ret.append(self.curse_add_line(bar.pre_char, decoration='BOLD'))
<add> ret.append(self.curse_add_line(str(bar), self.get_views(key=key, option='decoration')))
<add> ret.append(self.curse_add_line(bar.post_char, decoration='BOLD'))
<add> ret.append(self.curse_add_line(' '))
<add> ret.append(self.curse_new_line())
<add>
<add> return ret
<add>
<ide> def _hz_to_ghz(self, hz):
<ide> """Convert Hz to Ghz"""
<ide> return hz / 1000000000.0 | 1 |
Mixed | Ruby | use the port environment variable for rails server | 306c14c41135dc8d308967821d0bb26cf4bb7ecd | <ide><path>railties/CHANGELOG.md
<add>* `rails server` will now honour the `PORT` environment variable
<add>
<add> *David Cornu*
<add>
<ide> * Plugins generated using `rails plugin new` are now generated with the
<ide> version number set to 0.1.0.
<ide>
<ide><path>railties/lib/rails/commands/server.rb
<ide> def middleware
<ide>
<ide> def default_options
<ide> super.merge({
<del> Port: 3000,
<add> Port: ENV.fetch('PORT', 3000).to_i,
<ide> DoNotReverseLookup: true,
<ide> environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup,
<ide> daemonize: false,
<ide><path>railties/test/commands/server_test.rb
<ide> def test_environment_with_rack_env
<ide> end
<ide> end
<ide>
<add> def test_environment_with_port
<add> switch_env "PORT", "1234" do
<add> server = Rails::Server.new
<add> assert_equal 1234, server.options[:Port]
<add> end
<add> end
<add>
<ide> def test_caching_without_option
<ide> args = []
<ide> options = Rails::Server::Options.new.parse!(args) | 3 |
Go | Go | add missing locks in agent and service code | fac86cf69ab8f18341f75b26b4fb721dde139f6a | <ide><path>libnetwork/agent.go
<ide> import (
<ide> "net"
<ide> "os"
<ide> "sort"
<add> "sync"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> type agent struct {
<ide> advertiseAddr string
<ide> epTblCancel func()
<ide> driverCancelFuncs map[string][]func()
<add> sync.Mutex
<ide> }
<ide>
<ide> func getBindAddr(ifaceName string) (string, error) {
<ide> func resolveAddr(addrOrInterface string) (string, error) {
<ide> func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error {
<ide> drvEnc := discoverapi.DriverEncryptionUpdate{}
<ide>
<del> a := c.agent
<add> a := c.getAgent()
<add> if a == nil {
<add> logrus.Debug("Skipping key change as agent is nil")
<add> return nil
<add> }
<add>
<ide> // Find the deleted key. If the deleted key was the primary key,
<ide> // a new primary key should be set before removing if from keyring.
<add> c.Lock()
<add> added := []byte{}
<ide> deleted := []byte{}
<ide> j := len(c.keys)
<ide> for i := 0; i < j; {
<ide> func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error {
<ide> if !same {
<ide> c.keys = append(c.keys, key)
<ide> if key.Subsystem == subsysGossip {
<del> a.networkDB.SetKey(key.Key)
<add> added = key.Key
<ide> }
<ide>
<ide> if key.Subsystem == subsysIPSec {
<ide> func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error {
<ide> }
<ide> }
<ide> }
<add> c.Unlock()
<add>
<add> if len(added) > 0 {
<add> a.networkDB.SetKey(added)
<add> }
<ide>
<ide> key, tag, err := c.getPrimaryKeyTag(subsysGossip)
<ide> if err != nil {
<ide> func (c *controller) handleKeyChange(keys []*types.EncryptionKey) error {
<ide> }
<ide>
<ide> func (c *controller) agentSetup() error {
<add> c.Lock()
<ide> clusterProvider := c.cfg.Daemon.ClusterProvider
<del>
<add> agent := c.agent
<add> c.Unlock()
<ide> bindAddr := clusterProvider.GetLocalAddress()
<ide> advAddr := clusterProvider.GetAdvertiseAddress()
<ide> remote := clusterProvider.GetRemoteAddress()
<ide> func (c *controller) agentSetup() error {
<ide> listenAddr, _, _ := net.SplitHostPort(listen)
<ide>
<ide> logrus.Infof("Initializing Libnetwork Agent Listen-Addr=%s Local-addr=%s Adv-addr=%s Remote-addr =%s", listenAddr, bindAddr, advAddr, remoteAddr)
<del> if advAddr != "" && c.agent == nil {
<add> if advAddr != "" && agent == nil {
<ide> if err := c.agentInit(listenAddr, bindAddr, advAddr); err != nil {
<ide> logrus.Errorf("Error in agentInit : %v", err)
<ide> } else {
<ide> func (c *controller) agentSetup() error {
<ide> // For a given subsystem getKeys sorts the keys by lamport time and returns
<ide> // slice of keys and lamport time which can used as a unique tag for the keys
<ide> func (c *controller) getKeys(subsys string) ([][]byte, []uint64) {
<add> c.Lock()
<add> defer c.Unlock()
<add>
<ide> sort.Sort(ByTime(c.keys))
<ide>
<ide> keys := [][]byte{}
<ide> func (c *controller) getKeys(subsys string) ([][]byte, []uint64) {
<ide> // getPrimaryKeyTag returns the primary key for a given subsystem from the
<ide> // list of sorted key and the associated tag
<ide> func (c *controller) getPrimaryKeyTag(subsys string) ([]byte, uint64, error) {
<add> c.Lock()
<add> defer c.Unlock()
<ide> sort.Sort(ByTime(c.keys))
<ide> keys := []*types.EncryptionKey{}
<ide> for _, key := range c.keys {
<ide> func (c *controller) agentInit(listenAddr, bindAddrOrInterface, advertiseAddr st
<ide>
<ide> ch, cancel := nDB.Watch("endpoint_table", "", "")
<ide>
<add> c.Lock()
<ide> c.agent = &agent{
<ide> networkDB: nDB,
<ide> bindAddr: bindAddr,
<ide> advertiseAddr: advertiseAddr,
<ide> epTblCancel: cancel,
<ide> driverCancelFuncs: make(map[string][]func()),
<ide> }
<add> c.Unlock()
<ide>
<ide> go c.handleTableEvents(ch, c.handleEpTableEvent)
<ide>
<ide> func (c *controller) agentInit(listenAddr, bindAddrOrInterface, advertiseAddr st
<ide> }
<ide>
<ide> func (c *controller) agentJoin(remote string) error {
<del> if c.agent == nil {
<add> agent := c.getAgent()
<add> if agent == nil {
<ide> return nil
<ide> }
<del>
<del> return c.agent.networkDB.Join([]string{remote})
<add> return agent.networkDB.Join([]string{remote})
<ide> }
<ide>
<ide> func (c *controller) agentDriverNotify(d driverapi.Driver) {
<del> if c.agent == nil {
<add> agent := c.getAgent()
<add> if agent == nil {
<ide> return
<ide> }
<ide>
<ide> d.DiscoverNew(discoverapi.NodeDiscovery, discoverapi.NodeDiscoveryData{
<del> Address: c.agent.advertiseAddr,
<del> BindAddress: c.agent.bindAddr,
<add> Address: agent.advertiseAddr,
<add> BindAddress: agent.bindAddr,
<ide> Self: true,
<ide> })
<ide>
<ide> func (c *controller) agentClose() {
<ide> return
<ide> }
<ide>
<add> var cancelList []func()
<add>
<add> agent.Lock()
<ide> for _, cancelFuncs := range agent.driverCancelFuncs {
<ide> for _, cancel := range cancelFuncs {
<del> cancel()
<add> cancelList = append(cancelList, cancel)
<ide> }
<ide> }
<add> agent.Unlock()
<add>
<add> for _, cancel := range cancelList {
<add> cancel()
<add> }
<ide>
<ide> agent.epTblCancel()
<ide>
<ide> func (n *network) isClusterEligible() bool {
<ide> if n.driverScope() != datastore.GlobalScope {
<ide> return false
<ide> }
<del>
<del> c := n.getController()
<del> if c.agent == nil {
<del> return false
<del> }
<del>
<del> return true
<add> return n.getController().getAgent() != nil
<ide> }
<ide>
<ide> func (n *network) joinCluster() error {
<ide> if !n.isClusterEligible() {
<ide> return nil
<ide> }
<ide>
<del> c := n.getController()
<del> return c.agent.networkDB.JoinNetwork(n.ID())
<add> agent := n.getController().getAgent()
<add> if agent == nil {
<add> return nil
<add> }
<add>
<add> return agent.networkDB.JoinNetwork(n.ID())
<ide> }
<ide>
<ide> func (n *network) leaveCluster() error {
<ide> if !n.isClusterEligible() {
<ide> return nil
<ide> }
<ide>
<del> c := n.getController()
<del> return c.agent.networkDB.LeaveNetwork(n.ID())
<add> agent := n.getController().getAgent()
<add> if agent == nil {
<add> return nil
<add> }
<add>
<add> return agent.networkDB.LeaveNetwork(n.ID())
<ide> }
<ide>
<ide> func (ep *endpoint) addDriverInfoToCluster() error {
<ide> func (ep *endpoint) addDriverInfoToCluster() error {
<ide> return nil
<ide> }
<ide>
<del> ctrlr := n.ctrlr
<del> ctrlr.Lock()
<del> agent := ctrlr.agent
<del> ctrlr.Unlock()
<add> agent := n.getController().getAgent()
<ide> if agent == nil {
<ide> return nil
<ide> }
<ide> func (ep *endpoint) deleteDriverInfoFromCluster() error {
<ide> return nil
<ide> }
<ide>
<del> ctrlr := n.ctrlr
<del> ctrlr.Lock()
<del> agent := ctrlr.agent
<del> ctrlr.Unlock()
<add> agent := n.getController().getAgent()
<ide> if agent == nil {
<ide> return nil
<ide> }
<ide> func (ep *endpoint) addServiceInfoToCluster() error {
<ide> }
<ide>
<ide> c := n.getController()
<add> agent := c.getAgent()
<ide> if !ep.isAnonymous() && ep.Iface().Address() != nil {
<ide> var ingressPorts []*PortConfig
<ide> if ep.svcID != "" {
<ide> func (ep *endpoint) addServiceInfoToCluster() error {
<ide> return err
<ide> }
<ide>
<del> if err := c.agent.networkDB.CreateEntry("endpoint_table", n.ID(), ep.ID(), buf); err != nil {
<del> return err
<add> if agent != nil {
<add> if err := agent.networkDB.CreateEntry("endpoint_table", n.ID(), ep.ID(), buf); err != nil {
<add> return err
<add> }
<ide> }
<ide> }
<ide>
<ide> func (ep *endpoint) deleteServiceInfoFromCluster() error {
<ide> }
<ide>
<ide> c := n.getController()
<add> agent := c.getAgent()
<add>
<ide> if !ep.isAnonymous() {
<ide> if ep.svcID != "" && ep.Iface().Address() != nil {
<ide> var ingressPorts []*PortConfig
<ide> func (ep *endpoint) deleteServiceInfoFromCluster() error {
<ide> return err
<ide> }
<ide> }
<del>
<del> if err := c.agent.networkDB.DeleteEntry("endpoint_table", n.ID(), ep.ID()); err != nil {
<del> return err
<add> if agent != nil {
<add> if err := agent.networkDB.DeleteEntry("endpoint_table", n.ID(), ep.ID()); err != nil {
<add> return err
<add> }
<ide> }
<ide> }
<ide> return nil
<ide> func (n *network) addDriverWatches() {
<ide> }
<ide>
<ide> c := n.getController()
<add> agent := c.getAgent()
<add> if agent == nil {
<add> return
<add> }
<ide> for _, tableName := range n.driverTables {
<del> c.Lock()
<del> if c.agent == nil {
<del> c.Unlock()
<del> return
<del> }
<del> ch, cancel := c.agent.networkDB.Watch(tableName, n.ID(), "")
<del> c.agent.driverCancelFuncs[n.ID()] = append(c.agent.driverCancelFuncs[n.ID()], cancel)
<del> c.Unlock()
<del>
<add> ch, cancel := agent.networkDB.Watch(tableName, n.ID(), "")
<add> agent.Lock()
<add> agent.driverCancelFuncs[n.ID()] = append(agent.driverCancelFuncs[n.ID()], cancel)
<add> agent.Unlock()
<ide> go c.handleTableEvents(ch, n.handleDriverTableEvent)
<ide> d, err := n.driver(false)
<ide> if err != nil {
<ide> logrus.Errorf("Could not resolve driver %s while walking driver tabl: %v", n.networkType, err)
<ide> return
<ide> }
<ide>
<del> c.agent.networkDB.WalkTable(tableName, func(nid, key string, value []byte) bool {
<add> agent.networkDB.WalkTable(tableName, func(nid, key string, value []byte) bool {
<ide> if nid == n.ID() {
<ide> d.EventNotify(driverapi.Create, nid, tableName, key, value)
<ide> }
<ide> func (n *network) cancelDriverWatches() {
<ide> return
<ide> }
<ide>
<del> c := n.getController()
<del> c.Lock()
<del> cancelFuncs := c.agent.driverCancelFuncs[n.ID()]
<del> delete(c.agent.driverCancelFuncs, n.ID())
<del> c.Unlock()
<add> agent := n.getController().getAgent()
<add> if agent == nil {
<add> return
<add> }
<add>
<add> agent.Lock()
<add> cancelFuncs := agent.driverCancelFuncs[n.ID()]
<add> delete(agent.driverCancelFuncs, n.ID())
<add> agent.Unlock()
<ide>
<ide> for _, cancel := range cancelFuncs {
<ide> cancel()
<ide><path>libnetwork/controller.go
<ide> func New(cfgOptions ...config.Option) (NetworkController, error) {
<ide>
<ide> func (c *controller) SetClusterProvider(provider cluster.Provider) {
<ide> c.Lock()
<del> defer c.Unlock()
<ide> c.cfg.Daemon.ClusterProvider = provider
<add> disableProviderCh := c.cfg.Daemon.DisableProvider
<add> c.Unlock()
<ide> if provider != nil {
<ide> go c.clusterAgentInit()
<ide> } else {
<del> c.cfg.Daemon.DisableProvider <- struct{}{}
<add> disableProviderCh <- struct{}{}
<ide> }
<ide> }
<ide>
<ide> func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
<ide> return c.handleKeyChange(keys)
<ide> }
<ide>
<add>func (c *controller) getAgent() *agent {
<add> c.Lock()
<add> defer c.Unlock()
<add> return c.agent
<add>}
<add>
<ide> func (c *controller) clusterAgentInit() {
<ide> clusterProvider := c.cfg.Daemon.ClusterProvider
<ide> for {
<ide><path>libnetwork/network.go
<ide> func (n *network) Peers() []networkdb.PeerInfo {
<ide> return []networkdb.PeerInfo{}
<ide> }
<ide>
<del> var nDB *networkdb.NetworkDB
<del> n.ctrlr.Lock()
<del> if n.ctrlr.agentInitDone == nil && n.ctrlr.agent != nil {
<del> nDB = n.ctrlr.agent.networkDB
<add> agent := n.getController().getAgent()
<add> if agent == nil {
<add> return []networkdb.PeerInfo{}
<ide> }
<del> n.ctrlr.Unlock()
<ide>
<del> if nDB != nil {
<del> return n.ctrlr.agent.networkDB.Peers(n.id)
<del> }
<del> return []networkdb.PeerInfo{}
<add> return agent.networkDB.Peers(n.ID())
<ide> }
<ide>
<ide> func (n *network) DriverOptions() map[string]string {
<ide><path>libnetwork/networkdb/cluster.go
<ide> func (l *logWriter) Write(p []byte) (int, error) {
<ide> // SetKey adds a new key to the key ring
<ide> func (nDB *NetworkDB) SetKey(key []byte) {
<ide> logrus.Debugf("Adding key %s", hex.EncodeToString(key)[0:5])
<add> nDB.Lock()
<add> defer nDB.Unlock()
<ide> for _, dbKey := range nDB.config.Keys {
<ide> if bytes.Equal(key, dbKey) {
<ide> return
<ide> func (nDB *NetworkDB) SetKey(key []byte) {
<ide> // been added apriori through SetKey
<ide> func (nDB *NetworkDB) SetPrimaryKey(key []byte) {
<ide> logrus.Debugf("Primary Key %s", hex.EncodeToString(key)[0:5])
<add> nDB.RLock()
<add> defer nDB.RUnlock()
<ide> for _, dbKey := range nDB.config.Keys {
<ide> if bytes.Equal(key, dbKey) {
<ide> if nDB.keyring != nil {
<ide> func (nDB *NetworkDB) SetPrimaryKey(key []byte) {
<ide> // can't be the primary key
<ide> func (nDB *NetworkDB) RemoveKey(key []byte) {
<ide> logrus.Debugf("Remove Key %s", hex.EncodeToString(key)[0:5])
<add> nDB.Lock()
<add> defer nDB.Unlock()
<ide> for i, dbKey := range nDB.config.Keys {
<ide> if bytes.Equal(key, dbKey) {
<ide> nDB.config.Keys = append(nDB.config.Keys[:i], nDB.config.Keys[i+1:]...)
<ide><path>libnetwork/service_common.go
<ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in
<ide>
<ide> c.Lock()
<ide> s, ok := c.serviceBindings[skey]
<add> c.Unlock()
<ide> if !ok {
<del> c.Unlock()
<ide> return nil
<ide> }
<del> c.Unlock()
<ide>
<ide> s.Lock()
<ide> lb, ok := s.loadBalancers[nid]
<ide> func (c *controller) rmServiceBinding(name, sid, nid, eid string, vip net.IP, in
<ide> if len(s.loadBalancers) == 0 {
<ide> // All loadbalancers for the service removed. Time to
<ide> // remove the service itself.
<add> c.Lock()
<ide> delete(c.serviceBindings, skey)
<add> c.Unlock()
<ide> }
<ide>
<ide> // Remove loadbalancer service(if needed) and backend in all
<ide><path>libnetwork/service_linux.go
<ide> func init() {
<ide> func (n *network) connectedLoadbalancers() []*loadBalancer {
<ide> c := n.getController()
<ide>
<del> serviceBindings := make([]*service, 0, len(c.serviceBindings))
<ide> c.Lock()
<add> serviceBindings := make([]*service, 0, len(c.serviceBindings))
<ide> for _, s := range c.serviceBindings {
<ide> serviceBindings = append(serviceBindings, s)
<ide> } | 6 |
Ruby | Ruby | make work bin/test scripts with line filter | 2047877f4ed31168317948a848b25a5c36f32c7b | <ide><path>tools/test.rb
<ide> Bundler.setup
<ide>
<ide> require "rails/test_unit/minitest_plugin"
<add>require "rails/test_unit/line_filtering"
<add>require "active_support/test_case"
<ide>
<ide> module Rails
<ide> # Necessary to get rerun-snippts working.
<ide> def self.root
<ide> end
<ide> end
<ide>
<add>ActiveSupport::TestCase.extend Rails::LineFiltering
<ide> Rails::TestUnitReporter.executable = "bin/test"
<ide> Minitest.run_via[:rails] = true
<ide> require "active_support/testing/autorun" | 1 |
Javascript | Javascript | remove side effect of mmdloader.loadvmds() | 0c82ecf8a5b7878ac0dff9e94c621692315d1b6f | <ide><path>examples/js/loaders/MMDLoader.js
<ide> THREE.MMDLoader.prototype.loadVmds = function ( urls, callback, onProgress, onEr
<ide> var scope = this;
<ide>
<ide> var vmds = [];
<add> urls = urls.slice();
<ide>
<ide> function run () {
<ide> | 1 |
Go | Go | use default driver for ipam if none | c3220641274bb99e120a1b3dd64078f02589717b | <ide><path>daemon/cluster/convert/network.go
<ide> func BasicNetworkCreateToGRPC(create basictypes.NetworkCreateRequest) swarmapi.N
<ide> Attachable: create.Attachable,
<ide> }
<ide> if create.IPAM != nil {
<add> driver := create.IPAM.Driver
<add> if driver == "" {
<add> driver = "default"
<add> }
<ide> ns.IPAM = &swarmapi.IPAMOptions{
<ide> Driver: &swarmapi.Driver{
<del> Name: create.IPAM.Driver,
<add> Name: driver,
<ide> Options: create.IPAM.Options,
<ide> },
<ide> } | 1 |
Java | Java | add native support for @exceptionhandler | 45939720f2b96cf2784e9c34a6ca0d627f8353b7 | <add><path>spring-web/src/main/java/org/springframework/web/bind/annotation/ControllerMappingReflectiveProcessor.java
<del><path>spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMappingReflectiveProcessor.java
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> import org.springframework.http.HttpEntity;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.stereotype.Controller;
<ide>
<ide> /**
<del> * {@link ReflectiveProcessor} implementation for {@link RequestMapping}
<del> * annotated types. On top of registering reflection hints for invoking
<del> * the annotated method, this implementation handles:
<add> * {@link ReflectiveProcessor} implementation for {@link Controller} and
<add> * controller-specific annotated methods. On top of registering reflection
<add> * hints for invoking the annotated method, this implementation handles:
<ide> * <ul>
<ide> * <li>Return types annotated with {@link ResponseBody}.</li>
<ide> * <li>Parameters annotated with {@link RequestBody}.</li>
<ide> * @author Sebastien Deleuze
<ide> * @since 6.0
<ide> */
<del>class RequestMappingReflectiveProcessor implements ReflectiveProcessor {
<add>class ControllerMappingReflectiveProcessor implements ReflectiveProcessor {
<ide>
<ide> private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
<ide>
<ide> else if (element instanceof Method method) {
<ide> }
<ide> }
<ide>
<add> protected final BindingReflectionHintsRegistrar getBindingRegistrar() {
<add> return this.bindingRegistrar;
<add> }
<add>
<ide> protected void registerTypeHints(ReflectionHints hints, Class<?> type) {
<ide> hints.registerType(type);
<ide> }
<ide>
<ide> protected void registerMethodHints(ReflectionHints hints, Method method) {
<ide> hints.registerMethod(method, ExecutableMode.INVOKE);
<del> registerParameterHints(hints, method);
<del> registerReturnValueHints(hints, method);
<add> for (Parameter parameter : method.getParameters()) {
<add> registerParameterTypeHints(hints, MethodParameter.forParameter(parameter));
<add> }
<add> registerReturnTypeHints(hints, MethodParameter.forExecutable(method, -1));
<ide> }
<ide>
<del> protected void registerParameterHints(ReflectionHints hints, Method method) {
<del> hints.registerMethod(method, ExecutableMode.INVOKE);
<del> for (Parameter parameter : method.getParameters()) {
<del> MethodParameter methodParameter = MethodParameter.forParameter(parameter);
<del> if (methodParameter.hasParameterAnnotation(RequestBody.class) ||
<del> methodParameter.hasParameterAnnotation(ModelAttribute.class)) {
<del> this.bindingRegistrar.registerReflectionHints(hints, methodParameter.getGenericParameterType());
<del> }
<del> else if (HttpEntity.class.isAssignableFrom(methodParameter.getParameterType())) {
<del> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(methodParameter));
<del> }
<add> protected void registerParameterTypeHints(ReflectionHints hints, MethodParameter methodParameter) {
<add> if (methodParameter.hasParameterAnnotation(RequestBody.class) ||
<add> methodParameter.hasParameterAnnotation(ModelAttribute.class)) {
<add> this.bindingRegistrar.registerReflectionHints(hints, methodParameter.getGenericParameterType());
<add> }
<add> else if (HttpEntity.class.isAssignableFrom(methodParameter.getParameterType())) {
<add> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(methodParameter));
<ide> }
<ide> }
<ide>
<del> protected void registerReturnValueHints(ReflectionHints hints, Method method) {
<del> MethodParameter returnType = MethodParameter.forExecutable(method, -1);
<del> if (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||
<del> returnType.hasMethodAnnotation(ResponseBody.class)) {
<del> this.bindingRegistrar.registerReflectionHints(hints, returnType.getGenericParameterType());
<add> protected void registerReturnTypeHints(ReflectionHints hints, MethodParameter returnTypeParameter) {
<add> if (AnnotatedElementUtils.hasAnnotation(returnTypeParameter.getContainingClass(), ResponseBody.class) ||
<add> returnTypeParameter.hasMethodAnnotation(ResponseBody.class)) {
<add> this.bindingRegistrar.registerReflectionHints(hints, returnTypeParameter.getGenericParameterType());
<ide> }
<del> else if (HttpEntity.class.isAssignableFrom(returnType.getParameterType())) {
<del> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(returnType));
<add> else if (HttpEntity.class.isAssignableFrom(returnTypeParameter.getParameterType())) {
<add> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(returnTypeParameter));
<ide> }
<ide> }
<ide>
<ide> @Nullable
<del> protected Type getHttpEntityType(MethodParameter parameter) {
<add> private Type getHttpEntityType(MethodParameter parameter) {
<ide> MethodParameter nestedParameter = parameter.nested();
<del> return (nestedParameter.getNestedParameterType() == nestedParameter.getParameterType() ? null : nestedParameter.getNestedParameterType());
<add> return (nestedParameter.getNestedParameterType() == nestedParameter.getParameterType()
<add> ? null : nestedParameter.getNestedParameterType());
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<add>import org.springframework.aot.hint.annotation.Reflective;
<add>
<ide> /**
<ide> * Annotation for handling exceptions in specific handler classes and/or
<ide> * handler methods.
<ide> @Target(ElementType.METHOD)
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<add>@Reflective(ExceptionHandlerReflectiveProcessor.class)
<ide> public @interface ExceptionHandler {
<ide>
<ide> /**
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandlerReflectiveProcessor.java
<add>/*
<add> * Copyright 2002-2022 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> * https://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.web.bind.annotation;
<add>
<add>import org.springframework.aot.hint.ReflectionHints;
<add>import org.springframework.core.MethodParameter;
<add>import org.springframework.http.ProblemDetail;
<add>
<add>/**
<add> * {@link ControllerMappingReflectiveProcessor} specific implementation that
<add> * handles {@link ExceptionHandler @ExceptionHandler}-specific types.
<add> *
<add> * @author Stephane Nicoll
<add> * @since 6.0
<add> */
<add>class ExceptionHandlerReflectiveProcessor extends ControllerMappingReflectiveProcessor{
<add>
<add> @Override
<add> protected void registerReturnTypeHints(ReflectionHints hints, MethodParameter returnTypeParameter) {
<add> Class<?> returnType = returnTypeParameter.getParameterType();
<add> if (ProblemDetail.class.isAssignableFrom(returnType)) {
<add> getBindingRegistrar().registerReflectionHints(hints, returnTypeParameter.getGenericParameterType());
<add> }
<add> super.registerReturnTypeHints(hints, returnTypeParameter);
<add> }
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @Mapping
<del>@Reflective(RequestMappingReflectiveProcessor.class)
<add>@Reflective(ControllerMappingReflectiveProcessor.class)
<ide> public @interface RequestMapping {
<ide>
<ide> /**
<add><path>spring-web/src/test/java/org/springframework/web/bind/annotation/ControllerMappingReflectiveProcessorTests.java
<del><path>spring-web/src/test/java/org/springframework/web/bind/annotation/RequestMappingReflectiveProcessorTests.java
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> /**
<del> * Tests for {@link RequestMappingReflectiveProcessor}.
<add> * Tests for {@link ControllerMappingReflectiveProcessor}.
<ide> *
<ide> * @author Sebastien Deleuze
<ide> */
<del>public class RequestMappingReflectiveProcessorTests {
<add>public class ControllerMappingReflectiveProcessorTests {
<ide>
<del> private final RequestMappingReflectiveProcessor processor = new RequestMappingReflectiveProcessor();
<add> private final ControllerMappingReflectiveProcessor processor = new ControllerMappingReflectiveProcessor();
<ide>
<ide> private final ReflectionHints hints = new ReflectionHints();
<ide> | 5 |
Javascript | Javascript | remove opacity in shapepath | 55b733f634283cf087142279918005722b954b75 | <ide><path>src/extras/core/ShapePath.js
<ide> function ShapePath() {
<ide> this.type = 'ShapePath';
<ide>
<ide> this.color = new Color();
<del> this.opacity = 1.0;
<ide>
<ide> this.subPaths = [];
<ide> this.currentPath = null; | 1 |
Python | Python | fix linter errors | 917cdda0edd1764a6e77f48f424263898ff85bce | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def test_non_c_contiguous(self):
<ide> assert_array_equal(x.view('<i2'), expected)
<ide>
<ide>
<del>## Test various array sizes that hit different code paths in quicksort-avx512
<del>@pytest.mark.parametrize("N", \
<del> [8,16,24,32,48,64,96,128,151,191,256,383,512,1023,2047])
<add># Test various array sizes that hit different code paths in quicksort-avx512
<add>@pytest.mark.parametrize("N", [8, 16, 24, 32, 48, 64, 96, 128, 151, 191,
<add> 256, 383, 512, 1023, 2047])
<ide> def test_sort_float(N):
<del> ## Regular data with nan sprinkled
<add> # Regular data with nan sprinkled
<ide> np.random.seed(42)
<ide> arr = -0.5 + np.random.sample(N).astype('f')
<ide> arr[np.random.choice(arr.shape[0], 3)] = np.nan
<ide> assert_equal(np.sort(arr, kind='quick'), np.sort(arr, kind='heap'))
<ide>
<del> ## (2) with +INF
<add> # (2) with +INF
<ide> infarr = np.inf*np.ones(N, dtype='f')
<ide> infarr[np.random.choice(infarr.shape[0], 5)] = -1.0
<ide> assert_equal(np.sort(infarr, kind='quick'), np.sort(infarr, kind='heap'))
<ide>
<del> ## (3) with -INF
<add> # (3) with -INF
<ide> neginfarr = -np.inf*np.ones(N, dtype='f')
<ide> neginfarr[np.random.choice(neginfarr.shape[0], 5)] = 1.0
<ide> assert_equal(np.sort(neginfarr, kind='quick'),
<ide> np.sort(neginfarr, kind='heap'))
<ide>
<del> ## (4) with +/-INF
<add> # (4) with +/-INF
<ide> infarr = np.inf*np.ones(N, dtype='f')
<ide> infarr[np.random.choice(infarr.shape[0], (int)(N/2))] = -np.inf
<ide> assert_equal(np.sort(infarr, kind='quick'), np.sort(infarr, kind='heap'))
<ide>
<add>
<ide> def test_sort_int():
<del> ## Random data with NPY_MAX_INT32 and NPY_MIN_INT32 sprinkled
<add> # Random data with NPY_MAX_INT32 and NPY_MIN_INT32 sprinkled
<ide> np.random.seed(42)
<ide> N = 2047
<ide> minv = np.iinfo(np.int32).min
<ide> def test_sort_int():
<ide> arr[np.random.choice(arr.shape[0], 10)] = maxv
<ide> assert_equal(np.sort(arr, kind='quick'), np.sort(arr, kind='heap'))
<ide>
<add>
<ide> def test_sort_uint():
<del> ## Random data with NPY_MAX_UINT32 sprinkled
<add> # Random data with NPY_MAX_UINT32 sprinkled
<ide> np.random.seed(42)
<ide> N = 2047
<ide> maxv = np.iinfo(np.uint32).max | 1 |
Ruby | Ruby | remove unnecessary line break and quotes | 06332d58676f58ef7970d3a8e0affe38f13feba3 | <ide><path>railties/lib/rails/generators.rb
<ide> def invoke(namespace, args = ARGV, config = {})
<ide> options = sorted_groups.flat_map(&:last)
<ide> suggestion = Rails::Command::Spellchecker.suggest(namespace.to_s, from: options)
<ide> puts <<~MSG
<del> Could not find generator '#{namespace}'. Maybe you meant #{suggestion.inspect}?\n"
<del> Run `rails generate --help` for more options."
<add> Could not find generator '#{namespace}'. Maybe you meant #{suggestion.inspect}?
<add> Run `rails generate --help` for more options.
<ide> MSG
<ide> end
<ide> end | 1 |
Mixed | Python | add spacy as a matcher attribute | 03ae77e6035cb6f7e328221b0974a462db1a2734 | <ide><path>spacy/matcher/_schemas.py
<ide> "title": "Token is the first in a sentence",
<ide> "$ref": "#/definitions/boolean_value",
<ide> },
<add> "SPACY": {
<add> "title": "Token has a trailing space",
<add> "$ref": "#/definitions/boolean_value",
<add> },
<ide> "LIKE_NUM": {
<ide> "title": "Token resembles a number",
<ide> "$ref": "#/definitions/boolean_value",
<ide><path>spacy/tests/matcher/test_matcher_api.py
<ide> def test_attr_pipeline_checks(en_vocab):
<ide> ([{"IS_LEFT_PUNCT": True}], "``"),
<ide> ([{"IS_RIGHT_PUNCT": True}], "''"),
<ide> ([{"IS_STOP": True}], "the"),
<add> ([{"SPACY": True}], "the"),
<ide> ([{"LIKE_NUM": True}], "1"),
<ide> ([{"LIKE_URL": True}], "http://example.com"),
<ide> ([{"LIKE_EMAIL": True}], "mail@example.com"),
<ide><path>website/docs/usage/rule-based-matching.md
<ide> The available token pattern keys correspond to a number of
<ide> [`Token` attributes](/api/token#attributes). The supported attributes for
<ide> rule-based matching are:
<ide>
<del>| Attribute | Value Type | Description |
<del>| -------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------ |
<del>| `ORTH` | unicode | The exact verbatim text of a token. |
<del>| `TEXT` <Tag variant="new">2.1</Tag> | unicode | The exact verbatim text of a token. |
<del>| `LOWER` | unicode | The lowercase form of the token text. |
<del>| `LENGTH` | int | The length of the token text. |
<del>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | bool | Token text consists of alphabetic characters, ASCII characters, digits. |
<del>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | bool | Token text is in lowercase, uppercase, titlecase. |
<del>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | bool | Token is punctuation, whitespace, stop word. |
<del>| `IS_SENT_START` | bool | Token is start of sentence. |
<del>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | bool | Token text resembles a number, URL, email. |
<del>| `POS`, `TAG`, `DEP`, `LEMMA`, `SHAPE` | unicode | The token's simple and extended part-of-speech tag, dependency label, lemma, shape. Note that the values of these attributes are case-sensitive. For a list of available part-of-speech tags and dependency labels, see the [Annotation Specifications](/api/annotation).|
<del>| `ENT_TYPE` | unicode | The token's entity label. |
<del>| `_` <Tag variant="new">2.1</Tag> | dict | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). |
<add>| Attribute | Value Type | Description |
<add>| ------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `ORTH` | unicode | The exact verbatim text of a token. |
<add>| `TEXT` <Tag variant="new">2.1</Tag> | unicode | The exact verbatim text of a token. |
<add>| `LOWER` | unicode | The lowercase form of the token text. |
<add>| `LENGTH` | int | The length of the token text. |
<add>| `IS_ALPHA`, `IS_ASCII`, `IS_DIGIT` | bool | Token text consists of alphabetic characters, ASCII characters, digits. |
<add>| `IS_LOWER`, `IS_UPPER`, `IS_TITLE` | bool | Token text is in lowercase, uppercase, titlecase. |
<add>| `IS_PUNCT`, `IS_SPACE`, `IS_STOP` | bool | Token is punctuation, whitespace, stop word. |
<add>| `IS_SENT_START` | bool | Token is start of sentence. |
<add>| `SPACY` | bool | Token has a trailing space. |
<add>| `LIKE_NUM`, `LIKE_URL`, `LIKE_EMAIL` | bool | Token text resembles a number, URL, email. |
<add>| `POS`, `TAG`, `DEP`, `LEMMA`, `SHAPE` | unicode | The token's simple and extended part-of-speech tag, dependency label, lemma, shape. Note that the values of these attributes are case-sensitive. For a list of available part-of-speech tags and dependency labels, see the [Annotation Specifications](/api/annotation). |
<add>| `ENT_TYPE` | unicode | The token's entity label. |
<add>| `_` <Tag variant="new">2.1</Tag> | dict | Properties in [custom extension attributes](/usage/processing-pipelines#custom-components-attributes). |
<ide>
<ide> <Accordion title="Does it matter if the attribute names are uppercase or lowercase?">
<ide>
<ide> powerful model packages with binary weights _and_ rules included!
<ide>
<ide> ### Using a large number of phrase patterns {#entityruler-large-phrase-patterns new="2.2.4"}
<ide>
<del>When using a large amount of **phrase patterns** (roughly > 10000) it's useful to understand how the `add_patterns` function of the EntityRuler works. For each **phrase pattern**,
<del>the EntityRuler calls the nlp object to construct a doc object. This happens in case you try
<del>to add the EntityRuler at the end of an existing pipeline with, for example, a POS tagger and want to
<del>extract matches based on the pattern's POS signature.
<add>When using a large amount of **phrase patterns** (roughly > 10000) it's useful
<add>to understand how the `add_patterns` function of the EntityRuler works. For each
<add>**phrase pattern**, the EntityRuler calls the nlp object to construct a doc
<add>object. This happens in case you try to add the EntityRuler at the end of an
<add>existing pipeline with, for example, a POS tagger and want to extract matches
<add>based on the pattern's POS signature.
<ide>
<del>In this case you would pass a config value of `phrase_matcher_attr="POS"` for the EntityRuler.
<add>In this case you would pass a config value of `phrase_matcher_attr="POS"` for
<add>the EntityRuler.
<ide>
<del>Running the full language pipeline across every pattern in a large list scales linearly and can therefore take a long time on large amounts of phrase patterns.
<add>Running the full language pipeline across every pattern in a large list scales
<add>linearly and can therefore take a long time on large amounts of phrase patterns.
<ide>
<del>As of spaCy 2.2.4 the `add_patterns` function has been refactored to use nlp.pipe on all phrase patterns resulting in about a 10x-20x speed up with 5,000-100,000 phrase patterns respectively.
<add>As of spaCy 2.2.4 the `add_patterns` function has been refactored to use
<add>nlp.pipe on all phrase patterns resulting in about a 10x-20x speed up with
<add>5,000-100,000 phrase patterns respectively.
<ide>
<del>Even with this speedup (but especially if you're using an older version) the `add_patterns` function can still take a long time.
<add>Even with this speedup (but especially if you're using an older version) the
<add>`add_patterns` function can still take a long time.
<ide>
<del>An easy workaround to make this function run faster is disabling the other language pipes
<del>while adding the phrase patterns.
<add>An easy workaround to make this function run faster is disabling the other
<add>language pipes while adding the phrase patterns.
<ide>
<ide> ```python
<ide> entityruler = EntityRuler(nlp) | 3 |
Python | Python | add sanity-checks to be run at import time | 553c865599116aa20079aaf10142ff60ab8b0ae0 | <ide><path>numpy/__init__.py
<ide> def pkgload(*packages, **options):
<ide> from numpy.testing._private.pytesttester import PytestTester
<ide> test = PytestTester(__name__)
<ide> del PytestTester
<add>
<add>
<add> def _sanity_check():
<add> """
<add> Quick sanity checks for common bugs caused by environment.
<add> There are some cases e.g. with wrong BLAS ABI that cause wrong
<add> results under specific runtime conditions that are not necessarily
<add> achieved during test suite runs, and it is useful to catch those early.
<add>
<add> See https://github.com/numpy/numpy/issues/8577 and other
<add> similar bug reports.
<add>
<add> """
<add> try:
<add> x = ones(2, dtype=float32)
<add> if not abs(x.dot(x) - 2.0) < 1e-5:
<add> raise AssertionError()
<add> except AssertionError:
<add> msg = ("The current Numpy installation ({!r}) fails to "
<add> "pass simple sanity checks. This can be caused for example "
<add> "by incorrect BLAS library being linked in.")
<add> raise RuntimeError(msg.format(__file__))
<add>
<add> _sanity_check()
<add> del _sanity_check | 1 |
Ruby | Ruby | drop homebrew cask tap names from list | a4590f394e71384bb7acd780bc51ff184d8f2e1e | <ide><path>Library/Homebrew/extend/os/mac/search.rb
<ide> def search_casks(string_or_regex)
<ide> end
<ide> end
<ide>
<del> cask_tokens = Tap.flat_map(&:cask_tokens)
<add> cask_tokens = Tap.flat_map(&:cask_tokens).map do |c|
<add> c.sub(%r{^homebrew/cask.*/}, "")
<add> end
<ide>
<ide> results = cask_tokens.extend(Searchable)
<ide> .search(string_or_regex) | 1 |
Text | Text | remove lineheight example from docs | e17387e7f0f6f6279286fefda72ea1b90409a23c | <ide><path>docs/configuring-and-extending.md
<ide> Or you can use `observeConfig` to track changes from a view object.
<ide> ```coffeescript
<ide> class MyView extends View
<ide> initialize: ->
<del> @observeConfig 'editor.lineHeight', (lineHeight) =>
<del> @adjustLineHeight(lineHeight)
<add> @observeConfig 'editor.fontSize', () =>
<add> @adjustFontSize()
<ide> ```
<ide>
<ide> The `observeConfig` method will call the given callback immediately with the | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.