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 |
|---|---|---|---|---|---|
Text | Text | upgrade stability status of report api | 7798e59e988a66e731cc233f4a2fbee01269736d | <ide><path>doc/api/process.md
<ide> Additional documentation is available in the [report documentation][].
<ide> ### `process.report.reportOnFatalError`
<ide> <!-- YAML
<ide> added: v11.12.0
<add>changes:
<add> - version:
<add> - REPLACEME
<add> description: This API is no longer experimental.
<ide> -->
<ide>
<del>> Stability: 1 - Experimental
<del>
<ide> * {boolean}
<ide>
<ide> If `true`, a diagnostic report is generated on fatal errors, such as out of | 1 |
Javascript | Javascript | fix couple of typos in the docs | 1f4b417184ce53af15474de065400f8a686430c5 | <ide><path>src/Angular.js
<ide> var _undefined = undefined,
<ide> * @param {Object|Array} obj Object to iterate over.
<ide> * @param {function()} iterator Iterator function.
<ide> * @param {Object} context Object to become context (`this`) for the iterator function.
<del> * @returns {Objet|Array} Reference to `obj`.
<add> * @returns {Object|Array} Reference to `obj`.
<ide> */
<ide> function forEach(obj, iterator, context) {
<ide> var key;
<ide> function toKeyValue(obj) {
<ide>
<ide>
<ide> /**
<del> * we need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
<add> * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
<ide> * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
<ide> * segments:
<ide> * segment = *pchar
<ide><path>src/Browser.js
<ide> function Browser(window, document, body, XHR, $log) {
<ide> * The listener gets called with either HashChangeEvent object or simple object that also contains
<ide> * `oldURL` and `newURL` properties.
<ide> *
<del> * NOTE: this api is intended for use only by the $location service. Please use the
<add> * Note: this api is intended for use only by the $location service. Please use the
<ide> * {@link angular.service.$location $location service} to monitor hash changes in angular apps.
<ide> *
<ide> * @param {function(event)} listener Listener function to be called when url hash changes.
<ide><path>src/Compiler.js
<ide> Template.prototype = {
<ide> * The compilation is a process of walking the DOM tree and trying to match DOM elements to
<ide> * {@link angular.markup markup}, {@link angular.attrMarkup attrMarkup},
<ide> * {@link angular.widget widgets}, and {@link angular.directive directives}. For each match it
<del> * executes coresponding markup, attrMarkup, widget or directive template function and collects the
<add> * executes corresponding markup, attrMarkup, widget or directive template function and collects the
<ide> * instance functions into a single template function which is then returned.
<ide> *
<ide> * The template function can then be used once to produce the view or as it is the case with
<ide> Template.prototype = {
<ide> * root scope is created.
<ide> * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
<ide> * `template` and call the `cloneAttachFn` function allowing the caller to attach the
<del> * cloned elements to the DOM document at the approriate place. The `cloneAttachFn` is
<add> * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
<ide> * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
<ide> *
<ide> * * `clonedElement` - is a clone of the original `element` passed into the compiler.
<ide> Compiler.prototype = {
<ide> * not a problem, but under some circumstances the values for data
<ide> * is not available until after the full view is computed. If such
<ide> * values are needed before they are computed the order of
<del> * evaluation can be change using ng:eval-order
<add> * evaluation can be changed using ng:eval-order
<ide> *
<ide> * @element ANY
<ide> * @param {integer|string=} [priority=0] priority integer, or FIRST, LAST constant
<ide><path>src/Scope.js
<ide> function getter(instance, path, unboundFn) {
<ide> for ( var i = 0; i < len; i++) {
<ide> key = element[i];
<ide> if (!key.match(/^[\$\w][\$\w\d]*$/))
<del> throw "Expression '" + path + "' is not a valid expression for accesing variables.";
<add> throw "Expression '" + path + "' is not a valid expression for accessing variables.";
<ide> if (instance) {
<ide> lastInstance = instance;
<ide> instance = instance[key];
<ide> function createScope(parent, providers, instanceCache) {
<ide> * @description
<ide> * Assigns a value to a property of the current scope specified via `property_chain`. Unlike in
<ide> * JavaScript, if there are any `undefined` intermediary properties, empty objects are created
<del> * and assigned in to them instead of throwing an exception.
<add> * and assigned to them instead of throwing an exception.
<ide> *
<ide> <pre>
<ide> var scope = angular.scope();
<ide> function createScope(parent, providers, instanceCache) {
<ide> * parameters, `newValue` and `oldValue`.
<ide> * @param {(function()|DOMElement)=} [exceptionHanlder=angular.service.$exceptionHandler] Handler
<ide> * that gets called when `watchExp` or `listener` throws an exception. If a DOMElement is
<del> * specified as handler, the element gets decorated by angular with the information about the
<add> * specified as a handler, the element gets decorated by angular with the information about the
<ide> * exception.
<ide> * @param {boolean=} [initRun=true] Flag that prevents the first execution of the listener upon
<ide> * registration.
<ide><path>src/directives.js
<ide> angularDirective("ng:bind", function(expression, element){
<ide> error = formatError(e);
<ide> });
<ide> this.$element = oldElement;
<del> // If we are HTML than save the raw HTML data so that we don't
<add> // If we are HTML then save the raw HTML data so that we don't
<ide> // recompute sanitization since it is expensive.
<ide> // TODO: turn this into a more generic way to compute this
<ide> if (isHtml = (value instanceof HTML))
<ide><path>src/filters.js
<ide> *
<ide> * @param {number} amount Input to filter.
<ide> * @param {string=} symbol Currency symbol or identifier to be displayed.
<del> * @returns {string} Formated number.
<add> * @returns {string} Formatted number.
<ide> *
<ide> * @css ng-format-negative
<del> * When the value is negative, this css class is applied to the binding making it by default red.
<add> * When the value is negative, this css class is applied to the binding making it (by default) red.
<ide> *
<ide> * @example
<ide> <doc:example>
<ide> angularFilter.currency = function(amount, currencySymbol){
<ide> * @description
<ide> * Formats a number as text.
<ide> *
<del> * If the input is not a number empty string is returned.
<add> * If the input is not a number an empty string is returned.
<ide> *
<ide> * @param {number|string} number Number to format.
<ide> * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
<ide> angularFilter.uppercase = uppercase;
<ide> *
<ide> * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are
<ide> * then serialized back to properly escaped html string. This means that no unsafe input can make
<del> * it into the returned string, however since our parser is more strict than a typical browser
<add> * it into the returned string, however, since our parser is more strict than a typical browser
<ide> * parser, it's possible that some obscure input, which would be recognized as valid HTML by a
<ide> * browser, won't make it through the sanitizer.
<ide> *
<ide> angularFilter.html = function(html, option){
<ide> *
<ide> * @description
<ide> * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
<del> * plane email address links.
<add> * plain email address links.
<ide> *
<ide> * @param {string} text Input text.
<ide> * @returns {string} Html-linkified text.
<ide><path>src/formatters.js
<ide> * @name angular.formatter
<ide> * @description
<ide> *
<del> * Formatters are used for translating data formats between those used in for display and those used
<add> * Formatters are used for translating data formats between those used for display and those used
<ide> * for storage.
<ide> *
<ide> * Following is the list of built-in angular formatters:
<ide><path>src/jqLite.js
<ide> * focus on the most commonly needed functionality and minimal footprint. For this reason only a
<ide> * limited number of jQuery methods, arguments and invocation styles are supported.
<ide> *
<del> * NOTE: All element references in angular are always wrapped with jQuery (lite) and are never
<add> * Note: All element references in angular are always wrapped with jQuery (lite) and are never
<ide> * raw DOM references.
<ide> *
<ide> * ## Angular's jQuery lite implements these functions:
<ide> function JQLiteData(element, key, value) {
<ide>
<ide> function JQLiteHasClass(element, selector, _) {
<ide> // the argument '_' is important, since it makes the function have 3 arguments, which
<del> // is neede for delegate function to realize the this is a getter.
<add> // is needed for delegate function to realize the this is a getter.
<ide> var className = " " + selector + " ";
<ide> return ((" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf( className ) > -1);
<ide> }
<ide><path>src/markups.js
<ide> * Markup extensions do not themselves produce linking functions. Think of markup as a way to
<ide> * produce shorthand for a {@link angular.widget widget} or a {@link angular.directive directive}.
<ide> *
<del> * The most prominent example of an markup in angular is the built-in double curly markup
<del> * `{{expression}}`, which is a shorthand for `<span ng:bind="expression"></span>`.
<add> * The most prominent example of a markup in angular is the built-in double curly markup
<add> * `{{expression}}`, which is shorthand for `<span ng:bind="expression"></span>`.
<ide> *
<ide> * Create custom markup like this:
<ide> *
<ide> * @description
<ide> *
<ide> * Attribute markup extends the angular compiler in a very similar way as {@link angular.markup}
<del> * except that it allows you to modify the state of the attribute text rather then the content of a
<add> * except that it allows you to modify the state of the attribute text rather than the content of a
<ide> * node.
<ide> *
<ide> * Create custom attribute markup like this:
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> *
<ide> * @description
<ide> * Using <angular/> markup like {{hash}} in an href attribute makes
<del> * the page open to a wrong URL, ff the user clicks that link before
<add> * the page open to a wrong URL, if the user clicks that link before
<ide> * angular has a chance to replace the {{hash}} with actual URL, the
<ide> * link will be broken and will most likely return a 404 error.
<ide> * The `ng:href` solves this problem by placing the `href` in the
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> * </div>
<ide> * </pre>
<ide> *
<del> * the HTML specs do not require browsers preserve the special attributes such as disabled.(The presense of them means true and absense means false)
<add> * The HTML specs do not require browsers to preserve the special attributes such as disabled.
<add> * (The presence of them means true and absence means false)
<ide> * This prevents the angular compiler from correctly retrieving the binding expression.
<ide> * To solve this problem, we introduce ng:disabled.
<ide> *
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> * @name angular.directive.ng:checked
<ide> *
<ide> * @description
<del> * the HTML specs do not require browsers preserve the special attributes such as checked.(The presense of them means true and absense means false)
<add> * The HTML specs do not require browsers to preserve the special attributes such as checked.
<add> * (The presence of them means true and absence means false)
<ide> * This prevents the angular compiler from correctly retrieving the binding expression.
<ide> * To solve this problem, we introduce ng:checked.
<ide> * @example
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> * @name angular.directive.ng:multiple
<ide> *
<ide> * @description
<del> * the HTML specs do not require browsers preserve the special attributes such as multiple.(The presense of them means true and absense means false)
<add> * The HTML specs do not require browsers to preserve the special attributes such as multiple.
<add> * (The presence of them means true and absence means false)
<ide> * This prevents the angular compiler from correctly retrieving the binding expression.
<ide> * To solve this problem, we introduce ng:multiple.
<ide> *
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> * @name angular.directive.ng:readonly
<ide> *
<ide> * @description
<del> * the HTML specs do not require browsers preserve the special attributes such as readonly.(The presense of them means true and absense means false)
<add> * The HTML specs do not require browsers to preserve the special attributes such as readonly.
<add> * (The presence of them means true and absence means false)
<ide> * This prevents the angular compiler from correctly retrieving the binding expression.
<ide> * To solve this problem, we introduce ng:readonly.
<ide> * @example
<ide> angularTextMarkup('option', function(text, textNode, parentElement){
<ide> * @name angular.directive.ng:selected
<ide> *
<ide> * @description
<del>* the HTML specs do not require browsers preserve the special attributes such as selected.(The presense of them means true and absense means false)
<add>* The HTML specs do not require browsers to preserve the special attributes such as selected.
<add>* (The presence of them means true and absence means false)
<ide> * This prevents the angular compiler from correctly retrieving the binding expression.
<ide> * To solve this problem, we introduce ng:selected.
<ide> * @example
<ide><path>src/service/updateView.js
<ide> * or 'XHR' (instead of {@link angular.service.$xhr}) then you may be changing the model
<ide> * without angular knowledge and you may need to call '$updateView()' directly.
<ide> *
<del> * NOTE: if you wish to update the view immediately (without delay), you can do so by calling
<add> * Note: if you wish to update the view immediately (without delay), you can do so by calling
<ide> * {@link angular.scope.$eval} at any time from your code:
<ide> * <pre>scope.$root.$eval()</pre>
<ide> *
<ide><path>src/service/xhr.js
<ide> * @name angular.service.$xhr
<ide> * @function
<ide> * @requires $browser $xhr delegates all XHR requests to the `$browser.xhr()`. A mock version
<del> * of the $browser exists which allows setting expectaitions on XHR requests
<add> * of the $browser exists which allows setting expectations on XHR requests
<ide> * in your tests
<ide> * @requires $xhr.error $xhr delegates all non `2xx` response code to this service.
<ide> * @requires $log $xhr delegates all exceptions to `$log.error()`.
<ide> * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the server
<ide> * can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure that only
<ide> * JavaScript running on your domain could have read the token. The token must be unique for each
<del> * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens).
<add> * user and must be verifiable by the server (to prevent the JavaScript making up its own tokens).
<ide> * We recommend that the token is a digest of your site's authentication cookie with
<ide> * {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
<ide> *
<ide><path>src/validators.js
<ide> extend(angularValidator, {
<ide> if (value.match(/^\+\d{2,3} (\(\d{1,5}\))?[\d ]+\d$/)) {
<ide> return null;
<ide> }
<del> return "Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly.";
<add> return "Phone number needs to be in 1(987)654-3210 format in North America " +
<add> "or +999 (123) 45678 906 internationally.";
<ide> },
<ide>
<ide> /**
<ide><path>src/widgets.js
<ide> * @name angular.widget
<ide> * @description
<ide> *
<del> * An angular widget can be either a custom attribute that modifies an existing DOM elements or an
<add> * An angular widget can be either a custom attribute that modifies an existing DOM element or an
<ide> * entirely new DOM element.
<ide> *
<ide> * During html compilation, widgets are processed after {@link angular.markup markup}, but before
<ide> * @description
<ide> * The most common widgets you will use will be in the form of the
<ide> * standard HTML set. These widgets are bound using the `name` attribute
<del> * to an expression. In addition they can have `ng:validate`, `ng:required`,
<add> * to an expression. In addition, they can have `ng:validate`, `ng:required`,
<ide> * `ng:format`, `ng:change` attribute to further control their behavior.
<ide> *
<ide> * @usageContent
<ide> function compileFormatter(expr) {
<ide> *
<ide> * @description
<ide> * The `ng:format` attribute widget formats stored data to user-readable text and parses the text
<del> * back to the stored form. You might find this useful for example if you collect user input in a
<add> * back to the stored form. You might find this useful, for example, if you collect user input in a
<ide> * text field but need to store the data in the model as a list. Check out
<ide> * {@link angular.formatter formatters} to learn more.
<ide> *
<ide> function noopAccessor() { return { get: noop, set: noop }; }
<ide> /*
<ide> * TODO: refactor
<ide> *
<del> * The table bellow is not quite right. In some cases the formatter is on the model side
<add> * The table below is not quite right. In some cases the formatter is on the model side
<ide> * and in some cases it is on the view side. This is a historical artifact
<ide> *
<ide> * The concept of model/view accessor is useful for anyone who is trying to develop UI, and
<ide> angularWidget('@ng:repeat', function(expression, element){
<ide> * Sometimes it is necessary to write code which looks like bindings but which should be left alone
<ide> * by angular. Use `ng:non-bindable` to make angular ignore a chunk of HTML.
<ide> *
<del> * NOTE: `ng:non-bindable` looks like a directive, but is actually an attribute widget.
<add> * Note: `ng:non-bindable` looks like a directive, but is actually an attribute widget.
<ide> *
<ide> * @element ANY
<ide> *
<ide> * @example
<del> * In this example there are two location where a siple binding (`{{}}`) is present, but the one
<add> * In this example there are two location where a simple binding (`{{}}`) is present, but the one
<ide> * wrapped in `ng:non-bindable` is left alone.
<ide> *
<ide> * @example
<ide><path>test/ValidatorsSpec.js
<ide> describe('ValidatorTest', function(){
<ide> });
<ide>
<ide> it('Phone', function() {
<del> var error = "Phone number needs to be in 1(987)654-3210 format in North America or +999 (123) 45678 906 internationaly.";
<add> var error = "Phone number needs to be in 1(987)654-3210 format in North America " +
<add> "or +999 (123) 45678 906 internationally.";
<ide> assertEquals(angular.validator.phone("ab"), error);
<ide> assertEquals(null, angular.validator.phone("1(408)757-3023"));
<ide> assertEquals(null, angular.validator.phone("+421 (0905) 933 297")); | 14 |
Python | Python | add some doc to the paver script | 6b942481c52f6d2e88774fe4c18c3aed64cd7ee5 | <ide><path>pavement.py
<add>"""
<add>Building a fancy dmg from scratch
<add>=================================
<add>
<add>Clone the numpy-macosx-installer git repo from on github into the source tree
<add>(numpy-macosx-installer should be in the same directory as setup.py). Then, do
<add>as follows::
<add>
<add> paver clean clean_bootstrap
<add> paver bootstrap && source boostrap/bin/activate
<add> python setupegg.py install
<add> paver dmg
<add>
<add>Building a simple (no-superpack) windows installer from wine
<add>============================================================
<add>
<add>It assumes that blas/lapack are in c:\local\lib inside drive_c. Build python
<add>2.5 and python 2.6 installers.
<add>
<add> paver clean
<add> paver bdist_wininst
<add>
<add>Building changelog + notes
<add>==========================
<add>
<add>Assumes you have git and the binaries/tarballs in installers/::
<add>
<add> paver write_release
<add> paver write_note
<add>
<add>This automatically put the checksum into NOTES.txt, and write the Changelog
<add>which can be uploaded to sourceforge.
<add>"""
<ide> import os
<ide> import sys
<ide> import subprocess | 1 |
Javascript | Javascript | remove internal usage of `ember.__loader` | 89f0516c78af31fbd2ef3c9e7a6b84b497be6105 | <ide><path>packages/ember-metal/lib/core.js
<ide> /*globals Ember:true,ENV,EmberENV */
<ide>
<add>import require from 'require';
<add>
<ide> /**
<ide> @module ember
<ide> @submodule ember-metal
<ide> Ember.toString = function() { return 'Ember'; };
<ide>
<ide> // The debug functions are exported to globals with `require` to
<ide> // prevent babel-plugin-filter-imports from removing them.
<del>let debugModule = Ember.__loader.require('ember-metal/debug');
<add>let debugModule = require('ember-metal/debug');
<ide> Ember.assert = debugModule.assert;
<ide> Ember.warn = debugModule.warn;
<ide> Ember.debug = debugModule.debug;
<ide><path>packages/ember-metal/lib/index.js
<ide> */
<ide>
<ide> // BEGIN IMPORTS
<add>import require, { has } from 'require';
<ide> import Ember from 'ember-metal/core';
<ide> import { deprecateFunc } from 'ember-metal/debug';
<ide> import isEnabled, { FEATURES } from 'ember-metal/features';
<ide> Ember.onerror = null;
<ide> // do this for side-effects of updating Ember.assert, warn, etc when
<ide> // ember-debug is present
<ide> // This needs to be called before any deprecateFunc
<del>if (Ember.__loader.registry['ember-debug/index']) {
<del> requireModule('ember-debug');
<add>if (has('ember-debug')) {
<add> require('ember-debug');
<ide> } else {
<ide> Ember.Debug = { };
<ide>
<ide><path>packages/ember-runtime/lib/ext/rsvp.js
<ide> /* globals RSVP:true */
<ide>
<ide> import Ember from 'ember-metal/core';
<add>import require, { has } from 'require';
<ide> import { assert } from 'ember-metal/debug';
<ide> import Logger from 'ember-metal/logger';
<ide> import run from 'ember-metal/run_loop';
<ide> export function onerrorDefault(reason) {
<ide> if (error && error.name !== 'TransitionAborted') {
<ide> if (Ember.testing) {
<ide> // ES6TODO: remove when possible
<del> if (!Test && Ember.__loader.registry[testModuleName]) {
<del> Test = requireModule(testModuleName)['default'];
<add> if (!Test && has(testModuleName)) {
<add> Test = require(testModuleName)['default'];
<ide> }
<ide>
<ide> if (Test && Test.adapter) {
<ide><path>packages/ember-template-compiler/lib/compat/precompile.js
<ide> @module ember
<ide> @submodule ember-template-compiler
<ide> */
<del>import Ember from 'ember-metal/core';
<add>import require, { has } from 'require';
<ide> import compileOptions from 'ember-template-compiler/system/compile_options';
<ide>
<ide> var compile, compileSpec;
<ide>
<ide> export default function(string) {
<del> if ((!compile || !compileSpec) && Ember.__loader.registry['htmlbars-compiler/compiler']) {
<del> var Compiler = requireModule('htmlbars-compiler/compiler');
<add> if ((!compile || !compileSpec) && has('htmlbars-compiler/compiler')) {
<add> var Compiler = require('htmlbars-compiler/compiler');
<ide>
<ide> compile = Compiler.compile;
<ide> compileSpec = Compiler.compileSpec;
<ide><path>packages/ember-template-compiler/lib/system/compile.js
<ide> @submodule ember-template-compiler
<ide> */
<ide>
<del>import Ember from 'ember-metal/core';
<add>import require, { has } from 'require';
<ide> import compileOptions from 'ember-template-compiler/system/compile_options';
<ide> import template from 'ember-template-compiler/system/template';
<ide>
<ide> var compile;
<ide> @param {Object} options This is an options hash to augment the compiler options.
<ide> */
<ide> export default function(templateString, options) {
<del> if (!compile && Ember.__loader.registry['htmlbars-compiler/compiler']) {
<del> compile = requireModule('htmlbars-compiler/compiler').compile;
<add> if (!compile && has('htmlbars-compiler/compiler')) {
<add> compile = require('htmlbars-compiler/compiler').compile;
<ide> }
<ide>
<ide> if (!compile) {
<ide><path>packages/ember-template-compiler/lib/system/precompile.js
<ide> @module ember
<ide> @submodule ember-template-compiler
<ide> */
<del>import Ember from 'ember-metal/core';
<add>import require, { has } from 'require';
<ide> import compileOptions from 'ember-template-compiler/system/compile_options';
<ide>
<ide> var compileSpec;
<ide> var compileSpec;
<ide> @param {String} templateString This is the string to be compiled by HTMLBars.
<ide> */
<ide> export default function(templateString, options) {
<del> if (!compileSpec && Ember.__loader.registry['htmlbars-compiler/compiler']) {
<del> compileSpec = requireModule('htmlbars-compiler/compiler').compileSpec;
<add> if (!compileSpec && has('htmlbars-compiler/compiler')) {
<add> compileSpec = require('htmlbars-compiler/compiler').compileSpec;
<ide> }
<ide>
<ide> if (!compileSpec) {
<ide><path>packages/ember/lib/index.js
<ide> import 'ember-htmlbars';
<ide> import 'ember-routing-htmlbars';
<ide> import 'ember-routing-views';
<ide>
<del>import Ember from 'ember-metal/core';
<add>import require, { has } from 'require';
<ide> import { runLoadHooks } from 'ember-runtime/system/lazy_load';
<ide>
<del>if (Ember.__loader.registry['ember-template-compiler/index']) {
<del> requireModule('ember-template-compiler');
<add>if (has('ember-template-compiler')) {
<add> require('ember-template-compiler');
<ide> }
<ide>
<ide> // do this to ensure that Ember.Test is defined properly on the global
<ide> // if it is present.
<del>if (Ember.__loader.registry['ember-testing/index']) {
<del> requireModule('ember-testing');
<add>if (has('ember-testing')) {
<add> require('ember-testing');
<ide> }
<ide>
<ide> runLoadHooks('Ember');
<ide><path>packages/loader/lib/index.js
<ide> var mainContext = this;
<ide> requirejs = require = requireModule = function(name) {
<ide> return internalRequire(name, null);
<ide> }
<add>
<add> // setup `require` module
<ide> require['default'] = require;
<ide>
<add> require.has = function registryHas(moduleName) {
<add> return !!registry[moduleName] || !!registry[moduleName + '/index'];
<add> };
<add>
<ide> function missingModule(name, referrerName) {
<ide> if (referrerName) {
<ide> throw new Error('Could not find module ' + name + ' required by: ' + referrerName); | 8 |
Ruby | Ruby | fix dependency order | dc90709eaf1242f565de3a9282d7939f6bc853cf | <ide><path>tasks/release.rb
<del>FRAMEWORKS = %w( activesupport activemodel activerecord actionpack actionview actionmailer railties )
<add>FRAMEWORKS = %w( activesupport activemodel activerecord actionview actionpack actionmailer railties )
<ide>
<ide> root = File.expand_path('../../', __FILE__)
<ide> version = File.read("#{root}/RAILS_VERSION").strip | 1 |
Go | Go | remove some todos | f50b916ca6cce410f3b1bbd5250fb9ba2a7942a6 | <ide><path>daemon/container_windows.go
<ide> func (container *Container) CleanupStorage() error {
<ide> return nil
<ide> }
<ide>
<del>// TODO Windows. This can be further factored out. Used in daemon.go
<add>// prepareMountPoints is a no-op on Windows
<ide> func (container *Container) prepareMountPoints() error {
<ide> return nil
<ide> }
<ide>
<del>// TODO Windows. This can be further factored out. Used in delete.go
<add>// removeMountPoints is a no-op on Windows.
<ide> func (container *Container) removeMountPoints() error {
<ide> return nil
<ide> } | 1 |
Ruby | Ruby | add test for locale.detect | 1d3e8c5550a0c32a227f0cf3db97c2c0410fb886 | <ide><path>Library/Homebrew/test/locale_spec.rb
<ide> expect(subject.eql?("zh_CN_Hans")).to be false
<ide> end
<ide> end
<add>
<add> describe "#detect" do
<add> let(:locale_groups) { [["zh"], ["zh-TW"]] }
<add>
<add> it "finds best matching language code, independent of order" do
<add> expect(described_class.new("zh", "TW", nil).detect(locale_groups)).to eql(["zh-TW"])
<add> expect(described_class.new("zh", "TW", nil).detect(locale_groups.reverse)).to eql(["zh-TW"])
<add> expect(described_class.new("zh", "CN", "Hans").detect(locale_groups)).to eql(["zh"])
<add> end
<add> end
<ide> end | 1 |
Ruby | Ruby | use deep_symbolize_keys instead of symbolize_names | be2fd611375026ef902c73fb35526a08e10999c6 | <ide><path>railties/lib/rails/application.rb
<ide> def config_for(name, env: Rails.env)
<ide>
<ide> if yaml.exist?
<ide> require "erb"
<del> all_configs = ActiveSupport::ConfigurationFile.parse(yaml, symbolize_names: true)
<add> all_configs = ActiveSupport::ConfigurationFile.parse(yaml).deep_symbolize_keys
<ide> config, shared = all_configs[env.to_sym], all_configs[:shared]
<ide>
<ide> if config.is_a?(Hash)
<ide><path>railties/test/application/configuration_test.rb
<ide> class D < C
<ide> assert_equal "unicorn", Rails.application.config.my_custom_config[:key]
<ide> end
<ide>
<add> test "config_for handles YAML patches (like safe_yaml) that disable the symbolize_names option" do
<add> app_file "config/custom.yml", <<~RUBY
<add> development:
<add> key: value
<add> RUBY
<add>
<add> app "development"
<add>
<add> YAML.stub :load, { "development" => { "key" => "value" } } do
<add> assert_equal({ key: "value" }, Rails.application.config_for(:custom))
<add> end
<add> end
<add>
<ide> test "api_only is false by default" do
<ide> app "development"
<ide> assert_not Rails.application.config.api_only | 2 |
PHP | PHP | add the ability to skip algorithm checking | 7aeff1d4393afba36c52e301726d848e2a373b12 | <ide><path>src/Illuminate/Hashing/Argon2IdHasher.php
<ide> class Argon2IdHasher extends ArgonHasher
<ide> */
<ide> public function check($value, $hashedValue, array $options = [])
<ide> {
<del> if ($this->info($hashedValue)['algoName'] !== 'argon2id') {
<add> if ($this->verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'argon2id') {
<ide> throw new RuntimeException('This password does not use the Argon2id algorithm.');
<ide> }
<ide>
<ide><path>src/Illuminate/Hashing/ArgonHasher.php
<ide> class ArgonHasher extends AbstractHasher implements HasherContract
<ide> */
<ide> protected $threads = 2;
<ide>
<add> /**
<add> * Indicates whether to perform an algorithm check.
<add> *
<add> * @var bool
<add> */
<add> protected $verifyAlgorithm = true;
<add>
<ide> /**
<ide> * Create a new hasher instance.
<ide> *
<ide> public function __construct(array $options = [])
<ide> $this->time = $options['time'] ?? $this->time;
<ide> $this->memory = $options['memory'] ?? $this->memory;
<ide> $this->threads = $options['threads'] ?? $this->threads;
<add> $this->verifyAlgorithm = $options['verifyAlgorithm'] ?? $this->verifyAlgorithm;
<ide> }
<ide>
<ide> /**
<ide> protected function algorithm()
<ide> */
<ide> public function check($value, $hashedValue, array $options = [])
<ide> {
<del> if ($this->info($hashedValue)['algoName'] !== 'argon2i') {
<add> if ($this->verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'argon2i') {
<ide> throw new RuntimeException('This password does not use the Argon2i algorithm.');
<ide> }
<ide>
<ide><path>src/Illuminate/Hashing/BcryptHasher.php
<ide> class BcryptHasher extends AbstractHasher implements HasherContract
<ide> */
<ide> protected $rounds = 10;
<ide>
<add> /**
<add> * Indicates whether to perform an algorithm check.
<add> *
<add> * @var bool
<add> */
<add> protected $verifyAlgorithm = true;
<add>
<ide> /**
<ide> * Create a new hasher instance.
<ide> *
<ide> class BcryptHasher extends AbstractHasher implements HasherContract
<ide> public function __construct(array $options = [])
<ide> {
<ide> $this->rounds = $options['rounds'] ?? $this->rounds;
<add> $this->verifyAlgorithm = $options['verify_algorithm'] ?? $this->verifyAlgorithm;
<ide> }
<ide>
<ide> /**
<ide> public function make($value, array $options = [])
<ide> */
<ide> public function check($value, $hashedValue, array $options = [])
<ide> {
<del> if ($this->info($hashedValue)['algoName'] !== 'bcrypt') {
<add> if ($this->verifyAlgorithm && $this->info($hashedValue)['algoName'] !== 'bcrypt') {
<ide> throw new RuntimeException('This password does not use the Bcrypt algorithm.');
<ide> }
<ide> | 3 |
Javascript | Javascript | use regluar expression in vm test | e8170f2246717cd8171c450ba11ae04934cf7dd9 | <ide><path>test/parallel/test-vm-create-context-arg.js
<ide> const vm = require('vm');
<ide>
<ide> assert.throws(function() {
<ide> vm.createContext('string is not supported');
<del>}, TypeError);
<add>}, /^TypeError: sandbox must be an object$/);
<ide>
<ide> assert.doesNotThrow(function() {
<ide> vm.createContext({ a: 1 }); | 1 |
Javascript | Javascript | remove experimental warning from formdata | 5ad47a0c2a587616f8d7c25e09f76dab389fdbf0 | <ide><path>lib/internal/bootstrap/pre_execution.js
<ide> function setupFetch() {
<ide> return undici;
<ide> }
<ide>
<del> emitExperimentalWarning('The Fetch API');
<ide> undici = require('internal/deps/undici/undici');
<ide> return undici;
<ide> }
<ide>
<ide> async function fetch(input, init = undefined) {
<add> emitExperimentalWarning('The Fetch API');
<ide> return lazyUndici().fetch(input, init);
<ide> }
<ide> | 1 |
Java | Java | fix typo in javadoc | 1e1ea34e876bf15c804245b712332e53f1962496 | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/ListableBeanFactory.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> * They will ignore any singleton beans that have been registered by other means like
<ide> * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}'s
<ide> * {@code registerSingleton} method, with the exception of
<del> * {@code getBeanNamesOfType} and {@code getBeansOfType} which will check
<add> * {@code getBeanNamesForType} and {@code getBeansOfType} which will check
<ide> * such manually registered singletons too. Of course, BeanFactory's {@code getBean}
<ide> * does allow transparent access to such special beans as well. However, in typical
<ide> * scenarios, all beans will be defined by external bean definitions anyway, so most
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
<ide> "] in its raw version as part of a circular reference, but has eventually been " +
<ide> "wrapped. This means that said other beans do not use the final version of the " +
<ide> "bean. This is often the result of over-eager type matching - consider using " +
<del> "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
<add> "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
<ide> }
<ide> }
<ide> } | 2 |
Ruby | Ruby | add link_path_manpages method | 8cc027a3cd24b95120932c581c8b9eebb8c710f3 | <ide><path>Library/Homebrew/utils.rb
<ide> def truncate_text_to_approximate_size(s, max_bytes, options = {})
<ide> out.encode!("UTF-8")
<ide> out
<ide> end
<add>
<add>def link_path_manpages(path, command)
<add> return unless (path/"man").exist?
<add> conflicts = []
<add> (path/"man").find do |src|
<add> next if src.directory?
<add> dst = HOMEBREW_PREFIX/"share"/src.relative_path_from(path)
<add> next if dst.symlink? && src == dst.resolved_path
<add> if dst.exist?
<add> conflicts << dst
<add> next
<add> end
<add> dst.make_relative_symlink(src)
<add> end
<add> unless conflicts.empty?
<add> onoe <<-EOS.undent
<add> Could not link #{name} manpages to:
<add> #{conflicts.join("\n")}
<add>
<add> Please delete these files and run `#{command}`.
<add> EOS
<add> end
<add>end | 1 |
Go | Go | remove unused win32 errors (leftover from tp4) | 9637be0e9d539b4b379ae3dd31b60f17b6bbf4e5 | <ide><path>libcontainerd/local/local_windows.go
<ide> type container struct {
<ide> terminateInvoked bool
<ide> }
<ide>
<del>// Win32 error codes that are used for various workarounds
<del>// These really should be ALL_CAPS to match golangs syscall library and standard
<del>// Win32 error conventions, but golint insists on CamelCase.
<del>const (
<del> CoEClassstring = syscall.Errno(0x800401F3) // Invalid class string
<del> ErrorNoNetwork = syscall.Errno(1222) // The network is not present or not started
<del> ErrorBadPathname = syscall.Errno(161) // The specified path is invalid
<del> ErrorInvalidObject = syscall.Errno(0x800710D8) // The object identifier does not represent a valid object
<del>)
<del>
<ide> // defaultOwner is a tag passed to HCS to allow it to differentiate between
<ide> // container creator management stacks. We hard code "docker" in the case
<ide> // of docker. | 1 |
Text | Text | update react 18 configuration | 4ac0227423287223373dcfaf6d4ddf78aa4201f6 | <ide><path>docs/advanced-features/react-18.md
<ide> module.exports = {
<ide> }
<ide> ```
<ide>
<del>Next, you need to customize your `pages/_document` component to be a functional component by removing any static methods like `getInitialProps` or exports like `getServerSideProps`
<add>Next, if you already have customized `pages/_document` component, you need to remove the `getInitialProps` static method and the `getServerSideProps` export if there’s any, otherwise it won't work with server components. If no custom Document component is provided, Next.js will fallback to a default one like below.
<ide>
<ide> ```jsx
<ide> // pages/_document.js
<ide> To see a full example, check out [link to the demo and repository](https://githu
<ide> While RSC and SSR streaming is still in the alpha stage, not all Next.js APIs are supported. The following Next.js APIs have limited functionality inside Server Components:
<ide>
<ide> - React internals: Most of React hooks such as `useContext`, `useState`, `useReducer`, `useEffect` and `useLayoutEffect` are not supported as of today since Server Components are executed per requests and aren't stateful.
<add>- `next/head`
<ide> - Partial: Note that Inside `.client.js` components `useRouter` is supported
<ide> - Styled JSX
<ide> - CSS Modules | 1 |
Ruby | Ruby | replace template’s `j1` with `deparallelize` | 410121d8edfc8fd35cbf3739854cb69652c82ea1 | <ide><path>Library/Homebrew/cmd/create.rb
<ide> class #{Formula.class_s name} < Formula
<ide> depends_on :x11 # if your formula requires any X11/XQuartz components
<ide>
<ide> def install
<del> # ENV.j1 # if your formula's build system can't parallelize
<add> # ENV.deparallelize # if your formula fails when building in parallel
<ide>
<ide> <% if mode == :cmake %>
<ide> system "cmake", ".", *std_cmake_args | 1 |
Go | Go | add failing test case for issue | 53c5b1856d91093fed1c2d3f038d227f5fdef4b8 | <ide><path>integration/container_test.go
<ide> func TestOutput(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestContainerNetwork(t *testing.T) {
<del> runtime := mkRuntime(t)
<del> defer nuke(runtime)
<del> container, _, err := runtime.Create(
<del> &runconfig.Config{
<del> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"ping", "-c", "1", "127.0.0.1"},
<del> },
<del> "",
<del> )
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer runtime.Destroy(container)
<del> if err := container.Run(); err != nil {
<del> t.Fatal(err)
<del> }
<del> if code := container.State.GetExitCode(); code != 0 {
<del> t.Fatalf("Unexpected ping 127.0.0.1 exit code %d (expected 0)", code)
<del> }
<del>}
<del>
<ide> func TestKillDifferentUser(t *testing.T) {
<ide> runtime := mkRuntime(t)
<ide> defer nuke(runtime)
<ide> func TestVolumesFromWithVolumes(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestContainerNetwork(t *testing.T) {
<add> runtime := mkRuntime(t)
<add> defer nuke(runtime)
<add> container, _, err := runtime.Create(
<add> &runconfig.Config{
<add> Image: GetTestImage(runtime).ID,
<add> // If I change this to ping 8.8.8.8 it fails. Any idea why? - timthelion
<add> Cmd: []string{"ping", "-c", "1", "127.0.0.1"},
<add> },
<add> "",
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container)
<add> if err := container.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add> if code := container.State.GetExitCode(); code != 0 {
<add> t.Fatalf("Unexpected ping 127.0.0.1 exit code %d (expected 0)", code)
<add> }
<add>}
<add>
<add>// Issue #4681
<add>func TestLoopbackFunctionsWhenNetworkingIsDissabled(t *testing.T) {
<add> runtime := mkRuntime(t)
<add> defer nuke(runtime)
<add> container, _, err := runtime.Create(
<add> &runconfig.Config{
<add> Image: GetTestImage(runtime).ID,
<add> Cmd: []string{"ping", "-c", "1", "127.0.0.1"},
<add> NetworkDisabled: true,
<add> },
<add> "",
<add> )
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer runtime.Destroy(container)
<add> if err := container.Run(); err != nil {
<add> t.Fatal(err)
<add> }
<add> if code := container.State.GetExitCode(); code != 0 {
<add> t.Fatalf("Unexpected ping 127.0.0.1 exit code %d (expected 0)", code)
<add> }
<add>}
<add>
<ide> func TestOnlyLoopbackExistsWhenUsingDisableNetworkOption(t *testing.T) {
<ide> eng := NewTestEngine(t)
<ide> runtime := mkRuntimeFromEngine(eng, t) | 1 |
Ruby | Ruby | add brew-profile to contrib | cf66686a17617e6b9235f8aa655d6f8d3c846abf | <ide><path>Library/Contributions/cmd/brew-profile.rb
<add>begin
<add> require 'rubygems'
<add> require 'ruby-prof'
<add>rescue LoadError
<add> abort 'This command requires the ruby-prof gem'
<add>end
<add>
<add>require 'formula'
<add>
<add>RubyProf.start
<add>Formula.names.each { |n| Formula.factory(n) }
<add>RubyProf::GraphHtmlPrinter.new(RubyProf.stop).print(STDOUT) | 1 |
Go | Go | fix flaky testportmappingv6config | c721bad8ccddeb353e71d4b4b26ad878d1ae8bee | <ide><path>libnetwork/drivers/bridge/port_mapping_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/libnetwork/netlabel"
<add> "github.com/docker/docker/libnetwork/ns"
<ide> "github.com/docker/docker/libnetwork/testutils"
<ide> "github.com/docker/docker/libnetwork/types"
<ide> "github.com/docker/docker/pkg/reexec"
<ide> func TestPortMappingConfig(t *testing.T) {
<ide>
<ide> func TestPortMappingV6Config(t *testing.T) {
<ide> defer testutils.SetupTestOSContext(t)()
<add> if err := loopbackUp(); err != nil {
<add> t.Fatalf("Could not bring loopback iface up: %v", err)
<add> }
<add>
<ide> d := newDriver()
<ide>
<ide> config := &configuration{
<ide> func TestPortMappingV6Config(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> }
<add>
<add>func loopbackUp() error {
<add> nlHandle := ns.NlHandle()
<add> iface, err := nlHandle.LinkByName("lo")
<add> if err != nil {
<add> return err
<add> }
<add> return nlHandle.LinkSetUp(iface)
<add>} | 1 |
Ruby | Ruby | construct new argv from an options collection | cf08b71bf8dc94eaaeb1b0cde68b97a7e02ca129 | <ide><path>Library/Homebrew/build_options.rb
<ide> class BuildOptions
<ide> include Enumerable
<ide>
<ide> def initialize args
<del> @args = Array.new(args).extend(HomebrewArgvExtension)
<add> @args = Options.coerce(args)
<ide> @options = Options.new
<ide> end
<ide>
<ide> def as_flags
<ide> end
<ide>
<ide> def include? name
<del> @args.include? '--' + name
<add> args.include? '--' + name
<ide> end
<ide>
<ide> def with? name
<ide> def without? name
<ide> end
<ide>
<ide> def head?
<del> @args.flag? '--HEAD'
<add> args.include? '--HEAD'
<ide> end
<ide>
<ide> def devel?
<del> @args.include? '--devel'
<add> args.include? '--devel'
<ide> end
<ide>
<ide> def stable?
<ide> def stable?
<ide>
<ide> # True if the user requested a universal build.
<ide> def universal?
<del> @args.include?('--universal') && has_option?('universal')
<add> args.include?('--universal') && has_option?('universal')
<ide> end
<ide>
<ide> # Request a 32-bit only build.
<ide> # This is needed for some use-cases though we prefer to build Universal
<ide> # when a 32-bit version is needed.
<ide> def build_32_bit?
<del> @args.include?('--32-bit') && has_option?('32-bit')
<add> args.include?('--32-bit') && has_option?('32-bit')
<ide> end
<ide>
<ide> def used_options
<del> Options.new((as_flags & @args.options_only).map { |o| Option.new(o) })
<add> Options.new(@options & @args)
<ide> end
<ide>
<ide> def unused_options
<del> Options.new((as_flags - @args.options_only).map { |o| Option.new(o) })
<add> Options.new(@options - @args)
<ide> end
<ide> end
<ide><path>Library/Homebrew/dependencies.rb
<ide> def recommended?
<ide> end
<ide>
<ide> def options
<del> Options.new((tags - RESERVED_TAGS).map { |o| Option.new(o) })
<add> Options.coerce(tags - RESERVED_TAGS)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/formula.rb
<ide> def #{cksum}(val=nil)
<ide> end
<ide>
<ide> def build
<del> @build ||= BuildOptions.new(ARGV)
<add> @build ||= BuildOptions.new(ARGV.options_only)
<ide> end
<ide>
<ide> def url val=nil, specs=nil
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def initialize ff
<ide> @f = ff
<ide> @show_header = false
<ide> @ignore_deps = ARGV.ignore_deps? || ARGV.interactive?
<del> @options = []
<add> @options = Options.new
<ide>
<ide> @@attempted ||= Set.new
<ide>
<ide> def build_time
<ide> @build_time ||= Time.now - @start_time unless pour_bottle? or ARGV.interactive? or @start_time.nil?
<ide> end
<ide>
<add> def build_argv
<add> @build_argv ||= begin
<add> opts = Options.coerce(ARGV.options_only)
<add> unless opts.include? '--fresh'
<add> opts.concat(options) # from a dependent formula
<add> opts.concat((tab.used_options rescue [])) # from a previous install
<add> end
<add> opts << '--build-from-source' # don't download bottle
<add> end
<add> end
<add>
<ide> def build
<ide> FileUtils.rm Dir["#{HOMEBREW_LOGS}/#{f}/*"]
<ide>
<ide> def build
<ide> # I'm guessing this is not a good way to do this, but I'm no UNIX guru
<ide> ENV['HOMEBREW_ERROR_PIPE'] = write.to_i.to_s
<ide>
<del> args = ARGV.clone
<del> args.concat(tab.used_options.as_flags) unless tab.nil? or args.include? '--fresh'
<del> # FIXME: enforce the download of the non-bottled package
<del> # in the spawned Ruby process.
<del> args << '--build-from-source'
<del> # Add any options that were passed into this FormulaInstaller instance.
<del> # Usually this represents options being passed by a dependent formula.
<del> args.concat options
<del> args.uniq!
<del>
<ide> fork do
<ide> begin
<ide> read.close
<ide> def build
<ide> '-rbuild',
<ide> '--',
<ide> f.path,
<del> *args.options_only
<add> *build_argv
<ide> rescue Exception => e
<ide> Marshal.dump(e, write)
<ide> write.close
<ide> def build
<ide>
<ide> raise "Empty installation" if Dir["#{f.prefix}/*"].empty?
<ide>
<del> Tab.create(f, args).write # INSTALL_RECEIPT.json
<add> Tab.create(f, build_argv).write # INSTALL_RECEIPT.json
<ide>
<ide> rescue Exception => e
<ide> ignore_interrupts do
<ide><path>Library/Homebrew/options.rb
<ide> class Option
<ide> attr_reader :name, :description, :flag
<ide>
<ide> def initialize(name, description=nil)
<del> @name = name.to_s[/^(?:--)?(.+)$/, 1]
<add> @name, @flag = split_name(name)
<ide> @description = description.to_s
<del> @flag = "--#{@name}"
<ide> end
<ide>
<ide> def to_s
<ide> def eql?(other)
<ide> def hash
<ide> name.hash
<ide> end
<add>
<add> private
<add>
<add> def split_name(name)
<add> case name
<add> when /^-[a-zA-Z]$/
<add> [name[1..1], name]
<add> when /^--(.+)$/
<add> [$1, name]
<add> else
<add> [name, "--#{name}"]
<add> end
<add> end
<ide> end
<ide>
<ide> class Options
<ide> def -(o)
<ide> Options.new(@options - o)
<ide> end
<ide>
<add> def &(o)
<add> Options.new(@options & o)
<add> end
<add>
<ide> def *(arg)
<ide> @options.to_a * arg
<ide> end
<ide> def include?(o)
<ide> any? { |opt| opt == o || opt.name == o || opt.flag == o }
<ide> end
<ide>
<add> def concat(o)
<add> o.each { |opt| @options << opt }
<add> self
<add> end
<add>
<ide> def to_a
<ide> @options.to_a
<ide> end
<ide> alias_method :to_ary, :to_a
<add>
<add> def self.coerce(arg)
<add> case arg
<add> when self then arg
<add> when Option then new << arg
<add> when Array then new(arg.map { |a| Option.new(a.to_s) })
<add> else raise TypeError, "Cannot convert #{arg.inspect} to Options"
<add> end
<add> end
<ide> end
<ide><path>Library/Homebrew/tab.rb
<ide> def universal?
<ide> end
<ide>
<ide> def used_options
<del> Options.new(super.map { |o| Option.new(o) })
<add> Options.coerce(super)
<ide> end
<ide>
<ide> def unused_options
<del> Options.new(super.map { |o| Option.new(o) })
<add> Options.coerce(super)
<ide> end
<ide>
<ide> def options
<ide><path>Library/Homebrew/test/test_build_options.rb
<ide>
<ide> class BuildOptionsTests < Test::Unit::TestCase
<ide> def setup
<del> args = %w{--with-foo --with-bar --without-qux}.extend(HomebrewArgvExtension)
<add> args = %w{--with-foo --with-bar --without-qux}
<ide> @build = BuildOptions.new(args)
<ide> @build.add("with-foo")
<ide> @build.add("with-bar")
<ide><path>Library/Homebrew/test/test_options.rb
<ide> def test_description
<ide> assert_empty @option.description
<ide> assert_equal "foo", Option.new("foo", "foo").description
<ide> end
<add>
<add> def test_preserves_short_options
<add> option = Option.new("-d")
<add> assert_equal "-d", option.flag
<add> assert_equal "d", option.name
<add> end
<ide> end
<ide>
<ide> class OptionsTests < Test::Unit::TestCase
<ide> def test_to_ary
<ide> @options << option
<ide> assert_equal [option], @options.to_ary
<ide> end
<add>
<add> def test_concat_array
<add> option = Option.new("foo")
<add> @options.concat([option])
<add> assert @options.include?(option)
<add> assert_equal [option], @options.to_a
<add> end
<add>
<add> def test_concat_options
<add> option = Option.new("foo")
<add> opts = Options.new
<add> opts << option
<add> @options.concat(opts)
<add> assert @options.include?(option)
<add> assert_equal [option], @options.to_a
<add> end
<add>
<add> def test_concat_returns_self
<add> assert_same @options, (@options.concat([]))
<add> end
<add>
<add> def test_intersection
<add> foo, bar, baz = %w{foo bar baz}.map { |o| Option.new(o) }
<add> options = Options.new << foo << bar
<add> @options << foo << baz
<add> assert_equal [foo], (@options & options).to_a
<add> end
<add>
<add> def test_coerce_with_options
<add> assert_same @options, Options.coerce(@options)
<add> end
<add>
<add> def test_coerce_with_option
<add> option = Option.new("foo")
<add> assert_equal option, Options.coerce(option).to_a.first
<add> end
<add>
<add> def test_coerce_with_array
<add> array = %w{--foo --bar}
<add> option1 = Option.new("foo")
<add> option2 = Option.new("bar")
<add> assert_equal [option1, option2].sort, Options.coerce(array).to_a.sort
<add> end
<add>
<add> def test_coerce_raises_for_inappropriate_types
<add> assert_raises(TypeError) { Options.coerce(1) }
<add> end
<ide> end | 8 |
Python | Python | remove this deprecated alias | 0609255dd24ee300b56387f1006c074978ebb832 | <ide><path>django/core/mail/__init__.py
<ide> SafeMIMEText, SafeMIMEMultipart,
<ide> DEFAULT_ATTACHMENT_MIME_TYPE, make_msgid,
<ide> BadHeaderError, forbid_multi_line_headers)
<del>from django.core.mail.backends.smtp import EmailBackend as _SMTPConnection
<add>
<ide>
<ide> def get_connection(backend=None, fail_silently=False, **kwds):
<ide> """Load an email backend and return an instance of it. | 1 |
Go | Go | remove docker from some functions | de5c80b4f3ca51343fb4b698362ad232478b43be | <ide><path>distribution/pull_v1.go
<ide> func (p *v1Puller) Pull(ctx context.Context, ref reference.Named, platform strin
<ide> tr := transport.NewTransport(
<ide> // TODO(tiborvass): was ReceiveTimeout
<ide> registry.NewTransport(tlsConfig),
<del> registry.DockerHeaders(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
<add> registry.Headers(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
<ide> )
<ide> client := registry.HTTPClient(tr)
<ide> v1Endpoint := p.endpoint.ToV1Endpoint(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)
<ide><path>distribution/push_v1.go
<ide> func (p *v1Pusher) Push(ctx context.Context) error {
<ide> tr := transport.NewTransport(
<ide> // TODO(tiborvass): was NoTimeout
<ide> registry.NewTransport(tlsConfig),
<del> registry.DockerHeaders(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
<add> registry.Headers(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)...,
<ide> )
<ide> client := registry.HTTPClient(tr)
<ide> v1Endpoint := p.endpoint.ToV1Endpoint(dockerversion.DockerUserAgent(ctx), p.config.MetaHeaders)
<ide><path>distribution/registry.go
<ide> func NewV2Repository(ctx context.Context, repoInfo *registry.RepositoryInfo, end
<ide> base.Dial = proxyDialer.Dial
<ide> }
<ide>
<del> modifiers := registry.DockerHeaders(dockerversion.DockerUserAgent(ctx), metaHeaders)
<add> modifiers := registry.Headers(dockerversion.DockerUserAgent(ctx), metaHeaders)
<ide> authTransport := transport.NewTransport(base, modifiers...)
<ide>
<ide> challengeManager, foundVersion, err := registry.PingV2Registry(endpoint.URL, authTransport)
<ide><path>opts/hosts.go
<ide> var (
<ide> // ValidateHost validates that the specified string is a valid host and returns it.
<ide> func ValidateHost(val string) (string, error) {
<ide> host := strings.TrimSpace(val)
<del> // The empty string means default and is not handled by parseDockerDaemonHost
<add> // The empty string means default and is not handled by parseDaemonHost
<ide> if host != "" {
<del> _, err := parseDockerDaemonHost(host)
<add> _, err := parseDaemonHost(host)
<ide> if err != nil {
<ide> return val, err
<ide> }
<ide> func ParseHost(defaultToTLS bool, val string) (string, error) {
<ide> }
<ide> } else {
<ide> var err error
<del> host, err = parseDockerDaemonHost(host)
<add> host, err = parseDaemonHost(host)
<ide> if err != nil {
<ide> return val, err
<ide> }
<ide> }
<ide> return host, nil
<ide> }
<ide>
<del>// parseDockerDaemonHost parses the specified address and returns an address that will be used as the host.
<add>// parseDaemonHost parses the specified address and returns an address that will be used as the host.
<ide> // Depending of the address specified, this may return one of the global Default* strings defined in hosts.go.
<del>func parseDockerDaemonHost(addr string) (string, error) {
<add>func parseDaemonHost(addr string) (string, error) {
<ide> addrParts := strings.SplitN(addr, "://", 2)
<ide> if len(addrParts) == 1 && addrParts[0] != "" {
<ide> addrParts = []string{"tcp", addrParts[0]}
<ide><path>opts/hosts_test.go
<ide> func TestParseDockerDaemonHost(t *testing.T) {
<ide> "localhost:5555/path": "tcp://localhost:5555/path",
<ide> }
<ide> for invalidAddr, expectedError := range invalids {
<del> if addr, err := parseDockerDaemonHost(invalidAddr); err == nil || err.Error() != expectedError {
<add> if addr, err := parseDaemonHost(invalidAddr); err == nil || err.Error() != expectedError {
<ide> t.Errorf("tcp %v address expected error %q return, got %q and addr %v", invalidAddr, expectedError, err, addr)
<ide> }
<ide> }
<ide> for validAddr, expectedAddr := range valids {
<del> if addr, err := parseDockerDaemonHost(validAddr); err != nil || addr != expectedAddr {
<add> if addr, err := parseDaemonHost(validAddr); err != nil || addr != expectedAddr {
<ide> t.Errorf("%v -> expected %v, got (%v) addr (%v)", validAddr, expectedAddr, err, addr)
<ide> }
<ide> }
<ide><path>registry/auth.go
<ide> func (err fallbackError) Error() string {
<ide> func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) {
<ide> logrus.Debugf("attempting v2 login to registry endpoint %s", strings.TrimRight(endpoint.URL.String(), "/")+"/v2/")
<ide>
<del> modifiers := DockerHeaders(userAgent, nil)
<add> modifiers := Headers(userAgent, nil)
<ide> authTransport := transport.NewTransport(NewTransport(endpoint.TLSConfig), modifiers...)
<ide>
<ide> credentialAuthConfig := *authConfig
<ide><path>registry/endpoint_v1.go
<ide> func newV1Endpoint(address url.URL, tlsConfig *tls.Config, userAgent string, met
<ide>
<ide> // TODO(tiborvass): make sure a ConnectTimeout transport is used
<ide> tr := NewTransport(tlsConfig)
<del> endpoint.client = HTTPClient(transport.NewTransport(tr, DockerHeaders(userAgent, metaHeaders)...))
<add> endpoint.client = HTTPClient(transport.NewTransport(tr, Headers(userAgent, metaHeaders)...))
<ide> return endpoint
<ide> }
<ide>
<ide><path>registry/registry.go
<ide> func ReadCertsDirectory(tlsConfig *tls.Config, directory string) error {
<ide> return nil
<ide> }
<ide>
<del>// DockerHeaders returns request modifiers with a User-Agent and metaHeaders
<del>func DockerHeaders(userAgent string, metaHeaders http.Header) []transport.RequestModifier {
<add>// Headers returns request modifiers with a User-Agent and metaHeaders
<add>func Headers(userAgent string, metaHeaders http.Header) []transport.RequestModifier {
<ide> modifiers := []transport.RequestModifier{}
<ide> if userAgent != "" {
<ide> modifiers = append(modifiers, transport.NewHeaderRequestModifier(http.Header{
<ide><path>registry/registry_test.go
<ide> func spawnTestRegistrySession(t *testing.T) *Session {
<ide> }
<ide> userAgent := "docker test client"
<ide> var tr http.RoundTripper = debugTransport{NewTransport(nil), t.Log}
<del> tr = transport.NewTransport(AuthTransport(tr, authConfig, false), DockerHeaders(userAgent, nil)...)
<add> tr = transport.NewTransport(AuthTransport(tr, authConfig, false), Headers(userAgent, nil)...)
<ide> client := HTTPClient(tr)
<ide> r, err := NewSession(client, authConfig, endpoint)
<ide> if err != nil {
<ide><path>registry/service.go
<ide> func (s *DefaultService) Search(ctx context.Context, term string, limit int, aut
<ide> },
<ide> }
<ide>
<del> modifiers := DockerHeaders(userAgent, nil)
<add> modifiers := Headers(userAgent, nil)
<ide> v2Client, foundV2, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
<ide> if err != nil {
<ide> if fErr, ok := err.(fallbackError); ok { | 10 |
Python | Python | add sphinx-panels as an extension | 64e549a992ef7c908e46c2b243aa2bde50642d15 | <ide><path>doc/source/conf.py
<ide> class PyTypeObject(ctypes.Structure):
<ide> 'sphinx.ext.ifconfig',
<ide> 'matplotlib.sphinxext.plot_directive',
<ide> 'IPython.sphinxext.ipython_console_highlighting',
<del> 'IPython.sphinxext.ipython_directive',\
<add> 'IPython.sphinxext.ipython_directive',
<ide> 'sphinx.ext.mathjax',
<add> 'sphinx_panels',
<ide> ]
<ide>
<ide> skippable_extensions = [ | 1 |
Text | Text | fix description of `docker swarm update --help` | 2f0e00f58723cb3e063b49f564173b3768476c99 | <ide><path>docs/reference/commandline/swarm_update.md
<ide> Options:
<ide> --autolock Change manager autolocking setting (true|false)
<ide> --cert-expiry duration Validity period for node certificates (ns|us|ms|s|m|h) (default 2160h0m0s)
<ide> --dispatcher-heartbeat duration Dispatcher heartbeat period (ns|us|ms|s|m|h) (default 5s)
<del> --external-ca value Specifications of one or more certificate signing endpoints
<add> --external-ca external-ca Specifications of one or more certificate signing endpoints
<ide> --help Print usage
<del> --max-snapshots int Number of additional Raft snapshots to retain
<del> --snapshot-interval int Number of log entries between Raft snapshots
<add> --max-snapshots uint Number of additional Raft snapshots to retain
<add> --snapshot-interval uint Number of log entries between Raft snapshots (default 10000)
<ide> --task-history-limit int Task history retention limit (default 5)
<ide> ```
<ide> | 1 |
Text | Text | adjust the plurality of goal to goals | a15c584f202abcb25e269e2d4e22da0f5be0d95c | <ide><path>docs/Network.md
<ide> permalink: docs/network.html
<ide> next: timers
<ide> ---
<ide>
<del>One of React Native goal is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example.
<add>One of React Native goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example.
<ide>
<ide> ## XMLHttpRequest
<ide> | 1 |
PHP | PHP | convert radio to use selected instead of value | 88100a4bb7ee56b074b76f2ef4f579786a192dd9 | <ide><path>src/View/Input/Radio.php
<ide> public function __construct($templates) {
<ide> * - `options` - An array of options. See below for more information.
<ide> * - `disabled` - Either true or an array of inputs to disable.
<ide> * When true, the select element will be disabled.
<del> * - `value` - A string of the option to mark as selected.
<add> * - `selected` - A string of the option to mark as selected.
<ide> * - `label` - Either false to disable label generation, or
<ide> * an array of attributes for all labels.
<ide> *
<ide> public function render($data) {
<ide> 'name' => '',
<ide> 'options' => [],
<ide> 'disabled' => null,
<del> 'value' => null,
<add> 'selected' => null,
<ide> 'escape' => true,
<ide> 'label' => true,
<ide> 'empty' => false,
<ide> protected function _renderInput($val, $text, $data) {
<ide> $radio['id'] = Inflector::slug($radio['name'] . '_' . $radio['value']);
<ide> }
<ide>
<del> if (isset($data['value']) && strval($data['value']) === strval($radio['value'])) {
<add> if (isset($data['selected']) && strval($data['selected']) === strval($radio['value'])) {
<ide> $radio['checked'] = true;
<ide> }
<ide>
<ide><path>tests/TestCase/View/Input/RadioTest.php
<ide> public function testRenderSelected() {
<ide> $radio = new Radio($this->templates);
<ide> $data = [
<ide> 'name' => 'Versions[ver]',
<del> 'value' => '1',
<add> 'selected' => '1',
<ide> 'options' => [
<ide> 1 => 'one',
<ide> '1x' => 'one x', | 2 |
Text | Text | fix line length in worker_threads.md | ca60f5fb447e545270ef3c8f6dbf495b64b5ee12 | <ide><path>doc/api/worker_threads.md
<ide> markAsUntransferable(pooledBuffer);
<ide> const { port1 } = new MessageChannel();
<ide> port1.postMessage(typedArray1, [ typedArray1.buffer ]);
<ide>
<del>// The following line prints the contents of typedArray1 -- it still owns its
<del>// memory and has been cloned, not transferred. Without `markAsUntransferable()`,
<del>// this would print an empty Uint8Array. typedArray2 is intact as well.
<add>// The following line prints the contents of typedArray1 -- it still owns
<add>// its memory and has been cloned, not transferred. Without
<add>// `markAsUntransferable()`, this would print an empty Uint8Array.
<add>// typedArray2 is intact as well.
<ide> console.log(typedArray1);
<ide> console.log(typedArray2);
<ide> ``` | 1 |
Ruby | Ruby | remove illegal testcase | 4db3e51c8ec307ba0d068e4403f7a66805b3c3ff | <ide><path>Library/Homebrew/test/test_pkg_version.rb
<ide> def test_parse
<ide> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0")
<ide> assert_equal PkgVersion.new(Version.new("1.0"), 0), PkgVersion.parse("1.0_0")
<ide> assert_equal PkgVersion.new(Version.new("2.1.4"), 0), PkgVersion.parse("2.1.4_0")
<del> assert_equal PkgVersion.new(Version.new("2.1.4_1"), 0), PkgVersion.parse("2.1.4_1_0")
<ide> assert_equal PkgVersion.new(Version.new("1.0.1e"), 1), PkgVersion.parse("1.0.1e_1")
<ide> end
<ide> | 1 |
Javascript | Javascript | add proptypes.checkproptypes api | 600685bdefbb965129a73536a65b86cbaa73de48 | <ide><path>src/isomorphic/classic/types/ReactPropTypes.js
<ide>
<ide> var ReactElement = require('ReactElement');
<ide> var ReactPropTypesSecret = require('ReactPropTypesSecret');
<add>var checkReactTypeSpec = require('checkReactTypeSpec');
<ide>
<ide> var emptyFunction = require('emptyFunction');
<ide> var getIteratorFn = require('getIteratorFn');
<ide> if (__DEV__) {
<ide> };
<ide> }
<ide>
<add>function checkPropTypes(propTypes, object, location, componentName, warnOnRepeat) {
<add> checkReactTypeSpec(propTypes, object, location, componentName, null, null, warnOnRepeat);
<add>}
<add>ReactPropTypes.checkPropTypes = checkPropTypes;
<add>
<add>
<ide> /**
<ide> * inlined Object.is polyfill to avoid requiring consumers ship their own
<ide> * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
<ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
<ide> var PropTypes;
<ide> var React;
<ide> var ReactFragment;
<ide> var ReactTestUtils;
<del>var ReactPropTypesSecret;
<ide>
<ide> var Component;
<ide> var MyComponent;
<ide>
<del>function typeCheckFail(declaration, value, message) {
<del> var props = {testProp: value};
<del> var error = declaration(
<del> props,
<del> 'testProp',
<del> 'testComponent',
<del> 'prop',
<del> null,
<del> ReactPropTypesSecret
<del> );
<del> expect(error instanceof Error).toBe(true);
<del> expect(error.message).toBe(message);
<add>function getPropTypeWarningMessage(propTypes, object, componentName) {
<add> if (!console.error.calls) {
<add> spyOn(console, 'error');
<add> } else {
<add> console.error.calls.reset();
<add> }
<add> PropTypes.checkPropTypes(propTypes, object, 'prop', 'testComponent', true);
<add> const callCount = console.error.calls.count();
<add> if (callCount > 1) {
<add> throw new Error('Too many warnings.');
<add> }
<add> const message = console.error.calls.argsFor(0)[0] || null;
<add> console.error.calls.reset();
<add>
<add> return message;
<add>}
<add>
<add>function typeCheckFail(declaration, value, expectedMessage) {
<add> const propTypes = {
<add> testProp: declaration,
<add> };
<add> const props = {
<add> testProp: value,
<add> };
<add> const message = getPropTypeWarningMessage(propTypes, props, 'testComponent');
<add> expect(message).toContain(expectedMessage);
<ide> }
<ide>
<ide> function typeCheckFailRequiredValues(declaration) {
<ide> var specifiedButIsNullMsg = 'The prop `testProp` is marked as required in ' +
<ide> '`testComponent`, but its value is `null`.';
<ide> var unspecifiedMsg = 'The prop `testProp` is marked as required in ' +
<ide> '`testComponent`, but its value is \`undefined\`.';
<del> var props1 = {testProp: null};
<del> var error1 = declaration(
<del> props1,
<del> 'testProp',
<del> 'testComponent',
<del> 'prop',
<del> null,
<del> ReactPropTypesSecret
<del> );
<del> expect(error1 instanceof Error).toBe(true);
<del> expect(error1.message).toBe(specifiedButIsNullMsg);
<del> var props2 = {testProp: undefined};
<del> var error2 = declaration(
<del> props2,
<del> 'testProp',
<del> 'testComponent',
<del> 'prop',
<del> null,
<del> ReactPropTypesSecret
<del> );
<del> expect(error2 instanceof Error).toBe(true);
<del> expect(error2.message).toBe(unspecifiedMsg);
<del> var props3 = {};
<del> var error3 = declaration(
<del> props3,
<del> 'testProp',
<del> 'testComponent',
<del> 'prop',
<del> null,
<del> ReactPropTypesSecret
<del> );
<del> expect(error3 instanceof Error).toBe(true);
<del> expect(error3.message).toBe(unspecifiedMsg);
<add>
<add> var propTypes = { testProp: declaration };
<add>
<add> // Required prop is null
<add> var message1 = getPropTypeWarningMessage(propTypes, { testProp: null }, 'testComponent');
<add> expect(message1).toContain(specifiedButIsNullMsg);
<add>
<add> // Required prop is undefined
<add> var message2 = getPropTypeWarningMessage(propTypes, { testProp: undefined }, 'testComponent');
<add> expect(message2).toContain(unspecifiedMsg);
<add>
<add> // Required prop is not a member of props object
<add> var message3 = getPropTypeWarningMessage(propTypes, {}, 'testComponent');
<add> expect(message3).toContain(unspecifiedMsg);
<ide> }
<ide>
<ide> function typeCheckPass(declaration, value) {
<del> var props = {testProp: value};
<del> var error = declaration(
<del> props,
<del> 'testProp',
<del> 'testComponent',
<del> 'prop',
<del> null,
<del> ReactPropTypesSecret
<del> );
<del> expect(error).toBe(null);
<add> const propTypes = {
<add> testProp: declaration,
<add> };
<add> const props = {
<add> testProp: value,
<add> };
<add> const message = getPropTypeWarningMessage(propTypes, props, 'testComponent');
<add> expect(message).toBe(null);
<ide> }
<ide>
<ide> function expectWarningInDevelopment(declaration, value) {
<ide> describe('ReactPropTypes', () => {
<ide> React = require('React');
<ide> ReactFragment = require('ReactFragment');
<ide> ReactTestUtils = require('ReactTestUtils');
<del> ReactPropTypesSecret = require('ReactPropTypesSecret');
<ide> });
<ide>
<ide> describe('Primitive Types', () => {
<ide><path>src/shared/types/checkReactTypeSpec.js
<ide> function checkReactTypeSpec(
<ide> // It is only safe to pass fiber if it is the work-in-progress version, and
<ide> // only during reconciliation (begin and complete phase).
<ide> workInProgressOrDebugID,
<add> // Default behavior is to suppress repeated warnings, but can be overridden
<add> warnOnRepeat
<ide> ) {
<ide> for (var typeSpecName in typeSpecs) {
<ide> if (typeSpecs.hasOwnProperty(typeSpecName)) {
<ide> function checkReactTypeSpec(
<ide> typeSpecName,
<ide> typeof error
<ide> );
<del> if (error instanceof Error && !(error.message in loggedTypeFailures)) {
<add> if (error instanceof Error && (warnOnRepeat || !(error.message in loggedTypeFailures))) {
<ide> // Only monitor this failure once because there tends to be a lot of the
<ide> // same error.
<ide> loggedTypeFailures[error.message] = true; | 3 |
Ruby | Ruby | handle legacy options in the method_added hook | d122ae8eea053b6f1074c34ce55ebc3dc26e0801 | <ide><path>Library/Homebrew/formula.rb
<ide> def initialize(name, path, spec)
<ide>
<ide> @active_spec = determine_active_spec(spec)
<ide> validate_attributes :url, :name, :version
<del> active_spec.add_legacy_options(options)
<ide> @pkg_version = PkgVersion.new(version, revision)
<ide> @pin = FormulaPin.new(self)
<ide> end
<ide> def post_install; end
<ide> # tell the user about any caveats regarding this package, return a string
<ide> def caveats; nil end
<ide>
<del> # any e.g. configure options for this package
<del> def options; [] end
<del>
<ide> # Deprecated
<ide> DATA = :DATA
<ide> def patches; {} end
<ide> def self.method_added method
<ide> raise "You cannot override Formula#brew in class #{name}"
<ide> when :test
<ide> @test_defined = true
<add> when :options
<add> instance = allocate
<add>
<add> specs.each do |spec|
<add> instance.options.each do |opt, desc|
<add> spec.options << Option.new(opt[/^--(.+)$/, 1], desc)
<add> end
<add> end
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/software_spec.rb
<ide> def add_dep_option(dep)
<ide> options << Option.new("without-#{name}", "Build without #{name} support")
<ide> end
<ide> end
<del>
<del> def add_legacy_options(list)
<del> list.each { |opt, desc| options << Option.new(opt[/^--(.+)$/, 1], desc) }
<del> end
<ide> end
<ide>
<ide> class HeadSoftwareSpec < SoftwareSpec | 2 |
Javascript | Javascript | remove unneeded type import | bc863596f4bb2a312f4b37132b297927bce8cb34 | <ide><path>lib/Chunk.js
<ide> const ERR_CHUNK_INITIAL =
<ide>
<ide> /** @typedef {import("./Module")} Module */
<ide> /** @typedef {import("./ChunkGroup")} ChunkGroup */
<del>/** @typedef {import("./Entrypoint")} Entrypoint */
<ide> /** @typedef {import("./ModuleReason")} ModuleReason */
<ide> /** @typedef {import("webpack-sources").Source} Source */
<ide> /** @typedef {import("./util/createHash").Hash} Hash */ | 1 |
Ruby | Ruby | remove dead code | 2e0b0c1dab7eeafb58d29ac6e71071118c91365f | <ide><path>activerecord/test/cases/pooled_connections_test.rb
<ide> def teardown
<ide> @per_test_teardown.each {|td| td.call }
<ide> end
<ide>
<del> def checkout_connections
<del> ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :checkout_timeout => 0.3}))
<del> @connections = []
<del> @timed_out = 0
<del>
<del> 4.times do
<del> Thread.new do
<del> begin
<del> @connections << ActiveRecord::Base.connection_pool.checkout
<del> rescue ActiveRecord::ConnectionTimeoutError
<del> @timed_out += 1
<del> end
<del> end.join
<del> end
<del> end
<del>
<ide> # Will deadlock due to lack of Monitor timeouts in 1.9
<ide> def checkout_checkin_connections(pool_size, threads)
<ide> ActiveRecord::Base.establish_connection(@connection.merge({:pool => pool_size, :checkout_timeout => 0.5})) | 1 |
Ruby | Ruby | add audit check for system "xcodebuild" | 26c71b19f6f715e1f558da1c904aafe6eecebe11 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_text
<ide> problem "use \"scons *args\" instead of \"system 'scons', *args\""
<ide> end
<ide>
<del> if text =~ /system\s+['"]xcodebuild/ && text !~ /SYMROOT=/
<del> problem "xcodebuild should be passed an explicit \"SYMROOT\""
<add> if text =~ /system\s+['"]xcodebuild/
<add> problem %{use "xcodebuild *args" instead of "system 'xcodebuild', *args"}
<add> end
<add>
<add> if text =~ /xcodebuild[ (]["'*]/ && text !~ /SYMROOT=/
<add> problem %{xcodebuild should be passed an explicit "SYMROOT"}
<ide> end
<ide>
<ide> if text =~ /Formula\.factory\(/ | 1 |
Ruby | Ruby | add a setter for the cookie jar | 447c2cb1b0684c6efcfe1063222d537567fa1d3e | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> def handle_unverified_request
<ide> request.session = NullSessionHash.new(request.env)
<ide> request.env['action_dispatch.request.flash_hash'] = nil
<ide> request.env['rack.session.options'] = { skip: true }
<del> request.env['action_dispatch.cookies'] = NullCookieJar.build(request, {})
<add> request.cookie_jar = NullCookieJar.build(request, {})
<ide> end
<ide>
<ide> protected
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> module ActionDispatch
<ide> class Request < Rack::Request
<ide> def cookie_jar
<del> env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self, cookies)
<add> env['action_dispatch.cookies'.freeze] ||= Cookies::CookieJar.build(self, cookies)
<add> end
<add>
<add> # :stopdoc:
<add> def cookie_jar=(jar)
<add> env['action_dispatch.cookies'.freeze] = jar
<ide> end
<ide>
<ide> def key_generator
<ide> def cookies_serializer
<ide> def cookies_digest
<ide> env[Cookies::COOKIES_DIGEST]
<ide> end
<add> # :startdoc:
<ide> end
<ide>
<ide> # \Cookies are read and written through ActionController#cookies. | 2 |
Javascript | Javascript | check inspector support in test/inspector | 7dfeb36143a37b5f11766220a6408b9e6124a53b | <ide><path>test/inspector/test-inspector-port-zero-cluster.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>common.skipIfInspectorDisabled();
<ide> const assert = require('assert');
<ide> const cluster = require('cluster');
<ide>
<ide><path>test/inspector/test-inspector-port-zero.js
<ide> 'use strict';
<ide>
<del>const { mustCall } = require('../common');
<add>const { mustCall, skipIfInspectorDisabled } = require('../common');
<add>skipIfInspectorDisabled();
<ide> const assert = require('assert');
<ide> const { URL } = require('url');
<ide> const { spawn } = require('child_process'); | 2 |
Javascript | Javascript | add test for transition.tween | 1704957cb03c929ba1e4df00177d42fa3cde2a7c | <ide><path>test/core/transition-test-tween.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var assert = require("assert");
<add>
<add>module.exports = {
<add> topic: function() {
<add> var cb = this.callback,
<add> dd = [],
<add> ii = [],
<add> tt = [],
<add> fails = 0;
<add>
<add> var s = d3.select("body").append("div").selectAll("div")
<add> .data(["red", "green"])
<add> .enter().append("div")
<add> .text(function(d) { return d3.rgb(d)+""; });
<add>
<add> var t = s.transition()
<add> .tween("text", function() { ++fails; })
<add> .tween("text", tween);
<add>
<add> function tween(d, i) {
<add> dd.push(d);
<add> ii.push(i);
<add> if (tt.push(this) >= 2) cb(null, {
<add> selection: s,
<add> transition: t,
<add> data: dd,
<add> index: ii,
<add> context: tt,
<add> fails: fails
<add> });
<add> return i && function(t) {
<add> this.textContent = d3.hsl(230, 0.5, t) + "";
<add> };
<add> }
<add> },
<add>
<add> // The order here is a bit brittle: because the transition has zero delay,
<add> // it's invoking the start event immediately for all nodes, rather than
<add> // pushing each node onto the timer queue (which would reverse the order of
<add> // callbacks). The order in which tweens are invoked is undefined, so perhaps
<add> // we should sort the expected and actual values before comparing.
<add>
<add> "defines the corresponding tween": function(result) {
<add> assert.typeOf(result.transition.tween("text"), "function");
<add> },
<add> "the last tween takes precedence": function(result) {
<add> assert.equal(result.fails, 0);
<add> },
<add> "invokes the tween function": function(result) {
<add> assert.deepEqual(result.data, ["red", "green"], "expected data, got {actual}");
<add> assert.deepEqual(result.index, [0, 1], "expected data, got {actual}");
<add> assert.domEqual(result.context[0], result.selection[0][0], "expected this, got {actual}");
<add> assert.domEqual(result.context[1], result.selection[0][1], "expected this, got {actual}");
<add> },
<add>
<add> "end": {
<add> topic: function(result) {
<add> var cb = this.callback;
<add> result.transition.each("end", function(d, i) { if (i >= 1) cb(null, result); });
<add> },
<add> "uses the returned tweener": function(result) {
<add> assert.equal(result.selection[0][1].textContent, "hsl(230,50%,100%)");
<add> },
<add> "does nothing if the tweener is falsey": function(result) {
<add> assert.equal(result.selection[0][0].textContent, "#ff0000");
<add> }
<add> }
<add>};
<ide><path>test/core/transition-test.js
<ide> suite.addBatch({
<ide>
<ide> // Control
<ide> "each": require("./transition-test-each"),
<del> "call": require("./transition-test-call")
<del> // tween
<add> "call": require("./transition-test-call"),
<add> "tween": require("./transition-test-tween")
<ide>
<ide> });
<ide> | 2 |
Python | Python | set architecture in textcat example | 5063d999e5536c8aa96423781ec82cc7380c4051 | <ide><path>examples/training/train_textcat.py
<ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000):
<ide> # add the text classifier to the pipeline if it doesn't exist
<ide> # nlp.create_pipe works for built-ins that are registered with spaCy
<ide> if "textcat" not in nlp.pipe_names:
<del> textcat = nlp.create_pipe("textcat")
<add> textcat = nlp.create_pipe("textcat", config={
<add> "architecture": "simple_cnn",
<add> "exclusive_classes": True})
<ide> nlp.add_pipe(textcat, last=True)
<ide> # otherwise, get it, so we can add labels to it
<ide> else:
<ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000):
<ide> for i in range(n_iter):
<ide> losses = {}
<ide> # batch up the examples using spaCy's minibatch
<del> batches = minibatch(train_data, size=compounding(4.0, 16.0, 1.001))
<add> batches = minibatch(train_data, size=compounding(4.0, 32.0, 1.001))
<ide> for batch in batches:
<ide> texts, annotations = zip(*batch)
<ide> nlp.update(texts, annotations, sgd=optimizer, drop=0.2, losses=losses) | 1 |
Java | Java | fix toiterator exception handling | 11374c2653fa9aa2836a89f19d377ba25b198bbc | <ide><path>rxjava-core/src/main/java/rx/internal/operators/BlockingOperatorToIterator.java
<ide> public void onCompleted() {
<ide>
<ide> @Override
<ide> public void onError(Throwable e) {
<del> // ignore
<add> notifications.offer(Notification.<T>createOnError(e));
<ide> }
<ide>
<ide> @Override
<ide><path>rxjava-core/src/test/java/rx/internal/operators/BlockingOperatorToIteratorTest.java
<ide> public void call(Subscriber<? super String> observer) {
<ide> assertEquals(true, it.hasNext());
<ide> it.next();
<ide> }
<add>
<add> @Test(expected = TestException.class)
<add> public void testExceptionThrownFromOnSubscribe() {
<add> Iterable<String> strings = Observable.create(new Observable.OnSubscribe<String>() {
<add> @Override
<add> public void call(Subscriber<? super String> subscriber) {
<add> throw new TestException("intentional");
<add> }
<add> }).toBlocking().toIterable();
<add> for (String string : strings) {
<add> // never reaches here
<add> System.out.println(string);
<add> }
<add> }
<ide> } | 2 |
Text | Text | add instructions to run the examples | 6f70bb8c69cdbe1207e4909ccface32c8f51297b | <ide><path>README.md
<ide> When TensorFlow 2.0 and/or PyTorch has been installed, you can install from sour
<ide> pip install [--editable] .
<ide> ```
<ide>
<add>### Run the examples
<add>
<add>Examples are included in the repository but are not shipped with the library.
<add>Therefore, in order to run the examples you will first need to clone the
<add>repository and install the bleeding edge version of the library. To do so, create a new virtual environment and follow these steps:
<add>
<add>```bash
<add>git clone git@github.com:huggingface/transformers
<add>cd transformers
<add>pip install .
<add>```
<add>
<ide> ### Tests
<ide>
<ide> A series of tests are included for the library and the example scripts. Library tests can be found in the [tests folder](https://github.com/huggingface/transformers/tree/master/transformers/tests) and examples tests in the [examples folder](https://github.com/huggingface/transformers/tree/master/examples).
<ide> print("sentence_2 is", "a paraphrase" if pred_2 else "not a paraphrase", "of sen
<ide>
<ide> ## Quick tour of the fine-tuning/usage scripts
<ide>
<add>**Important**
<add>Before running the fine-tuning scripts, please read the
<add>[instructions](#run-the-examples) on how to
<add>setup your environment to run the examples.
<add>
<ide> The library comprises several example scripts with SOTA performances for NLU and NLG tasks:
<ide>
<ide> - `run_glue.py`: an example fine-tuning Bert, XLNet and XLM on nine different GLUE tasks (*sequence-level classification*) | 1 |
Javascript | Javascript | remove createreactclass from swipeablerow | 14e1628ba80e6ab918e3d7ac570fa4ec01d7de02 | <ide><path>Libraries/Experimental/SwipeableRow/SwipeableRow.js
<ide> const Animated = require('Animated');
<ide> const I18nManager = require('I18nManager');
<ide> const PanResponder = require('PanResponder');
<ide> const React = require('React');
<del>const PropTypes = require('prop-types');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide>
<del>const createReactClass = require('create-react-class');
<ide> const emptyFunction = require('fbjs/lib/emptyFunction');
<ide>
<ide> import type {LayoutEvent, PressEvent} from 'CoreEventTypes';
<ide> const RIGHT_SWIPE_BOUNCE_BACK_DURATION = 300;
<ide> * how far the finger swipes, and not the actual animation distance.
<ide> */
<ide> const RIGHT_SWIPE_THRESHOLD = 30 * SLOW_SPEED_SWIPE_FACTOR;
<add>const DEFAULT_SWIPE_THRESHOLD = 30;
<ide>
<ide> type Props = $ReadOnly<{|
<ide> children?: ?React.Node,
<ide> isOpen?: ?boolean,
<ide> maxSwipeDistance?: ?number,
<del> onClose?: ?Function,
<del> onOpen?: ?Function,
<del> onSwipeEnd?: ?Function,
<del> onSwipeStart?: ?Function,
<add> onClose?: ?() => void,
<add> onOpen?: ?() => void,
<add> onSwipeEnd?: ?() => void,
<add> onSwipeStart?: ?() => void,
<ide> preventSwipeRight?: ?boolean,
<ide> shouldBounceOnMount?: ?boolean,
<ide> slideoutView?: ?React.Node,
<ide> swipeThreshold?: ?number,
<ide> |}>;
<ide>
<add>type State = {
<add> currentLeft: Animated.Value,
<add> isSwipeableViewRendered: boolean,
<add> rowHeight: ?number,
<add>};
<add>
<ide> /**
<ide> * Creates a swipable row that allows taps on the main item and a custom View
<ide> * on the item hidden behind the row. Typically this should be used in
<ide> * conjunction with SwipeableListView for additional functionality, but can be
<ide> * used in a normal ListView. See the renderRow for SwipeableListView to see how
<ide> * to use this component separately.
<ide> */
<del>const SwipeableRow = createReactClass({
<del> displayName: 'SwipeableRow',
<del> _panResponder: {},
<del> _previousLeft: CLOSED_LEFT_POSITION,
<del> _timeoutID: (null: ?TimeoutID),
<del>
<del> propTypes: {
<del> children: PropTypes.any,
<del> isOpen: PropTypes.bool,
<del> preventSwipeRight: PropTypes.bool,
<del> maxSwipeDistance: PropTypes.number.isRequired,
<del> onOpen: PropTypes.func.isRequired,
<del> onClose: PropTypes.func.isRequired,
<del> onSwipeEnd: PropTypes.func.isRequired,
<del> onSwipeStart: PropTypes.func.isRequired,
<del> // Should bounce the row on mount
<del> shouldBounceOnMount: PropTypes.bool,
<del> /**
<del> * A ReactElement that is unveiled when the user swipes
<del> */
<del> slideoutView: PropTypes.node.isRequired,
<del> /**
<del> * The minimum swipe distance required before fully animating the swipe. If
<del> * the user swipes less than this distance, the item will return to its
<del> * previous (open/close) position.
<del> */
<del> swipeThreshold: PropTypes.number.isRequired,
<del> },
<add>class SwipeableRow extends React.Component<Props, State> {
<add> _handleMoveShouldSetPanResponderCapture = (
<add> event: PressEvent,
<add> gestureState: GestureState,
<add> ): boolean => {
<add> // Decides whether a swipe is responded to by this component or its child
<add> return gestureState.dy < 10 && this._isValidSwipe(gestureState);
<add> };
<ide>
<del> getInitialState(): Object {
<del> return {
<del> currentLeft: new Animated.Value(this._previousLeft),
<del> /**
<del> * In order to render component A beneath component B, A must be rendered
<del> * before B. However, this will cause "flickering", aka we see A briefly
<del> * then B. To counter this, _isSwipeableViewRendered flag is used to set
<del> * component A to be transparent until component B is loaded.
<del> */
<del> isSwipeableViewRendered: false,
<del> rowHeight: (null: ?number),
<del> };
<del> },
<add> _handlePanResponderGrant = (
<add> event: PressEvent,
<add> gestureState: GestureState,
<add> ): void => {};
<ide>
<del> getDefaultProps(): Object {
<del> return {
<del> isOpen: false,
<del> preventSwipeRight: false,
<del> maxSwipeDistance: 0,
<del> onOpen: emptyFunction,
<del> onClose: emptyFunction,
<del> onSwipeEnd: emptyFunction,
<del> onSwipeStart: emptyFunction,
<del> swipeThreshold: 30,
<del> };
<del> },
<add> _handlePanResponderMove = (
<add> event: PressEvent,
<add> gestureState: GestureState,
<add> ): void => {
<add> if (this._isSwipingExcessivelyRightFromClosedPosition(gestureState)) {
<add> return;
<add> }
<ide>
<del> UNSAFE_componentWillMount(): void {
<del> this._panResponder = PanResponder.create({
<del> onMoveShouldSetPanResponderCapture: this
<del> ._handleMoveShouldSetPanResponderCapture,
<del> onPanResponderGrant: this._handlePanResponderGrant,
<del> onPanResponderMove: this._handlePanResponderMove,
<del> onPanResponderRelease: this._handlePanResponderEnd,
<del> onPanResponderTerminationRequest: this._onPanResponderTerminationRequest,
<del> onPanResponderTerminate: this._handlePanResponderEnd,
<del> onShouldBlockNativeResponder: (event, gestureState) => false,
<del> });
<del> },
<add> this.props.onSwipeStart && this.props.onSwipeStart();
<add>
<add> if (this._isSwipingRightFromClosed(gestureState)) {
<add> this._swipeSlowSpeed(gestureState);
<add> } else {
<add> this._swipeFullSpeed(gestureState);
<add> }
<add> };
<add>
<add> _onPanResponderTerminationRequest = (
<add> event: PressEvent,
<add> gestureState: GestureState,
<add> ): boolean => {
<add> return false;
<add> };
<add>
<add> _handlePanResponderEnd = (
<add> event: PressEvent,
<add> gestureState: GestureState,
<add> ): void => {
<add> const horizontalDistance = IS_RTL ? -gestureState.dx : gestureState.dx;
<add> if (this._isSwipingRightFromClosed(gestureState)) {
<add> this.props.onOpen && this.props.onOpen();
<add> this._animateBounceBack(RIGHT_SWIPE_BOUNCE_BACK_DURATION);
<add> } else if (this._shouldAnimateRemainder(gestureState)) {
<add> if (horizontalDistance < 0) {
<add> // Swiped left
<add> this.props.onOpen && this.props.onOpen();
<add> this._animateToOpenPositionWith(gestureState.vx, horizontalDistance);
<add> } else {
<add> // Swiped right
<add> this.props.onClose && this.props.onClose();
<add> this._animateToClosedPosition();
<add> }
<add> } else {
<add> if (this._previousLeft === CLOSED_LEFT_POSITION) {
<add> this._animateToClosedPosition();
<add> } else {
<add> this._animateToOpenPosition();
<add> }
<add> }
<add>
<add> this.props.onSwipeEnd && this.props.onSwipeEnd();
<add> };
<add>
<add> _panResponder = PanResponder.create({
<add> onMoveShouldSetPanResponderCapture: this
<add> ._handleMoveShouldSetPanResponderCapture,
<add> onPanResponderGrant: this._handlePanResponderGrant,
<add> onPanResponderMove: this._handlePanResponderMove,
<add> onPanResponderRelease: this._handlePanResponderEnd,
<add> onPanResponderTerminationRequest: this._onPanResponderTerminationRequest,
<add> onPanResponderTerminate: this._handlePanResponderEnd,
<add> onShouldBlockNativeResponder: (event, gestureState) => false,
<add> });
<add>
<add> _previousLeft = CLOSED_LEFT_POSITION;
<add> _timeoutID: ?TimeoutID = null;
<add>
<add> state = {
<add> currentLeft: new Animated.Value(this._previousLeft),
<add> /**
<add> * In order to render component A beneath component B, A must be rendered
<add> * before B. However, this will cause "flickering", aka we see A briefly
<add> * then B. To counter this, _isSwipeableViewRendered flag is used to set
<add> * component A to be transparent until component B is loaded.
<add> */
<add> isSwipeableViewRendered: false,
<add> rowHeight: null,
<add> };
<ide>
<ide> componentDidMount(): void {
<ide> if (this.props.shouldBounceOnMount) {
<ide> const SwipeableRow = createReactClass({
<ide> this._animateBounceBack(ON_MOUNT_BOUNCE_DURATION);
<ide> }, ON_MOUNT_BOUNCE_DELAY);
<ide> }
<del> },
<add> }
<ide>
<del> UNSAFE_componentWillReceiveProps(nextProps: Object): void {
<add> UNSAFE_componentWillReceiveProps(nextProps: $Shape<Props>): void {
<ide> /**
<ide> * We do not need an "animateOpen(noCallback)" because this animation is
<ide> * handled internally by this component.
<ide> */
<del> if (this.props.isOpen && !nextProps.isOpen) {
<add> const isOpen = this.props.isOpen ?? false;
<add> const nextIsOpen = nextProps.isOpen ?? false;
<add>
<add> if (isOpen && !nextIsOpen) {
<ide> this._animateToClosedPosition();
<ide> }
<del> },
<add> }
<ide>
<ide> componentWillUnmount() {
<ide> if (this._timeoutID != null) {
<ide> clearTimeout(this._timeoutID);
<ide> }
<del> },
<add> }
<ide>
<ide> render(): React.Element<any> {
<ide> // The view hidden behind the main view
<ide> const SwipeableRow = createReactClass({
<ide> {swipeableView}
<ide> </View>
<ide> );
<del> },
<add> }
<ide>
<ide> close(): void {
<del> this.props.onClose();
<add> this.props.onClose && this.props.onClose();
<ide> this._animateToClosedPosition();
<del> },
<add> }
<ide>
<del> _onSwipeableViewLayout(event: LayoutEvent): void {
<add> _onSwipeableViewLayout = (event: LayoutEvent): void => {
<ide> this.setState({
<ide> isSwipeableViewRendered: true,
<ide> rowHeight: event.nativeEvent.layout.height,
<ide> });
<del> },
<del>
<del> _handleMoveShouldSetPanResponderCapture(
<del> event: PressEvent,
<del> gestureState: GestureState,
<del> ): boolean {
<del> // Decides whether a swipe is responded to by this component or its child
<del> return gestureState.dy < 10 && this._isValidSwipe(gestureState);
<del> },
<del>
<del> _handlePanResponderGrant(
<del> event: PressEvent,
<del> gestureState: GestureState,
<del> ): void {},
<del>
<del> _handlePanResponderMove(event: PressEvent, gestureState: GestureState): void {
<del> if (this._isSwipingExcessivelyRightFromClosedPosition(gestureState)) {
<del> return;
<del> }
<del>
<del> this.props.onSwipeStart();
<del>
<del> if (this._isSwipingRightFromClosed(gestureState)) {
<del> this._swipeSlowSpeed(gestureState);
<del> } else {
<del> this._swipeFullSpeed(gestureState);
<del> }
<del> },
<add> };
<ide>
<ide> _isSwipingRightFromClosed(gestureState: GestureState): boolean {
<ide> const gestureStateDx = IS_RTL ? -gestureState.dx : gestureState.dx;
<ide> return this._previousLeft === CLOSED_LEFT_POSITION && gestureStateDx > 0;
<del> },
<add> }
<ide>
<ide> _swipeFullSpeed(gestureState: GestureState): void {
<ide> this.state.currentLeft.setValue(this._previousLeft + gestureState.dx);
<del> },
<add> }
<ide>
<ide> _swipeSlowSpeed(gestureState: GestureState): void {
<ide> this.state.currentLeft.setValue(
<ide> this._previousLeft + gestureState.dx / SLOW_SPEED_SWIPE_FACTOR,
<ide> );
<del> },
<add> }
<ide>
<ide> _isSwipingExcessivelyRightFromClosedPosition(
<ide> gestureState: GestureState,
<ide> const SwipeableRow = createReactClass({
<ide> this._isSwipingRightFromClosed(gestureState) &&
<ide> gestureStateDx > RIGHT_SWIPE_THRESHOLD
<ide> );
<del> },
<del>
<del> _onPanResponderTerminationRequest(
<del> event: PressEvent,
<del> gestureState: GestureState,
<del> ): boolean {
<del> return false;
<del> },
<add> }
<ide>
<ide> _animateTo(
<ide> toValue: number,
<ide> const SwipeableRow = createReactClass({
<ide> this._previousLeft = toValue;
<ide> callback();
<ide> });
<del> },
<add> }
<ide>
<ide> _animateToOpenPosition(): void {
<del> const maxSwipeDistance = IS_RTL
<del> ? -this.props.maxSwipeDistance
<del> : this.props.maxSwipeDistance;
<del> this._animateTo(-maxSwipeDistance);
<del> },
<add> const maxSwipeDistance = this.props.maxSwipeDistance ?? 0;
<add> const directionAwareMaxSwipeDistance = IS_RTL
<add> ? -maxSwipeDistance
<add> : maxSwipeDistance;
<add> this._animateTo(-directionAwareMaxSwipeDistance);
<add> }
<ide>
<ide> _animateToOpenPositionWith(speed: number, distMoved: number): void {
<ide> /**
<ide> const SwipeableRow = createReactClass({
<ide> speed > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD
<ide> ? speed
<ide> : HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD;
<add> const maxSwipeDistance = this.props.maxSwipeDistance ?? 0;
<ide> /**
<ide> * Calculate the duration the row should take to swipe the remaining distance
<ide> * at the same speed the user swiped (or the speed threshold)
<ide> */
<del> const duration = Math.abs(
<del> (this.props.maxSwipeDistance - Math.abs(distMoved)) / speed,
<del> );
<del> const maxSwipeDistance = IS_RTL
<del> ? -this.props.maxSwipeDistance
<del> : this.props.maxSwipeDistance;
<del> this._animateTo(-maxSwipeDistance, duration);
<del> },
<add> const duration = Math.abs((maxSwipeDistance - Math.abs(distMoved)) / speed);
<add> const directionAwareMaxSwipeDistance = IS_RTL
<add> ? -maxSwipeDistance
<add> : maxSwipeDistance;
<add> this._animateTo(-directionAwareMaxSwipeDistance, duration);
<add> }
<ide>
<ide> _animateToClosedPosition(duration: number = SWIPE_DURATION): void {
<ide> this._animateTo(CLOSED_LEFT_POSITION, duration);
<del> },
<add> }
<ide>
<del> _animateToClosedPositionDuringBounce(): void {
<add> _animateToClosedPositionDuringBounce = (): void => {
<ide> this._animateToClosedPosition(RIGHT_SWIPE_BOUNCE_BACK_DURATION);
<del> },
<add> };
<ide>
<ide> _animateBounceBack(duration: number): void {
<ide> /**
<ide> const SwipeableRow = createReactClass({
<ide> duration,
<ide> this._animateToClosedPositionDuringBounce,
<ide> );
<del> },
<add> }
<ide>
<ide> // Ignore swipes due to user's finger moving slightly when tapping
<ide> _isValidSwipe(gestureState: GestureState): boolean {
<add> const preventSwipeRight = this.props.preventSwipeRight ?? false;
<ide> if (
<del> this.props.preventSwipeRight &&
<add> preventSwipeRight &&
<ide> this._previousLeft === CLOSED_LEFT_POSITION &&
<ide> gestureState.dx > 0
<ide> ) {
<ide> return false;
<ide> }
<ide>
<ide> return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD;
<del> },
<add> }
<ide>
<ide> _shouldAnimateRemainder(gestureState: GestureState): boolean {
<ide> /**
<ide> * If user has swiped past a certain distance, animate the rest of the way
<ide> * if they let go
<ide> */
<add> const swipeThreshold = this.props.swipeThreshold ?? DEFAULT_SWIPE_THRESHOLD;
<ide> return (
<del> Math.abs(gestureState.dx) > this.props.swipeThreshold ||
<add> Math.abs(gestureState.dx) > swipeThreshold ||
<ide> gestureState.vx > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD
<ide> );
<del> },
<del>
<del> _handlePanResponderEnd(event: PressEvent, gestureState: GestureState): void {
<del> const horizontalDistance = IS_RTL ? -gestureState.dx : gestureState.dx;
<del> if (this._isSwipingRightFromClosed(gestureState)) {
<del> this.props.onOpen();
<del> this._animateBounceBack(RIGHT_SWIPE_BOUNCE_BACK_DURATION);
<del> } else if (this._shouldAnimateRemainder(gestureState)) {
<del> if (horizontalDistance < 0) {
<del> // Swiped left
<del> this.props.onOpen();
<del> this._animateToOpenPositionWith(gestureState.vx, horizontalDistance);
<del> } else {
<del> // Swiped right
<del> this.props.onClose();
<del> this._animateToClosedPosition();
<del> }
<del> } else {
<del> if (this._previousLeft === CLOSED_LEFT_POSITION) {
<del> this._animateToClosedPosition();
<del> } else {
<del> this._animateToOpenPosition();
<del> }
<del> }
<del>
<del> this.props.onSwipeEnd();
<del> },
<del>});
<del>
<del>// TODO: Delete this when `SwipeableRow` uses class syntax.
<del>class TypedSwipeableRow extends React.Component<Props> {
<del> close() {}
<add> }
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<ide> const styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>module.exports = ((SwipeableRow: any): Class<TypedSwipeableRow>);
<add>module.exports = SwipeableRow; | 1 |
Ruby | Ruby | remove odd asignation | f74692788914a95794e823d2ec40815319447131 | <ide><path>actionpack/lib/action_view/asset_paths.rb
<ide> def compute_asset_host(source)
<ide> def relative_url_root
<ide> config = controller.config if controller.respond_to?(:config)
<ide> config ||= config.action_controller if config.action_controller.present?
<del> config ||= config
<ide> config.relative_url_root
<ide> end
<ide> | 1 |
Python | Python | remove print stament which some how ended up there | 4d7fd3f3c58fd4dd32512a9a72af471ab3a52b3a | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def list_sizes(self, location=None):
<ide> attributes = copy.deepcopy(attributes)
<ide> price = self._get_size_price(size_id=instance_type)
<ide> attributes.update({'price': price})
<del> print attributes
<ide> sizes.append(NodeSize(driver=self, **attributes))
<ide> return sizes
<ide> | 1 |
Javascript | Javascript | use https urls in jsonp example | 279f00b05b76e0aafe0774fe136c218b0c97418c | <ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<ide> <button id="samplejsonpbtn"
<ide> ng-click="updateModel('JSONP',
<del> 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
<add> 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
<ide> Sample JSONP
<ide> </button>
<ide> <button id="invalidjsonpbtn"
<del> ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
<add> ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
<ide> Invalid JSONP
<ide> </button>
<ide> <pre>http status code: {{status}}</pre> | 1 |
Ruby | Ruby | build fix for actionmailer | 5138a303e423312a8f68b1dc14cca0758dcff59e | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<add>require 'rack/session/abstract/id'
<ide> require 'action_controller/metal/exceptions'
<ide>
<ide> module ActionController #:nodoc: | 1 |
Javascript | Javascript | add better dev-only invariants | 0a5c5f093bdb12d6b7e2953e71f174623f9de979 | <ide><path>src/Container.js
<ide> import values from 'lodash/object/values';
<ide> import mapValues from 'lodash/object/mapValues';
<ide> import invariant from 'invariant';
<ide> import isPlainObject from 'lodash/lang/isPlainObject';
<add>import isFunction from 'lodash/lang/isFunction';
<ide>
<ide> export default class ReduxContainer extends Component {
<ide> static contextTypes = {
<ide> export default class ReduxContainer extends Component {
<ide>
<ide> static propTypes = {
<ide> children: PropTypes.func.isRequired,
<del> actions: PropTypes.object.isRequired,
<del> stores: PropTypes.object.isRequired
<add> actions: PropTypes.objectOf(
<add> PropTypes.func.isRequired
<add> ).isRequired,
<add> stores: PropTypes.objectOf(
<add> PropTypes.func.isRequired
<add> ).isRequired
<ide> }
<ide>
<ide> static defaultProps = {
<ide> export default class ReduxContainer extends Component {
<ide>
<ide> update(props) {
<ide> const { stores, actions } = props;
<del> invariant(
<del> isPlainObject(actions) &&
<del> Object.keys(actions).every(key => typeof actions[key] === 'function'),
<del> '"actions" must be a plain object with functions as values. Did you misspell an import?'
<del> );
<del> invariant(
<del> isPlainObject(stores) &&
<del> Object.keys(stores).every(key => typeof stores[key] === 'function'),
<del> '"stores" must be a plain object with functions as values. Did you misspell an import?'
<del> );
<add>
<add> if (process.env.NODE_ENV !== 'production') {
<add> invariant(
<add> isPlainObject(actions),
<add> '"actions" must be a plain object with functions as values. Instead received: %s.',
<add> actions
<add> );
<add> invariant(
<add> isPlainObject(stores),
<add> '"stores" must be a plain object with functions as values. Instead received: %s.',
<add> stores
<add> );
<add> Object.keys(actions).forEach(key =>
<add> invariant(
<add> isFunction(actions[key]),
<add> 'Expected "%s" in "actions" to be a function. Instead received: %s.',
<add> key,
<add> actions[key]
<add> )
<add> );
<add> Object.keys(stores).forEach(key =>
<add> invariant(
<add> isFunction(stores[key]),
<add> 'Expected "%s" in "stores" to be a function. Instead received: %s.',
<add> key,
<add> stores[key]
<add> )
<add> );
<add> }
<ide>
<ide> const { wrapActionCreator, observeStores } = this.context.redux;
<ide> this.actions = mapValues(props.actions, wrapActionCreator); | 1 |
PHP | PHP | add option for scoped cache locks | 28b8cb91251f0643f2aa61072c0554edeabce21b | <ide><path>src/Illuminate/Cache/Lock.php
<ide> abstract class Lock implements LockContract
<ide> */
<ide> protected $seconds;
<ide>
<add> /**
<add> * A (usually) random string that acts as scope identifier of this lock.
<add> *
<add> * @var string
<add> */
<add> protected $scope;
<add>
<ide> /**
<ide> * Create a new lock instance.
<ide> *
<ide> abstract public function acquire();
<ide> */
<ide> abstract public function release();
<ide>
<add> /**
<add> * Returns the value written into the driver for this lock.
<add> *
<add> * @return mixed
<add> */
<add> abstract protected function getValue();
<add>
<ide> /**
<ide> * Attempt to acquire the lock.
<ide> *
<ide> public function block($seconds, $callback = null)
<ide>
<ide> return true;
<ide> }
<add>
<add> /**
<add> * Secures this lock against out of order releases of expired clients.
<add> *
<add> * @return Lock
<add> */
<add> public function safe()
<add> {
<add> return $this->scoped(uniqid());
<add> }
<add>
<add> /**
<add> * Secures this lock against out of order releases of expired clients.
<add> *
<add> * @param string $scope
<add> * @return Lock
<add> */
<add> public function scoped($scope)
<add> {
<add> $this->scope = $scope;
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Determines whether this is a client scoped lock.
<add> *
<add> * @return bool
<add> */
<add> protected function isScoped()
<add> {
<add> return ! is_null($this->scope);
<add> }
<add>
<add> /**
<add> * Returns the value that should be written into the cache.
<add> *
<add> * @return mixed
<add> */
<add> protected function value()
<add> {
<add> return $this->isScoped() ? serialize($this->scope) : 1;
<add> }
<add>
<add> /**
<add> * Determines whether this lock is allowed to release the lock in the driver.
<add> *
<add> * @return bool
<add> */
<add> protected function canRelease()
<add> {
<add> if (! $this->isScoped()) {
<add> return true;
<add> }
<add>
<add> return unserialize($this->getValue()) === $this->scope;
<add> }
<ide> }
<ide><path>src/Illuminate/Cache/MemcachedLock.php
<ide> public function __construct($memcached, $name, $seconds)
<ide> public function acquire()
<ide> {
<ide> return $this->memcached->add(
<del> $this->name, 1, $this->seconds
<add> $this->name, $this->value(), $this->seconds
<ide> );
<ide> }
<ide>
<ide> public function acquire()
<ide> */
<ide> public function release()
<ide> {
<del> $this->memcached->delete($this->name);
<add> if ($this->canRelease()) {
<add> $this->memcached->delete($this->name);
<add> }
<add> }
<add>
<add> /**
<add> * Returns the value written into the driver for this lock.
<add> *
<add> * @return mixed
<add> */
<add> protected function getValue()
<add> {
<add> return $this->memcached->get($this->name);
<ide> }
<ide> }
<ide><path>src/Illuminate/Cache/RedisLock.php
<ide> public function __construct($redis, $name, $seconds)
<ide> */
<ide> public function acquire()
<ide> {
<del> $result = $this->redis->setnx($this->name, 1);
<add> $result = $this->redis->setnx($this->name, $this->value());
<ide>
<ide> if ($result === 1 && $this->seconds > 0) {
<ide> $this->redis->expire($this->name, $this->seconds);
<ide> public function acquire()
<ide> */
<ide> public function release()
<ide> {
<del> $this->redis->del($this->name);
<add> if ($this->canRelease()) {
<add> $this->redis->del($this->name);
<add> }
<add> }
<add>
<add> /**
<add> * Returns the value written into the driver for this lock.
<add> *
<add> * @return string
<add> */
<add> protected function getValue()
<add> {
<add> return $this->redis->get($this->name);
<ide> }
<ide> }
<ide><path>src/Illuminate/Contracts/Cache/Lock.php
<ide> public function block($seconds, $callback = null);
<ide> * @return void
<ide> */
<ide> public function release();
<add>
<add> /**
<add> * Secures this lock against out of order releases of expired clients.
<add> *
<add> * @return mixed
<add> */
<add> public function safe();
<ide> }
<ide><path>tests/Integration/Cache/MemcachedCacheLockTest.php
<ide> public function test_locks_throw_timeout_if_block_expires()
<ide> return 'taylor';
<ide> }));
<ide> }
<add>
<add> public function test_memcached_locks_are_released_safely()
<add> {
<add> Cache::store('memcached')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('memcached')->lock('bar', 1)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add> sleep(2);
<add>
<add> $secondLock = Cache::store('memcached')->lock('bar', 10)->safe();
<add> $this->assertTrue($secondLock->acquire());
<add>
<add> $firstLock->release();
<add>
<add> $this->assertTrue(Cache::store('memcached')->has('bar'));
<add> }
<add>
<add> public function test_safe_memcached_locks_are_exclusive()
<add> {
<add> Cache::store('memcached')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('memcached')->lock('bar', 10)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add>
<add> $secondLock = Cache::store('memcached')->lock('bar', 10)->safe();
<add> $this->assertFalse($secondLock->acquire());
<add> }
<add>
<add> public function test_safe_memcached_locks_can_be_released_by_original_owner()
<add> {
<add> Cache::store('memcached')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('memcached')->lock('bar', 10)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add>
<add> $secondLock = Cache::store('memcached')->lock('bar', 10)->safe();
<add> $this->assertFalse($secondLock->acquire());
<add>
<add> $firstLock->release();
<add> $this->assertFalse(Cache::store('memcached')->has('bar'));
<add> }
<ide> }
<ide><path>tests/Integration/Cache/RedisCacheLockTest.php
<ide> public function test_redis_locks_can_block_for_seconds()
<ide> Cache::store('redis')->lock('foo')->release();
<ide> $this->assertTrue(Cache::store('redis')->lock('foo', 10)->block(1));
<ide> }
<add>
<add> public function test_redis_locks_are_released_safely()
<add> {
<add> Cache::store('redis')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('redis')->lock('bar', 1)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add> sleep(2);
<add>
<add> $secondLock = Cache::store('redis')->lock('bar', 10)->safe();
<add> $this->assertTrue($secondLock->acquire());
<add>
<add> $firstLock->release();
<add>
<add> $this->assertTrue(Cache::store('redis')->has('bar'));
<add> }
<add>
<add> public function test_safe_redis_locks_are_exclusive()
<add> {
<add> Cache::store('redis')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('redis')->lock('bar', 10)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add>
<add> $secondLock = Cache::store('redis')->lock('bar', 10)->safe();
<add> $this->assertFalse($secondLock->acquire());
<add> }
<add>
<add> public function test_safe_redis_locks_can_be_released_by_original_owner()
<add> {
<add> Cache::store('redis')->lock('bar')->release();
<add>
<add> $firstLock = Cache::store('redis')->lock('bar', 10)->safe();
<add> $this->assertTrue($firstLock->acquire());
<add>
<add> $secondLock = Cache::store('redis')->lock('bar', 10)->safe();
<add> $this->assertFalse($secondLock->acquire());
<add>
<add> $firstLock->release();
<add> $this->assertFalse(Cache::store('redis')->has('bar'));
<add> }
<ide> } | 6 |
Mixed | Javascript | fix ssr cache example (#510) | 355dbf8fdd1812d75ee6b9f0e360f403cb5802ec | <ide><path>examples/ssr-caching/README.md
<ide> Install it and run:
<ide>
<ide> ```bash
<ide> npm install
<del>npm run dev
<add>npm start
<ide> ```
<ide>
<ide> Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
<ide><path>examples/ssr-caching/server.js
<ide> app.prepare()
<ide> })
<ide>
<ide> server.get('/blog/:id', (req, res) => {
<del> const queryParams = { id: req.paradms.id }
<add> const queryParams = { id: req.params.id }
<ide> renderAndCache(req, res, '/blog', queryParams)
<ide> })
<ide> | 2 |
PHP | PHP | check _serialize keys before using them | aed215fb508bdcbc6bdcfb6f2b730e6b73fac74b | <ide><path>src/View/XmlView.php
<ide> protected function _serialize($serialize)
<ide> if (is_numeric($alias)) {
<ide> $alias = $key;
<ide> }
<del> $data[$rootNode][$alias] = $this->viewVars[$key];
<add> if (array_key_exists($key, $this->viewVars)) {
<add> $data[$rootNode][$alias] = $this->viewVars[$key];
<add> }
<ide> }
<ide> } else {
<ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; | 1 |
Python | Python | add kannada, tamil, and telugu unicode blocks | bee79619278a5e055ac744798a6ea0001951c94b | <ide><path>spacy/lang/char_classes.py
<ide>
<ide> _hindi = r"\u0900-\u097F"
<ide>
<add>_kannada = r"\u0C80-\u0CFF"
<add>
<add>_tamil = r"\u0B80-\u0BFF"
<add>
<add>_telugu = r"\u0C00-\u0C7F"
<add>
<ide> # Latin standard
<ide> _latin_u_standard = r"A-Z"
<ide> _latin_l_standard = r"a-z"
<ide> _upper = LATIN_UPPER + _russian_upper + _tatar_upper + _greek_upper + _ukrainian_upper
<ide> _lower = LATIN_LOWER + _russian_lower + _tatar_lower + _greek_lower + _ukrainian_lower
<ide>
<del>_uncased = _bengali + _hebrew + _persian + _sinhala + _hindi
<add>_uncased = _bengali + _hebrew + _persian + _sinhala + _hindi + _kannada + _tamil + _telugu
<ide>
<ide> ALPHA = group_chars(LATIN + _russian + _tatar + _greek + _ukrainian + _uncased)
<ide> ALPHA_LOWER = group_chars(_lower + _uncased) | 1 |
Python | Python | fix sequence timeout deadlock | cf9595ae20be49917f2a19b24467e822ac878269 | <ide><path>keras/utils/data_utils.py
<ide> def get(self):
<ide> try:
<ide> future = self.queue.get(block=True)
<ide> inputs = future.get(timeout=30)
<del> self.queue.task_done()
<ide> except mp.TimeoutError:
<ide> idx = future.idx
<ide> warnings.warn(
<ide> 'The input {} could not be retrieved.'
<ide> ' It could be because a worker has died.'.format(idx),
<ide> UserWarning)
<ide> inputs = self.sequence[idx]
<add> finally:
<add> self.queue.task_done()
<add>
<ide> if inputs is not None:
<ide> yield inputs
<ide> except Exception:
<ide><path>tests/keras/utils/data_utils_test.py
<ide> import sys
<ide> import tarfile
<ide> import threading
<add>import signal
<ide> import shutil
<ide> import zipfile
<ide> from itertools import cycle
<ide> def on_epoch_end(self):
<ide> pass
<ide>
<ide>
<add>class SlowSequence(Sequence):
<add> def __init__(self, shape, value=1.0):
<add> self.shape = shape
<add> self.inner = value
<add> self.wait = True
<add>
<add> def __getitem__(self, item):
<add> if self.wait:
<add> self.wait = False
<add> time.sleep(40)
<add> return np.ones(self.shape, dtype=np.uint32) * item * self.inner
<add>
<add> def __len__(self):
<add> return 10
<add>
<add> def on_epoch_end(self):
<add> pass
<add>
<add>
<ide> @threadsafe_generator
<ide> def create_generator_from_sequence_threads(ds):
<ide> for i in cycle(range(len(ds))):
<ide> def test_ordered_enqueuer_fail_threads():
<ide> next(gen_output)
<ide>
<ide>
<add>def test_ordered_enqueuer_timeout_threads():
<add> enqueuer = OrderedEnqueuer(SlowSequence([3, 10, 10, 3]),
<add> use_multiprocessing=False)
<add>
<add> def handler(signum, frame):
<add> raise TimeoutError('Sequence deadlocked')
<add>
<add> old = signal.signal(signal.SIGALRM, handler)
<add> signal.setitimer(signal.ITIMER_REAL, 60)
<add> with pytest.warns(UserWarning) as record:
<add> enqueuer.start(5, 10)
<add> gen_output = enqueuer.get()
<add> for epoch_num in range(2):
<add> acc = []
<add> for i in range(10):
<add> acc.append(next(gen_output)[0, 0, 0, 0])
<add> assert acc == list(range(10)), 'Order was not keep in ' \
<add> 'OrderedEnqueuer with threads'
<add> enqueuer.stop()
<add> assert len(record) == 1
<add> assert str(record[0].message) == 'The input 0 could not be retrieved. ' \
<add> 'It could be because a worker has died.'
<add> signal.setitimer(signal.ITIMER_REAL, 0)
<add> signal.signal(signal.SIGALRM, old)
<add>
<add>
<ide> @use_spawn
<ide> def test_on_epoch_end_processes():
<ide> enqueuer = OrderedEnqueuer(DummySequence([3, 10, 10, 3]), | 2 |
Text | Text | add documentation for working on engine api | 109c54c481c7dafe88b622b87c0c7c172fed5ea1 | <ide><path>api/README.md
<del>This directory contains code pertaining to the Docker API:
<add># Working on the Engine API
<ide>
<del> - Used by the docker client when communicating with the docker daemon
<add>The Engine API is an HTTP API used by the command-line client to communicate with the daemon. It can also be used by third-party software to control the daemon.
<ide>
<del> - Used by third party tools wishing to interface with the docker daemon
<add>It consists of various components in this repository:
<add>
<add>- `api/swagger.yaml` A Swagger definition of the API.
<add>- `api/types/` Types shared by both the client and server, representing various objects, options, responses, etc. Most are written manually, but some are automatically generated from the Swagger definition. See [#27919](https://github.com/docker/docker/issues/27919) for progress on this.
<add>- `cli/` The command-line client.
<add>- `client/` The Go client used by the command-line client. It can also be used by third-party Go programs.
<add>- `daemon/` The daemon, which serves the API.
<add>
<add>## Swagger definition
<add>
<add>The API is defined by the [Swagger](http://swagger.io/specification/) definition in `api/swagger.yaml`. This definition can be used to:
<add>
<add>1. To automatically generate documentation.
<add>2. To automatically generate the Go server and client. (A work-in-progress.)
<add>3. Provide a machine readable version of the API for introspecting what it can do, automatically generating clients for other languages, etc.
<add>
<add>## Updating the API documentation
<add>
<add>The API documentation is generated entirely from `api/swagger.yaml`. If you make updates to the API, you'll need to edit this file to represent the change in the documentation.
<add>
<add>The file is split into two main sections:
<add>
<add>- `definitions`, which defines re-usable objects used in requests and responses
<add>- `paths`, which defines the API endpoints (and some inline objects which don't need to be reusable)
<add>
<add>To make an edit, first look for the endpoint you want to edit under `paths`, then make the required edits. Endpoints may reference reusable objects with `$ref`, which can be found in the `definitions` section.
<add>
<add>There is hopefully enough example material in the file for you to copy a similar pattern from elsewhere in the file (e.g. adding new fields or endpoints), but for the full reference, see the [Swagger specification](https://github.com/docker/docker/issues/27919)
<add>
<add>`swagger.yaml` is validated by `hack/validate/swagger` to ensure it is a valid Swagger definition. This is useful for when you are making edits to ensure you are doing the right thing.
<add>
<add>## Viewing the API documentation
<add>
<add>When you make edits to `swagger.yaml`, you may want to check the generated API documentation to ensure it renders correctly.
<add>
<add>All the documentation generation is done in the documentation repository, [docker/docker.github.io](https://github.com/docker/docker.github.io). The Swagger definition is vendored periodically into this repository, but you can manually copy over the Swagger definition to test changes.
<add>
<add>Copy `api/swagger.yaml` in this repository to `engine/api/[VERSION_NUMBER]/swagger.yaml` in the documentation repository, overwriting what is already there. Then, run `docker-compose up` in the documentation repository and browse to [http://localhost:4000/engine/api/](http://localhost:4000/engine/api/) when it finishes rendering. | 1 |
Python | Python | fix sundry errors | 527937eb3df319c23a9ccfe26558739acec14e8c | <ide><path>numpy/core/fromnumeric.py
<ide> def sum(x, axis=None, dtype=None, out=None):
<ide> if out is not None:
<ide> out[...] = res
<ide> return out
<add> return res
<ide> try:
<ide> sum = x.sum
<ide> except AttributeError:
<ide><path>numpy/core/numeric.py
<ide> def alterdot():
<ide> def restoredot():
<ide> pass
<ide>
<del>def tensordot(a, b, axes=(-1,0))
<add>def tensordot(a, b, axes=(-1,0)):
<ide> """tensordot returns the product for any (ndim >= 1) arrays.
<ide>
<ide> r_{xxx, yyy} = \sum_k a_{xxx,k} b_{k,yyy} where
<ide> def tensordot(a, b, axes=(-1,0))
<ide> if not equal:
<ide> raise ValueError, "shape-mismatch for sum"
<ide>
<del> olda = [ for k in aa if k not in axes_a]
<add> olda = [k for k in aa if k not in axes_a]
<ide> oldb = [k for k in bs if k not in axes_b]
<ide>
<ide> at = a.reshape(nd1, nd2)
<ide><path>numpy/lib/function_base.py
<del>u__all__ = ['logspace', 'linspace',
<add>__all__ = ['logspace', 'linspace',
<ide> 'select', 'piecewise', 'trim_zeros',
<ide> 'copy', 'iterable', #'base_repr', 'binary_repr',
<ide> 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', | 3 |
Python | Python | increase test coverage | a11bf06aa756f43f740f5c51b8ffbf722ad8c1ad | <ide><path>tests/test_model_saving.py
<ide> def test_saving_model_with_long_weights_names():
<ide> f = x
<ide> for i in range(4):
<ide> f = Dense(2, name='nested_model_dense_%d' % (i,))(f)
<add> f = Dense(2, name='nested_model_dense_4', trainable=False)(f)
<ide> # This layer name will make the `weights_name`
<ide> # HDF5 attribute blow out of proportion.
<ide> f = Dense(2, name='nested_model_output' + ('x' * (2**15)))(f) | 1 |
Python | Python | handle kombu serialization errors as task errors | bbd1e4b28c8739053b45204890bad4959bf8e19f | <ide><path>celery/app/trace.py
<ide>
<ide> from billiard.einfo import ExceptionInfo
<ide> from kombu.utils import kwdict
<add>from kombu.exceptions import SerializationError
<ide>
<ide> from celery import current_app
<ide> from celery import states, signals
<ide> def trace_task(uuid, args, kwargs, request=None):
<ide> except BaseException as exc:
<ide> raise
<ide> else:
<del> # callback tasks must be applied before the result is
<del> # stored, so that result.children is populated.
<del> [signature(callback, app=app).apply_async((retval, ))
<del> for callback in task_request.callbacks or []]
<del> if publish_result:
<del> store_result(
<del> uuid, retval, SUCCESS, request=task_request,
<del> )
<del> if task_on_success:
<del> task_on_success(retval, uuid, args, kwargs)
<del> if success_receivers:
<del> send_success(sender=task, result=retval)
<add> try:
<add> # callback tasks must be applied before the result is
<add> # stored, so that result.children is populated.
<add> [signature(callback, app=app).apply_async((retval, ))
<add> for callback in task_request.callbacks or []]
<add> if publish_result:
<add> store_result(
<add> uuid, retval, SUCCESS, request=task_request,
<add> )
<add> except SerializationError as exc:
<add> if propagate:
<add> raise
<add> I = Info(FAILURE, exc)
<add> state, retval = I.state, I.retval
<add> R = I.handle_error_state(task, eager=eager)
<add> [signature(errback, app=app).apply_async((uuid, ))
<add> for errback in task_request.errbacks or []]
<add> else:
<add> if task_on_success:
<add> task_on_success(retval, uuid, args, kwargs)
<add> if success_receivers:
<add> send_success(sender=task, result=retval)
<ide>
<ide> # -* POST *-
<ide> if state not in IGNORE_STATES: | 1 |
PHP | PHP | remove unneeded line | 0c0654394c277576f20a8b45f5077f6800b47237 | <ide><path>src/Illuminate/Auth/Console/MakeAuthCommand.php
<ide> public function fire()
<ide>
<ide> file_put_contents(
<ide> app_path('Http/Controllers/HomeController.php'),
<del> $this->compileControllerStub(),
<del> FILE_TEXT
<add> $this->compileControllerStub()
<ide> );
<ide>
<ide> $this->info('Updated Routes File.'); | 1 |
Text | Text | update swc failed error with link to discussion | 00c53d632ce84af8727c030181570ae7bbd6f66b | <ide><path>errors/failed-loading-swc.md
<ide> If SWC continues to fail to load you can opt-out by disabling `swcMinify` in you
<ide> }
<ide> ```
<ide>
<del>Be sure to report the issue on [the feedback thread](https://github.com/vercel/next.js/discussions/30174) sharing the below information so we can get it fixed:
<del>
<del>- your node architecture and platform `node -e 'console.log(process.arch, process.platform)'`
<del>- your operating system version and CPU
<del>- your Next.js version `yarn next --version`
<del>- your package manager (`yarn` or `npm`) and version
<del>- your node.js version `node -v`
<del>- whether `@next/swc-<your-system-version>` was downloaded in `node_modules` correctly
<add>Be sure to report the issue on [the feedback thread](https://github.com/vercel/next.js/discussions/30468) so that we can investigate it further.
<ide>
<ide> ### Useful Links
<ide>
<del>- [SWC Feedback Thread](https://github.com/vercel/next.js/discussions/30174)
<add>- [SWC Feedback Thread](https://github.com/vercel/next.js/discussions/30468)
<ide> - [SWC Disabled Document](https://nextjs.org/docs/messages/swc-disabled) | 1 |
Javascript | Javascript | modify test messages to template literals | f96745a4d31111788700dd276baed2b966c6f090 | <ide><path>test/parallel/test-cli-syntax.js
<ide> const notFoundRE = /^Error: Cannot find module/m;
<ide> const cmd = [node, ..._args].join(' ');
<ide> exec(cmd, common.mustCall((err, stdout, stderr) => {
<ide> assert.ifError(err);
<del> assert.strictEqual(stdout, '', 'stdout produced');
<del> assert.strictEqual(stderr, '', 'stderr produced');
<add> assert.strictEqual(stdout, '');
<add> assert.strictEqual(stderr, '');
<ide> }));
<ide> });
<ide> });
<ide> const notFoundRE = /^Error: Cannot find module/m;
<ide> const cmd = [node, ..._args].join(' ');
<ide> exec(cmd, common.mustCall((err, stdout, stderr) => {
<ide> assert.strictEqual(err instanceof Error, true);
<del> assert.strictEqual(err.code, 1, `code === ${err.code}`);
<add> assert.strictEqual(err.code, 1);
<ide>
<ide> // no stdout should be produced
<del> assert.strictEqual(stdout, '', 'stdout produced');
<add> assert.strictEqual(stdout, '');
<ide>
<ide> // stderr should have a syntax error message
<del> assert(syntaxErrorRE.test(stderr), 'stderr incorrect');
<add> assert(syntaxErrorRE.test(stderr), `${syntaxErrorRE} === ${stderr}`);
<ide>
<ide> // stderr should include the filename
<del> assert(stderr.startsWith(file), "stderr doesn't start with the filename");
<add> assert(stderr.startsWith(file), `${stderr} starts with ${file}`);
<ide> }));
<ide> });
<ide> });
<ide> const notFoundRE = /^Error: Cannot find module/m;
<ide> const cmd = [node, ..._args].join(' ');
<ide> exec(cmd, common.mustCall((err, stdout, stderr) => {
<ide> // no stdout should be produced
<del> assert.strictEqual(stdout, '', 'stdout produced');
<add> assert.strictEqual(stdout, '');
<ide>
<ide> // stderr should have a module not found error message
<del> assert(notFoundRE.test(stderr), 'stderr incorrect');
<add> assert(notFoundRE.test(stderr), `${notFoundRE} === ${stderr}`);
<ide>
<del> assert.strictEqual(err.code, 1, `code === ${err.code}`);
<add> assert.strictEqual(err.code, 1);
<ide> }));
<ide> });
<ide> });
<ide> syntaxArgs.forEach(function(args) {
<ide> const c = spawnSync(node, args, { encoding: 'utf8', input: stdin });
<ide>
<ide> // no stdout or stderr should be produced
<del> assert.strictEqual(c.stdout, '', 'stdout produced');
<del> assert.strictEqual(c.stderr, '', 'stderr produced');
<add> assert.strictEqual(c.stdout, '');
<add> assert.strictEqual(c.stderr, '');
<ide>
<del> assert.strictEqual(c.status, 0, `code === ${c.status}`);
<add> assert.strictEqual(c.status, 0);
<ide> });
<ide>
<ide> // should throw if code piped from stdin with --check has bad syntax
<ide> syntaxArgs.forEach(function(args) {
<ide> const c = spawnSync(node, args, { encoding: 'utf8', input: stdin });
<ide>
<ide> // stderr should include '[stdin]' as the filename
<del> assert(c.stderr.startsWith('[stdin]'), "stderr doesn't start with [stdin]");
<add> assert(c.stderr.startsWith('[stdin]'), `${c.stderr} starts with ${stdin}`);
<ide>
<ide> // no stdout or stderr should be produced
<del> assert.strictEqual(c.stdout, '', 'stdout produced');
<add> assert.strictEqual(c.stdout, '');
<ide>
<ide> // stderr should have a syntax error message
<del> assert(syntaxErrorRE.test(c.stderr), 'stderr incorrect');
<add> assert(syntaxErrorRE.test(c.stderr), `${syntaxErrorRE} === ${c.stderr}`);
<ide>
<del> assert.strictEqual(c.status, 1, `code === ${c.status}`);
<add> assert.strictEqual(c.status, 1);
<ide> });
<ide>
<ide> // should throw if -c and -e flags are both passed
<ide> syntaxArgs.forEach(function(args) {
<ide> const cmd = [node, ...args].join(' ');
<ide> exec(cmd, common.mustCall((err, stdout, stderr) => {
<ide> assert.strictEqual(err instanceof Error, true);
<del> assert.strictEqual(err.code, 9, `code === ${err.code}`);
<add> assert.strictEqual(err.code, 9);
<ide> assert(
<ide> stderr.startsWith(
<ide> `${node}: either --check or --eval can be used, not both` | 1 |
Python | Python | remove duplicated code between sort and argsort | 821293d73fb6f62a9304c744a6144b43a853ba81 | <ide><path>numpy/ma/core.py
<ide> def sort(self, axis=-1, kind='quicksort', order=None,
<ide> if self is masked:
<ide> return
<ide>
<del> if fill_value is None:
<del> if endwith:
<del> # nan > inf
<del> if np.issubdtype(self.dtype, np.floating):
<del> filler = np.nan
<del> else:
<del> filler = minimum_fill_value(self)
<del> else:
<del> filler = maximum_fill_value(self)
<del> else:
<del> filler = fill_value
<add> sidx = self.argsort(axis=axis, kind=kind, order=order,
<add> fill_value=fill_value, endwith=endwith)
<ide>
<del> sidx = self.filled(filler).argsort(axis=axis, kind=kind,
<del> order=order)
<ide> # save meshgrid memory for 1d arrays
<ide> if self.ndim == 1:
<ide> idx = sidx | 1 |
Ruby | Ruby | remove unused code | 2eed9286ce3af77d29bdd20b4c2a5fa93baf03b1 | <ide><path>activesupport/test/core_ext/module_test.rb
<ide> class Cd
<ide> end
<ide> end
<ide>
<del>class De
<del>end
<del>
<ide> Somewhere = Struct.new(:street, :city)
<ide>
<ide> Someone = Struct.new(:name, :place) do | 1 |
Text | Text | add the text "de forma a validar" to article | 03c55d309bcec2279476631ece4695853f71d4f2 | <ide><path>guide/portuguese/machine-learning/deep-learning/index.md
<ide> Para os não iniciados, um neurônio artificial é basicamente uma função mate
<ide>
<ide> ### Por que isso é um grande negócio?
<ide>
<del>Chegando com o conjunto de regras manualmente para algumas das tarefas pode ser muito complicado (embora teoricamente possível). Por exemplo, se você tentar escrever um conjunto manual de regras para classificar uma imagem (basicamente um monte de valores de pixel) de se ela pertence a um gato ou cachorro, você verá por que é complicado. Acrescente a isso o fato de que cães e gatos vêm em uma variedade de formas, tamanhos e cores, e, para não mencionar, as imagens podem ter origens diferentes. Você pode entender rapidamente porque codificar um problema tão simples pode ser problemático.
<add>Chegando com o conjunto de regras manualmente para algumas das tarefas pode ser muito complicado (embora teoricamente possível). Por exemplo, se você tentar escrever um conjunto manual de regras para classificar uma imagem (basicamente um monte de valores de pixel) de forma a validar se ela pertence a um gato ou cachorro, você verá por que essa é uma tarefa complicada. Acrescente isso ao fato de que cães e gatos vêm em uma variedade de formas, tamanhos e cores e, para não mencionar, as imagens podem ter origens diferentes. Você pode entender rapidamente porque codificar um problema tão simples pode ser problemático.
<ide>
<del>Deep Learning ajuda a resolver este problema de descobrir o conjunto de regras que podem classificar uma imagem como a de um gato ou um cachorro, automaticamente! Tudo o que é preciso é um monte de imagens que já estão corretamente classificadas como de um gato ou de um cachorro e que poderão aprender o conjunto de regras necessário. Magia!
<add>Deep Learning ajuda a resolver o problema de descobrir o conjunto de regras que podem classificar uma imagem como a de um gato ou um cachorro, automaticamente! Tudo o que é preciso é um monte de imagens que já estão corretamente classificadas como de um gato ou de um cachorro e que poderão aprender o conjunto de regras necessário. Magia!
<ide>
<ide> Acontece que há muitos problemas por aí que não são relacionados à imagem (como o reconhecimento de voz), em que encontrar o conjunto de regras é muito complicado. Deep Learning pode ajudar com isso desde que haja muitos dados rotulados já presentes.
<ide>
<ide> Atualmente, há uma variedade de estruturas de aprendizagem profunda que permite
<ide> * [Imagenet](http://image-net.org/)
<ide> * [Um Guia para Principiantes do Entendimento de Redes Neurais Convolucionais](https://adeshpande3.github.io/adeshpande3.github.io/A-Beginner's-Guide-To-Understanding-Convolutional-Neural-Networks/)
<ide> * [Aprendizado Profundo SIMPLIFICADO - DeepLearning.TV](https://www.youtube.com/playlist?list=PLjJh1vlSEYgvGod9wWiydumYl8hOXixNu)
<del>* [Redes Neurais e Aprendizagem Profunda](http://neuralnetworksanddeeplearning.com)
<ide>\ No newline at end of file
<add>* [Redes Neurais e Aprendizagem Profunda](http://neuralnetworksanddeeplearning.com) | 1 |
PHP | PHP | add a new interfact for redis connections | 9e2017064df6e7681140065ca484bb3a469b67c3 | <ide><path>src/Illuminate/Contracts/Redis/Connections/Connection.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Redis\Connections;
<add>
<add>use Closure;
<add>
<add>interface Connection
<add>{
<add> /**
<add> * Subscribe to a set of given channels for messages.
<add> *
<add> * @param array|string $channels
<add> * @param \Closure $callback
<add> * @return void
<add> */
<add> public function subscribe($channels, Closure $callback);
<add>
<add> /**
<add> * Subscribe to a set of given channels with wildcards.
<add> *
<add> * @param array|string $channels
<add> * @param \Closure $callback
<add> * @return void
<add> */
<add> public function psubscribe($channels, Closure $callback);
<add>
<add> /**
<add> * Run a command against the Redis database.
<add> *
<add> * @param string $method
<add> * @param array $parameters
<add> * @return mixed
<add> */
<add> public function command($method, array $parameters = []);
<add>}
<ide>\ No newline at end of file | 1 |
Python | Python | use jinja2 templating for non owner email notif; | 940e09bcf54aa291153f84ecf389e761a43003d7 | <ide><path>airflow/www/utils.py
<ide> import os
<ide> from flask import after_this_request, request, Response
<ide> from flask.ext.login import current_user
<add>from jinja2 import Template
<ide> import wtforms
<ide> from wtforms.compat import text_type
<ide>
<ide> def wrapper(*args, **kwargs):
<ide> subject = (
<ide> 'Actions taken on DAG {0} by {1}'.format(
<ide> dag_id, user))
<del> html = 'action: <i>{0}</i><br><br>'.format(f.__name__)
<del> html += '<b>Parameters</b>:<br><table>'
<del> for k, v in request.args.items():
<del> if k != 'origin':
<del> html += '<tr><td>{0}</td><td>{1}</td></tr>'.format(k, v)
<del> html += '</table>'
<del> utils.send_email(task.email, subject, html)
<add> items = request.args.items()
<add> content = Template('''
<add> action: <i>{{ f.__name__ }}</i><br>
<add> <br>
<add> <b>Parameters</b>:<br>
<add> <table>
<add> {% for k, v in items %}
<add> {% if k != 'origin' %}
<add> <tr>
<add> <td>{{ k }}</td>
<add> <td>{{ v }}</td>
<add> </tr>
<add> {% endif %}
<add> {% endfor %}
<add> </table>
<add> ''').render(**locals())
<add> utils.send_email(task.email, subject, content)
<ide>
<ide> return f(*args, **kwargs)
<ide> return wrapper | 1 |
Python | Python | fix a small typo | 8f116200c5597e7d99dc77cb7911012635eb300e | <ide><path>libcloud/compute/drivers/cloudscale.py
<ide> def _list_resources(self, url, tranform_func):
<ide>
<ide> def _to_node(self, data):
<ide> state = self.NODE_STATE_MAP.get(data['status'], NodeState.UNKNOWN)
<del> extra_keys = ['volumes', 'inferfaces', 'anti_affinity_with']
<add> extra_keys = ['volumes', 'interfaces', 'anti_affinity_with']
<ide> extra = {}
<ide> for key in extra_keys:
<ide> if key in data: | 1 |
Java | Java | add support for removeoncancelpolicy | 7441f2301281049cff7224bf650646490388080e | <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBean.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.concurrent.ThreadFactory;
<ide>
<ide> import org.springframework.beans.factory.FactoryBean;
<add>import org.springframework.lang.UsesJava7;
<ide> import org.springframework.scheduling.support.DelegatingErrorHandlingRunnable;
<ide> import org.springframework.scheduling.support.TaskUtils;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> * @author Juergen Hoeller
<ide> * @since 2.0
<ide> * @see #setPoolSize
<add> * @see #setRemoveOnCancelPolicy(boolean)
<ide> * @see #setThreadFactory
<ide> * @see ScheduledExecutorTask
<ide> * @see java.util.concurrent.ScheduledExecutorService
<ide> public class ScheduledExecutorFactoryBean extends ExecutorConfigurationSupport
<ide> implements FactoryBean<ScheduledExecutorService> {
<ide>
<add> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher
<add> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod(
<add> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class);
<add>
<add>
<ide> private int poolSize = 1;
<ide>
<add> private Boolean removeOnCancelPolicy;
<add>
<ide> private ScheduledExecutorTask[] scheduledExecutorTasks;
<ide>
<ide> private boolean continueScheduledExecutionAfterException = false;
<ide> public void setPoolSize(int poolSize) {
<ide> this.poolSize = poolSize;
<ide> }
<ide>
<add> /**
<add> * Set the same property on ScheduledExecutorService available in JDK 1.7 or
<add> * higher. This property is ignored on JDK 1.6.
<add> * Default is false.
<add> */
<add> public void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy) {
<add> this.removeOnCancelPolicy = removeOnCancelPolicy;
<add> }
<add>
<ide> /**
<ide> * Register a list of ScheduledExecutorTask objects with the ScheduledExecutorService
<ide> * that this FactoryBean creates. Depending on each ScheduledExecutorTask's settings,
<ide> protected ExecutorService initializeExecutor(
<ide> ScheduledExecutorService executor =
<ide> createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);
<ide>
<add> if (executor instanceof ScheduledThreadPoolExecutor) {
<add> configureRemoveOnCancelPolicy(((ScheduledThreadPoolExecutor) executor));
<add> }
<add>
<ide> // Register specified ScheduledExecutorTasks, if necessary.
<ide> if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
<ide> registerTasks(this.scheduledExecutorTasks, executor);
<ide> protected Runnable getRunnableToSchedule(ScheduledExecutorTask task) {
<ide> new DelegatingErrorHandlingRunnable(task.getRunnable(), TaskUtils.LOG_AND_PROPAGATE_ERROR_HANDLER));
<ide> }
<ide>
<add> @UsesJava7 // guard setting removeOnCancelPolicy (safe with 1.6 due to hasRemoveOnCancelPolicyMethod check)
<add> private void configureRemoveOnCancelPolicy(ScheduledThreadPoolExecutor service) {
<add> if (hasRemoveOnCancelPolicyMethod && this.removeOnCancelPolicy != null) {
<add> service.setRemoveOnCancelPolicy(true);
<add> }
<add> }
<add>
<ide>
<ide> @Override
<ide> public ScheduledExecutorService getObject() {
<ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.core.task.AsyncListenableTaskExecutor;
<ide> import org.springframework.core.task.TaskRejectedException;
<add>import org.springframework.lang.UsesJava7;
<ide> import org.springframework.scheduling.SchedulingTaskExecutor;
<ide> import org.springframework.scheduling.TaskScheduler;
<ide> import org.springframework.scheduling.Trigger;
<ide> import org.springframework.scheduling.support.TaskUtils;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.ErrorHandler;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.util.concurrent.ListenableFutureTask;
<ide> * @author Mark Fisher
<ide> * @since 3.0
<ide> * @see #setPoolSize
<add> * @see #setRemoveOnCancelPolicy(boolean)
<ide> * @see #setThreadFactory
<ide> * @see #setErrorHandler
<ide> */
<ide> @SuppressWarnings("serial")
<ide> public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupport
<ide> implements AsyncListenableTaskExecutor, SchedulingTaskExecutor, TaskScheduler {
<ide>
<add> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher
<add> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod(
<add> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class);
<add>
<add>
<ide> private volatile int poolSize = 1;
<ide>
<add> private volatile Boolean removeOnCancelPolicy;
<add>
<ide> private volatile ScheduledExecutorService scheduledExecutor;
<ide>
<ide> private volatile ErrorHandler errorHandler;
<ide> public void setPoolSize(int poolSize) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Set the same property on ScheduledExecutorService available in JDK 1.7 or
<add> * higher. This property is ignored on JDK 1.6.
<add> * Default is false.
<add> * <p><b>This setting can be modified at runtime, for example through JMX.</b>
<add> */
<add> @UsesJava7 // guard setting removeOnCancelPolicy (safe with 1.6 due to hasRemoveOnCancelPolicyMethod check)
<add> public void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy) {
<add> this.removeOnCancelPolicy = removeOnCancelPolicy;
<add> if (this.scheduledExecutor instanceof ScheduledThreadPoolExecutor) {
<add> configureRemoveOnCancelPolicy((ScheduledThreadPoolExecutor) this.scheduledExecutor);
<add> }
<add> }
<add>
<add> @UsesJava7 // guard setting removeOnCancelPolicy (safe with 1.6 due to hasRemoveOnCancelPolicyMethod check)
<add> private void configureRemoveOnCancelPolicy(ScheduledThreadPoolExecutor service) {
<add> if (hasRemoveOnCancelPolicyMethod && this.removeOnCancelPolicy != null) {
<add> service.setRemoveOnCancelPolicy(true);
<add> }
<add> }
<add>
<ide> /**
<ide> * Set a custom {@link ErrorHandler} strategy.
<ide> */
<ide> protected ExecutorService initializeExecutor(
<ide> ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
<ide>
<ide> this.scheduledExecutor = createExecutor(this.poolSize, threadFactory, rejectedExecutionHandler);
<add>
<add> if (this.scheduledExecutor instanceof ScheduledThreadPoolExecutor) {
<add> configureRemoveOnCancelPolicy(((ScheduledThreadPoolExecutor) this.scheduledExecutor));
<add> }
<add>
<ide> return this.scheduledExecutor;
<ide> }
<ide>
<ide> public int getPoolSize() {
<ide> return getScheduledThreadPoolExecutor().getPoolSize();
<ide> }
<ide>
<add> /**
<add> * Return the current setting of removeOnCancelPolicy.
<add> * <p>Requires an underlying {@link ScheduledThreadPoolExecutor} and JDK 1.7+.
<add> */
<add> public boolean isRemoveOnCancelPolicy() {
<add> return this.removeOnCancelPolicy;
<add> }
<add>
<ide> /**
<ide> * Return the number of currently active threads.
<ide> * <p>Requires an underlying {@link ScheduledThreadPoolExecutor}.
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketNamespaceUtils.java
<ide>
<ide> package org.springframework.web.socket.config;
<ide>
<del>import org.springframework.web.socket.sockjs.transport.SockJsThreadPoolTaskScheduler;
<add>import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
<ide> import org.w3c.dom.Element;
<ide>
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> private static RuntimeBeanReference registerSockJsTaskScheduler(String scheduler
<ide> ParserContext parserContext, Object source) {
<ide>
<ide> if (!parserContext.getRegistry().containsBeanDefinition(schedulerName)) {
<del> RootBeanDefinition taskSchedulerDef = new RootBeanDefinition(SockJsThreadPoolTaskScheduler.class);
<add> RootBeanDefinition taskSchedulerDef = new RootBeanDefinition(ThreadPoolTaskScheduler.class);
<ide> taskSchedulerDef.setSource(source);
<ide> taskSchedulerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
<ide> taskSchedulerDef.getPropertyValues().add("poolSize", Runtime.getRuntime().availableProcessors());
<ide> taskSchedulerDef.getPropertyValues().add("threadNamePrefix", schedulerName + "-");
<add> taskSchedulerDef.getPropertyValues().add("removeOnCancelPolicy", true);
<ide> parserContext.getRegistry().registerBeanDefinition(schedulerName, taskSchedulerDef);
<ide> parserContext.registerComponent(new BeanComponentDefinition(taskSchedulerDef, schedulerName));
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketConfigurationSupport.java
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
<ide> import org.springframework.web.servlet.HandlerMapping;
<del>import org.springframework.web.servlet.handler.AbstractHandlerMapping;
<del>import org.springframework.web.socket.sockjs.transport.SockJsThreadPoolTaskScheduler;
<ide>
<ide> /**
<ide> * Configuration support for WebSocket request handling.
<ide> public class WebSocketConfigurationSupport {
<ide> public HandlerMapping webSocketHandlerMapping() {
<ide> ServletWebSocketHandlerRegistry registry = new ServletWebSocketHandlerRegistry(defaultSockJsTaskScheduler());
<ide> registerWebSocketHandlers(registry);
<del> AbstractHandlerMapping hm = registry.getHandlerMapping();
<del> return hm;
<add> return registry.getHandlerMapping();
<ide> }
<ide>
<ide> protected void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
<ide> protected void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
<ide> */
<ide> @Bean
<ide> public ThreadPoolTaskScheduler defaultSockJsTaskScheduler() {
<del> ThreadPoolTaskScheduler scheduler = new SockJsThreadPoolTaskScheduler();
<add> ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
<ide> scheduler.setThreadNamePrefix("SockJS-");
<add> scheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
<add> scheduler.setRemoveOnCancelPolicy(true);
<ide> return scheduler;
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupport.java
<ide> import org.springframework.web.servlet.HandlerMapping;
<ide> import org.springframework.web.socket.WebSocketHandler;
<ide> import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler;
<del>import org.springframework.web.socket.sockjs.transport.SockJsThreadPoolTaskScheduler;
<ide>
<ide> /**
<ide> * Extends {@link AbstractMessageBrokerConfiguration} and adds configuration for
<ide> protected void configureWebSocketTransport(WebSocketTransportRegistration regist
<ide> */
<ide> @Bean
<ide> public ThreadPoolTaskScheduler messageBrokerSockJsTaskScheduler() {
<del> ThreadPoolTaskScheduler scheduler = new SockJsThreadPoolTaskScheduler();
<add> ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
<ide> scheduler.setThreadNamePrefix("MessageBrokerSockJS-");
<add> scheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
<add> scheduler.setRemoveOnCancelPolicy(true);
<ide> return scheduler;
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/SockJsThreadPoolTaskScheduler.java
<del>/*
<del> * Copyright 2002-2014 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.web.socket.sockjs.transport;
<del>
<del>import org.springframework.lang.UsesJava7;
<del>import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
<del>import org.springframework.util.ClassUtils;
<del>
<del>import java.util.concurrent.ExecutorService;
<del>import java.util.concurrent.RejectedExecutionHandler;
<del>import java.util.concurrent.ScheduledThreadPoolExecutor;
<del>import java.util.concurrent.ThreadFactory;
<del>
<del>/**
<del> * An extension of ThreadPoolTaskScheduler optimized for managing a large number
<del> * of task, e.g. setting he pool size to the number of available processors and
<del> * setting the setRemoveOnCancelPolicy property of
<del> * {@link java.util.concurrent.ScheduledThreadPoolExecutor} available in JDK 1.7
<del> * or higher in order to avoid keeping cancelled tasks around.
<del> *
<del> * @author Rossen Stoyanchev
<del> * @since 4.1
<del> */
<del>@SuppressWarnings("serial")
<del>public class SockJsThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {
<del>
<del> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher
<del> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod(
<del> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class);
<del>
<del>
<del> public SockJsThreadPoolTaskScheduler() {
<del> setThreadNamePrefix("SockJS-");
<del> setPoolSize(Runtime.getRuntime().availableProcessors());
<del> }
<del>
<del>
<del> @Override
<del> protected ExecutorService initializeExecutor(ThreadFactory factory, RejectedExecutionHandler handler) {
<del> ExecutorService service = super.initializeExecutor(factory, handler);
<del> configureRemoveOnCancelPolicy((ScheduledThreadPoolExecutor) service);
<del> return service;
<del> }
<del>
<del> @UsesJava7 // guard setting removeOnCancelPolicy (safe with 1.6 due to hasRemoveOnCancelPolicyMethod check)
<del> private void configureRemoveOnCancelPolicy(ScheduledThreadPoolExecutor service) {
<del> if (hasRemoveOnCancelPolicyMethod) {
<del> service.setRemoveOnCancelPolicy(true);
<del> }
<del> }
<del>
<del>}
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandlerTests.java
<ide> public void checkSession() throws Exception {
<ide> assertTrue(session1.isOpen());
<ide> assertFalse(session2.isOpen());
<ide> assertNull(session1.getCloseStatus());
<del> assertEquals(CloseStatus.PROTOCOL_ERROR, session2.getCloseStatus());
<add> assertEquals(CloseStatus.SESSION_NOT_RELIABLE, session2.getCloseStatus());
<ide> }
<ide>
<ide> | 7 |
Python | Python | remove non-native byte order from _var check | 3d9b25d6b6234aa95ff54c595e02a916056beab8 | <ide><path>numpy/core/_methods.py
<ide> _complex_to_float.update({
<ide> nt.dtype(nt.clongdouble) : nt.dtype(nt.longdouble),
<ide> })
<del># Add reverse-endian types
<del>_complex_to_float.update({
<del> k.newbyteorder() : v.newbyteorder() for k, v in _complex_to_float.items()
<del>})
<ide>
<ide> # avoid keyword arguments to speed up parsing, saves about 15%-20% for very
<ide> # small reductions | 1 |
Go | Go | add integration test for start_first update order | 6763641d6932468a0503516bb32e39202989aa52 | <ide><path>integration-cli/docker_api_swarm_service_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmServicesUpdate(c *check.C) {
<ide> map[string]int{image1: instances})
<ide> }
<ide>
<add>func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateStartFirst(c *check.C) {
<add> d := s.AddDaemon(c, true, true)
<add>
<add> // service image at start
<add> image1 := "busybox:latest"
<add> // target image in update
<add> image2 := "testhealth"
<add>
<add> // service started from this image won't pass health check
<add> _, _, err := d.BuildImageWithOut(image2,
<add> `FROM busybox
<add> HEALTHCHECK --interval=1s --timeout=1s --retries=1024\
<add> CMD cat /status`,
<add> true)
<add> c.Check(err, check.IsNil)
<add>
<add> // create service
<add> instances := 5
<add> parallelism := 2
<add> rollbackParallelism := 3
<add> id := d.CreateService(c, serviceForUpdate, setInstances(instances), setUpdateOrder(swarm.UpdateOrderStartFirst), setRollbackOrder(swarm.UpdateOrderStartFirst))
<add>
<add> checkStartingTasks := func(expected int) []swarm.Task {
<add> var startingTasks []swarm.Task
<add> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
<add> tasks := d.GetServiceTasks(c, id)
<add> startingTasks = nil
<add> for _, t := range tasks {
<add> if t.Status.State == swarm.TaskStateStarting {
<add> startingTasks = append(startingTasks, t)
<add> }
<add> }
<add> return startingTasks, nil
<add> }, checker.HasLen, expected)
<add>
<add> return startingTasks
<add> }
<add>
<add> makeTasksHealthy := func(tasks []swarm.Task) {
<add> for _, t := range tasks {
<add> containerID := t.Status.ContainerStatus.ContainerID
<add> d.Cmd("exec", containerID, "touch", "/status")
<add> }
<add> }
<add>
<add> // wait for tasks ready
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances})
<add>
<add> // issue service update
<add> service := d.GetService(c, id)
<add> d.UpdateService(c, service, setImage(image2))
<add>
<add> // first batch
<add>
<add> // The old tasks should be running, and the new ones should be starting.
<add> startingTasks := checkStartingTasks(parallelism)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances})
<add>
<add> // make it healthy
<add> makeTasksHealthy(startingTasks)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances - parallelism, image2: parallelism})
<add>
<add> // 2nd batch
<add>
<add> // The old tasks should be running, and the new ones should be starting.
<add> startingTasks = checkStartingTasks(parallelism)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances - parallelism, image2: parallelism})
<add>
<add> // make it healthy
<add> makeTasksHealthy(startingTasks)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances - 2*parallelism, image2: 2 * parallelism})
<add>
<add> // 3nd batch
<add>
<add> // The old tasks should be running, and the new ones should be starting.
<add> startingTasks = checkStartingTasks(1)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances - 2*parallelism, image2: 2 * parallelism})
<add>
<add> // make it healthy
<add> makeTasksHealthy(startingTasks)
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image2: instances})
<add>
<add> // Roll back to the previous version. This uses the CLI because
<add> // rollback is a client-side operation.
<add> out, err := d.Cmd("service", "update", "--rollback", id)
<add> c.Assert(err, checker.IsNil, check.Commentf(out))
<add>
<add> // first batch
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image2: instances - rollbackParallelism, image1: rollbackParallelism})
<add>
<add> // 2nd batch
<add> waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
<add> map[string]int{image1: instances})
<add>}
<add>
<ide> func (s *DockerSwarmSuite) TestAPISwarmServicesFailedUpdate(c *check.C) {
<ide> const nodeCount = 3
<ide> var daemons [nodeCount]*daemon.Swarm
<ide><path>integration-cli/docker_api_swarm_test.go
<ide> func setInstances(replicas int) daemon.ServiceConstructor {
<ide> }
<ide> }
<ide>
<add>func setUpdateOrder(order string) daemon.ServiceConstructor {
<add> return func(s *swarm.Service) {
<add> if s.Spec.UpdateConfig == nil {
<add> s.Spec.UpdateConfig = &swarm.UpdateConfig{}
<add> }
<add> s.Spec.UpdateConfig.Order = order
<add> }
<add>}
<add>
<add>func setRollbackOrder(order string) daemon.ServiceConstructor {
<add> return func(s *swarm.Service) {
<add> if s.Spec.RollbackConfig == nil {
<add> s.Spec.RollbackConfig = &swarm.UpdateConfig{}
<add> }
<add> s.Spec.RollbackConfig.Order = order
<add> }
<add>}
<add>
<ide> func setImage(image string) daemon.ServiceConstructor {
<ide> return func(s *swarm.Service) {
<ide> s.Spec.TaskTemplate.ContainerSpec.Image = image | 2 |
Text | Text | use the word "maintainers" | ebd77ae8c429b3d9ac200df11c7cccec2137d629 | <ide><path>README.md
<ide> Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebre
<ide>
<ide> Who Are You?
<ide> ------------
<del>Homebrew is currently maintained by [Misty De Meo][mistydemeo], [Adam Vandenberg][adamv], [Jack Nagel][jacknagel], [Mike McQuaid][mikemcquaid] and [Brett Koonce][asparagui].
<add>Homebrew's current maintainers are [Misty De Meo][mistydemeo], [Adam Vandenberg][adamv], [Jack Nagel][jacknagel], [Mike McQuaid][mikemcquaid] and [Brett Koonce][asparagui].
<ide>
<ide> Homebrew was originally created by [Max Howell][mxcl].
<ide> | 1 |
PHP | PHP | remove inflection from missing controller errors | 672519855564b7110595201bd2cdda86ca8c2d98 | <ide><path>src/Routing/Dispatcher.php
<ide> public function dispatch(Request $request, Response $response) {
<ide>
<ide> if (!($controller instanceof Controller)) {
<ide> throw new MissingControllerException(array(
<del> 'class' => Inflector::camelize($request->params['controller']),
<del> 'plugin' => empty($request->params['plugin']) ? null : Inflector::camelize($request->params['plugin']),
<del> 'prefix' => empty($request->params['prefix']) ? null : Inflector::camelize($request->params['prefix']),
<add> 'class' => $request->params['controller'],
<add> 'plugin' => empty($request->params['plugin']) ? null : $request->params['plugin'],
<add> 'prefix' => empty($request->params['prefix']) ? null : $request->params['prefix'],
<ide> '_ext' => empty($request->params['_ext']) ? null : $request->params['_ext']
<ide> ));
<ide> }
<ide><path>tests/TestCase/Routing/DispatcherTest.php
<ide> public function testMissingController() {
<ide> $request = new Request([
<ide> 'url' => 'some_controller/home',
<ide> 'params' => [
<del> 'controller' => 'some_controller',
<add> 'controller' => 'SomeController',
<ide> 'action' => 'home',
<ide> ]
<ide> ]);
<ide> public function testMissingControllerInterface() {
<ide> $request = new Request([
<ide> 'url' => 'dispatcher_test_interface/index',
<ide> 'params' => [
<del> 'controller' => 'dispatcher_test_interface',
<add> 'controller' => 'DispatcherTestInterface',
<ide> 'action' => 'index',
<ide> ]
<ide> ]);
<ide> public function testMissingControllerAbstract() {
<ide> $request = new Request([
<ide> 'url' => 'abstract/index',
<ide> 'params' => [
<del> 'controller' => 'abstract',
<add> 'controller' => 'Abstract',
<ide> 'action' => 'index',
<ide> ]
<ide> ]);
<ide> public function testDispatchBasic() {
<ide> $url = new Request([
<ide> 'url' => 'pages/home',
<ide> 'params' => [
<del> 'controller' => 'pages',
<add> 'controller' => 'Pages',
<ide> 'action' => 'display',
<ide> 'pass' => ['extract'],
<ide> 'return' => 1 | 2 |
Javascript | Javascript | restore optselected hack still needed by ie9/10 | f75c0627f22b4af52199b46659675258811970f5 | <ide><path>src/attributes.js
<ide> jQuery.each([ "radio", "checkbox" ], function() {
<ide> }
<ide> });
<ide> });
<add>
<add>// IE9/10 do not see a selected option inside an optgroup unless you access it
<add>// Support: IE9, IE10
<add>if ( !jQuery.support.optSelected ) {
<add> jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
<add> get: function( elem ) {
<add> var parent = elem.parentNode;
<add> if ( parent && parent.parentNode ) {
<add> parent.parentNode.selectedIndex;
<add> }
<add> return null;
<add> }
<add> });
<add>}
<ide><path>src/support.js
<ide> jQuery.support = (function() {
<ide> // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
<ide> checkOn: !!input.value,
<ide>
<add> // Must access the parent to make an option select properly
<add> // Support: IE9, IE10
<add> optSelected: opt.selected,
<add>
<ide> // Makes sure cloning an html5 element does not cause problems
<ide> // Where outerHTML is undefined, this still works
<ide> html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", | 2 |
Javascript | Javascript | delay pause/resume until after connect | de65ba7aba0e48a846e8cad86278f51372d3de23 | <ide><path>lib/net.js
<ide> Object.defineProperty(Socket.prototype, 'bufferSize', {
<ide>
<ide>
<ide> Socket.prototype.pause = function() {
<add> if (this._paused) return;
<add> this._paused = true;
<add> if (this._connecting) {
<add> // will actually pause once the handle is established.
<add> return;
<add> }
<ide> if (this._handle) {
<ide> this._handle.readStop();
<ide> }
<ide> };
<ide>
<ide>
<ide> Socket.prototype.resume = function() {
<add> if (!this._paused) return;
<add> this._paused = false;
<add> if (this._connecting) {
<add> // will actually resume once the handle is established.
<add> return;
<add> }
<ide> if (this._handle) {
<ide> this._handle.readStart();
<ide> }
<ide> function afterConnect(status, handle, req, readable, writable) {
<ide> assert.ok(self._connecting);
<ide> self._connecting = false;
<ide>
<add> // now that we're connected, process any pending pause state.
<add> if (self._paused) {
<add> self._paused = false;
<add> self.pause();
<add> }
<add>
<ide> if (status == 0) {
<ide> self.readable = readable;
<ide> self.writable = writable;
<ide><path>test/simple/test-net-socket-pause-resume-immediate.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 net = require('net');
<add>
<add>var sock = net.connect(1234, 'localhost');
<add>sock.pause();
<add>sock.resume();
<add>console.log('ok');
<add>process.exit(0); | 2 |
Javascript | Javascript | transform app url to editor | fd955635e57368de46998487ec54bae47bf26d97 | <ide><path>client/src/templates/Challenges/redux/create-question-epic.js
<ide> import {
<ide> projectFormValuesSelector
<ide> } from '../redux';
<ide> import { tap, mapTo } from 'rxjs/operators';
<add>import { transformEditorLink } from '../utils';
<ide> import envData from '../../../../../config/env.json';
<ide>
<ide> const { forumLocation } = envData;
<ide> function createQuestionEpic(action$, state$, { window }) {
<ide> }
<ide> ${
<ide> projectFormValues
<del> ?.map(([key, val]) => `${key}: ${val}\n`)
<add> ?.map(([key, val]) => `${key}: ${transformEditorLink(val)}\n`)
<ide> ?.join('') || filesToMarkdown(files)
<ide> }
<ide>
<ide><path>client/src/templates/Challenges/redux/create-question-epic.test.js
<add>/* global expect */
<add>
<add>import { transformEditorLink } from '../utils';
<add>
<add>describe('create-question-epic', () => {
<add> describe('transformEditorLink', () => {
<add> const links = [
<add> {
<add> input: 'https://some-project.camperbot.repl.co',
<add> expected: 'https://replit.com/@camperbot/some-project'
<add> },
<add> {
<add> input: 'https://some-project.glitch.me/',
<add> expected: 'https://glitch.com/edit/#!/some-project'
<add> },
<add> {
<add> input: 'https://github.com/user/repo-name',
<add> expected: 'https://github.com/user/repo-name'
<add> }
<add> ];
<add> it('should correctly transform app links to editor links', () => {
<add> links.forEach(link => {
<add> expect(transformEditorLink(link.input)).toStrictEqual(link.expected);
<add> });
<add> });
<add> it('should not transform editor links in GitHub submission', () => {
<add> links.forEach(link => {
<add> expect(transformEditorLink(link.expected)).toStrictEqual(link.expected);
<add> });
<add> });
<add> });
<add>});
<ide><path>client/src/templates/Challenges/utils/index.js
<ide> export function isGoodXHRStatus(status) {
<ide> const statusInt = parseInt(status, 10);
<ide> return (statusInt >= 200 && statusInt < 400) || statusInt === 402;
<ide> }
<add>
<add>export function transformEditorLink(url) {
<add> return url
<add> .replace(
<add> /(?<=\/\/)(?<projectname>[^.]+)\.(?<username>[^.]+)\.repl\.co\/?/,
<add> 'replit.com/@$<username>/$<projectname>'
<add> )
<add> .replace(
<add> /(?<=\/\/)(?<projectname>[^.]+)\.glitch\.me\/?/,
<add> 'glitch.com/edit/#!/$<projectname>'
<add> );
<add>} | 3 |
PHP | PHP | use null session handler | 3b6da655655c08bbb513f511461bcb1b40eb8d57 | <ide><path>src/Illuminate/Session/SessionManager.php
<ide> use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
<ide> use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
<ide> use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
<add>use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
<ide> use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler;
<ide>
<ide> class SessionManager extends Manager {
<ide> protected function callCustomCreator($driver)
<ide> */
<ide> protected function createArrayDriver()
<ide> {
<del> return new Store(new MockArraySessionStorage);
<add> return new Store($this->app['config']['session.cookie'], new NullSessionHandler);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | remove stray ( | 26889bb61f152a8d7c438f8504cd97179c9eb1d3 | <ide><path>src/Validation/Validation.php
<ide> public static function url($check, $strict = false)
<ide> static::_populateIp();
<ide>
<ide> $emoji = '\x{1F190}-\x{1F9EF}';
<del> $alpha = '0-9(\p{L}\p{N}' . $emoji;
<add> $alpha = '0-9\p{L}\p{N}' . $emoji;
<ide> $hex = '(%[0-9a-f]{2})';
<ide> $subDelimiters = preg_quote('/!"$&\'()*+,-.@_:;=~[]', '/');
<ide> $path = '([' . $subDelimiters . $alpha . ']|' . $hex . ')'; | 1 |
PHP | PHP | add @return to settrustedproxies method | 4061792e9d0a7916955e94dd5625342f3b144f9e | <ide><path>src/Http/ServerRequest.php
<ide> public function clientIp()
<ide> * register trusted proxies
<ide> *
<ide> * @param array $proxies ips list of trusted proxies
<add> * @return void
<ide> */
<ide> public function setTrustedProxies(array $proxies)
<ide> { | 1 |
Ruby | Ruby | correct doc for (audio|video)_tag [ci skip] | 6d8beaad1f5f69a5af3b2044b492b9dd636cc094 | <ide><path>actionview/lib/action_view/helpers/asset_tag_helper.rb
<ide> def image_alt(src)
<ide> # ==== Examples
<ide> #
<ide> # video_tag("trailer")
<del> # # => <video src="/videos/trailer" />
<add> # # => <video src="/videos/trailer"></video>
<ide> # video_tag("trailer.ogg")
<del> # # => <video src="/videos/trailer.ogg" />
<add> # # => <video src="/videos/trailer.ogg"></video>
<ide> # video_tag("trailer.ogg", controls: true, autobuffer: true)
<del> # # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
<add> # # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" ></video>
<ide> # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
<del> # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
<add> # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/images/screenshot.png"></video>
<ide> # video_tag("/trailers/hd.avi", size: "16x16")
<del> # # => <video src="/trailers/hd.avi" width="16" height="16" />
<add> # # => <video src="/trailers/hd.avi" width="16" height="16"></video>
<ide> # video_tag("/trailers/hd.avi", size: "16")
<del> # # => <video height="16" src="/trailers/hd.avi" width="16" />
<add> # # => <video height="16" src="/trailers/hd.avi" width="16"></video>
<ide> # video_tag("/trailers/hd.avi", height: '32', width: '32')
<del> # # => <video height="32" src="/trailers/hd.avi" width="32" />
<add> # # => <video height="32" src="/trailers/hd.avi" width="32"></video>
<ide> # video_tag("trailer.ogg", "trailer.flv")
<ide> # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
<ide> # video_tag(["trailer.ogg", "trailer.flv"])
<ide> def video_tag(*sources)
<ide> # your public audios directory.
<ide> #
<ide> # audio_tag("sound")
<del> # # => <audio src="/audios/sound" />
<add> # # => <audio src="/audios/sound"></audio>
<ide> # audio_tag("sound.wav")
<del> # # => <audio src="/audios/sound.wav" />
<add> # # => <audio src="/audios/sound.wav"></audio>
<ide> # audio_tag("sound.wav", autoplay: true, controls: true)
<del> # # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
<add> # # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav"></audio>
<ide> # audio_tag("sound.wav", "sound.mid")
<ide> # # => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>
<ide> def audio_tag(*sources) | 1 |
Ruby | Ruby | add support for optional and recommended deps | 6193167f5878bbc09b3417dc2b836be3b10d5b1e | <ide><path>Library/Homebrew/build_options.rb
<ide> def include? name
<ide> @args.include? '--' + name
<ide> end
<ide>
<add> def with? name
<add> if has_option? "with-#{name}"
<add> include? "with-#{name}"
<add> elsif has_option? "without-#{name}"
<add> not include? "without-#{name}"
<add> else
<add> false
<add> end
<add> end
<add>
<add> def without? name
<add> not with? name
<add> end
<add>
<ide> def head?
<ide> @args.flag? '--HEAD'
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def test &block
<ide> # This method is called once by `factory` before creating any instances.
<ide> # It allows the DSL to finalize itself, reducing complexity in the constructor.
<ide> def finalize_dsl
<add> # Synthesize options for optional dependencies
<add> dependencies.deps.select(&:optional?).each do |dep|
<add> option "with-#{dep.name}", "Build with #{dep.name} support"
<add> end
<add>
<add> # Synthesize options for recommended dependencies
<add> dependencies.deps.select(&:recommended?).each do |dep|
<add> option "without-#{dep.name}", "Build without #{dep.name} support"
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_build_options.rb
<ide> def test_include
<ide> assert !@build.include?("--with-foo")
<ide> end
<ide>
<add> def test_with_without
<add> assert @build.with?("foo")
<add> assert @build.with?("bar")
<add> assert @build.with?("baz")
<add> assert @build.without?("qux")
<add> end
<add>
<ide> def test_used_options
<ide> assert @build.used_options.include?("--with-foo")
<ide> assert @build.used_options.include?("--with-bar") | 3 |
Ruby | Ruby | remove config dir from the load path | 57f0b9738e71016d8a9898d83fe39b2310bf6c91 | <ide><path>railties/lib/initializer.rb
<ide> def after_initialize
<ide> def load_application_initializers
<ide> if gems_dependencies_loaded
<ide> Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer|
<del> load initializer.sub(/^#{Regexp.escape(configuration.root_path)}\//, '')
<add> load(initializer)
<ide> end
<ide> end
<ide> end
<ide> def default_load_paths
<ide> app/controllers
<ide> app/helpers
<ide> app/services
<del> config
<ide> lib
<ide> vendor
<ide> ).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) } | 1 |
Text | Text | add npm link to readme | d548d28f516ffee5da30f645245069218a5833d0 | <ide><path>README.md
<ide>
<ide> Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js
<ide> uses an event-driven, non-blocking I/O model that makes it lightweight and
<del>efficient. The Node.js package ecosystem, npm, is the largest ecosystem of open
<del>source libraries in the world.
<add>efficient. The Node.js package ecosystem, [npm][], is the largest ecosystem of
<add>open source libraries in the world.
<ide>
<ide> The Node.js project is supported by the
<ide> [Node.js Foundation](https://nodejs.org/en/foundation/). Contributions,
<ide> keys:
<ide> * **Timothy J Fontaine** <tjfontaine@gmail.com>
<ide> `7937DFD2AB06298B2293C3187D33FF9D0246406D`
<ide>
<add>[npm]: https://www.npmjs.com
<ide> [Website]: https://nodejs.org/en/
<ide> [Contributing to the project]: CONTRIBUTING.md
<ide> [Node.js Help]: https://github.com/nodejs/help | 1 |
PHP | PHP | apply fixes from styleci | ac3d11e2a0d7d794adcdde648a27594a4153f6e9 | <ide><path>src/Illuminate/Database/Connectors/Connector.php
<ide> class Connector
<ide> public function createConnection($dsn, array $config, array $options)
<ide> {
<ide> list($username, $password) = [
<del> Arr::get($config, 'username'), Arr::get($config, 'password')
<add> Arr::get($config, 'username'), Arr::get($config, 'password'),
<ide> ];
<ide>
<ide> try { | 1 |
PHP | PHP | add guard to authentication events | 69cddedae349956c5f38455e861e3fc490d89a07 | <ide><path>src/Illuminate/Auth/Events/Attempting.php
<ide> class Attempting
<ide> */
<ide> public $remember;
<ide>
<add> /**
<add> * The guard this attempt is made to.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<ide> /**
<ide> * Create a new event instance.
<ide> *
<ide> * @param array $credentials
<ide> * @param bool $remember
<add> * @param string $guard
<ide> * @return void
<ide> */
<del> public function __construct($credentials, $remember)
<add> public function __construct($credentials, $remember, $guard)
<ide> {
<ide> $this->remember = $remember;
<ide> $this->credentials = $credentials;
<add> $this->guard = $guard;
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/Events/Authenticated.php
<ide> class Authenticated
<ide> */
<ide> public $user;
<ide>
<add> /**
<add> * The guard the user is authenticating to.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<ide> /**
<ide> * Create a new event instance.
<ide> *
<ide> * @param \Illuminate\Contracts\Auth\Authenticatable $user
<add> * @param string $guard
<ide> * @return void
<ide> */
<del> public function __construct($user)
<add> public function __construct($user, $guard)
<ide> {
<ide> $this->user = $user;
<add> $this->guard = $guard;
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/Events/Failed.php
<ide> class Failed
<ide> */
<ide> public $credentials;
<ide>
<add> /**
<add> * The guard the user failed to authenticated to.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<ide> /**
<ide> * Create a new event instance.
<ide> *
<ide> * @param \Illuminate\Contracts\Auth\Authenticatable|null $user
<ide> * @param array $credentials
<add> * @param string $guard
<ide> * @return void
<ide> */
<del> public function __construct($user, $credentials)
<add> public function __construct($user, $credentials, $guard)
<ide> {
<ide> $this->user = $user;
<ide> $this->credentials = $credentials;
<add> $this->guard = $guard;
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/Events/Login.php
<ide> class Login
<ide> */
<ide> public $remember;
<ide>
<add> /**
<add> * The guard the user authenticated to.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<ide> /**
<ide> * Create a new event instance.
<ide> *
<ide> * @param \Illuminate\Contracts\Auth\Authenticatable $user
<ide> * @param bool $remember
<add> * @param string $guard
<ide> * @return void
<ide> */
<del> public function __construct($user, $remember)
<add> public function __construct($user, $remember, $guard)
<ide> {
<ide> $this->user = $user;
<ide> $this->remember = $remember;
<add> $this->guard = $guard;
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/Events/Logout.php
<ide> class Logout
<ide> */
<ide> public $user;
<ide>
<add> /**
<add> * The guard to which the user was authenticated.
<add> *
<add> * @var string
<add> */
<add> public $guard;
<add>
<ide> /**
<ide> * Create a new event instance.
<ide> *
<ide> * @param \Illuminate\Contracts\Auth\Authenticatable $user
<add> * @param string $guard
<ide> * @return void
<ide> */
<del> public function __construct($user)
<add> public function __construct($user, $guard)
<ide> {
<ide> $this->user = $user;
<add> $this->guard = $guard;
<ide> }
<ide> }
<ide><path>src/Illuminate/Auth/SessionGuard.php
<ide> public function logout()
<ide> }
<ide>
<ide> if (isset($this->events)) {
<del> $this->events->dispatch(new Events\Logout($user));
<add> $this->events->dispatch(new Events\Logout($user, $this->name));
<ide> }
<ide>
<ide> // Once we have fired the logout event we will clear the users out of memory
<ide> protected function fireAttemptEvent(array $credentials, $remember = false)
<ide> {
<ide> if (isset($this->events)) {
<ide> $this->events->dispatch(new Events\Attempting(
<del> $credentials, $remember
<add> $credentials, $remember, $this->name
<ide> ));
<ide> }
<ide> }
<ide> protected function fireAttemptEvent(array $credentials, $remember = false)
<ide> protected function fireLoginEvent($user, $remember = false)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->dispatch(new Events\Login($user, $remember));
<add> $this->events->dispatch(new Events\Login(
<add> $user, $remember, $this->name
<add> ));
<ide> }
<ide> }
<ide>
<ide> protected function fireLoginEvent($user, $remember = false)
<ide> protected function fireAuthenticatedEvent($user)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->dispatch(new Events\Authenticated($user));
<add> $this->events->dispatch(new Events\Authenticated(
<add> $user, $this->name
<add> ));
<ide> }
<ide> }
<ide>
<ide> protected function fireAuthenticatedEvent($user)
<ide> protected function fireFailedEvent($user, array $credentials)
<ide> {
<ide> if (isset($this->events)) {
<del> $this->events->dispatch(new Events\Failed($user, $credentials));
<add> $this->events->dispatch(new Events\Failed(
<add> $user, $credentials, $this->name
<add> ));
<ide> }
<ide> }
<ide> | 6 |
Javascript | Javascript | add documentation only file to list of files | 62f79e820fcfb025acee688adae95481b35f6e54 | <ide><path>angularFiles.js
<ide> var angularFiles = {
<ide> 'src/ng/q.js',
<ide> 'src/ng/raf.js',
<ide> 'src/ng/rootScope.js',
<add> 'src/ng/rootElement.js',
<ide> 'src/ng/sanitizeUri.js',
<ide> 'src/ng/sce.js',
<ide> 'src/ng/sniffer.js', | 1 |
Javascript | Javascript | remove unused eslint-disable | a63fccc2590ff2ed1ce35107fb432e40c7a5e82a | <ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> // eslint-disable-next-line no-unused-vars
<ide> keyboardVerticalOffset = 0,
<ide> style,
<del> // eslint-disable-next-line no-unused-vars
<ide> onLayout,
<ide> ...props
<ide> } = this.props; | 1 |
Javascript | Javascript | fix catalan ordinals | 022cbb4407d9f25e21b201fae0f3a6b9a6a8380c | <ide><path>locale/ca.js
<ide> y : 'un any',
<ide> yy : '%d anys'
<ide> },
<del> ordinalParse : /\d{1,2}º/,
<del> ordinal : '%dº',
<add> ordinalParse: /\d{1,2}(r|n|t|è)/,
<add> ordinal : function (number) {
<add> var output = (number === 1) ? 'r' :
<add> (number === 2) ? 'n' :
<add> (number === 3) ? 'r' :
<add> (number === 4) ? 't' : 'è';
<add> return number + output;
<add> },
<ide> week : {
<ide> dow : 1, // Monday is the first day of the week.
<ide> doy : 4 // The week that contains Jan 4th is the first week of the year.
<ide><path>test/locale/ca.js
<ide> exports['locale:ca'] = {
<ide> },
<ide>
<ide> 'format ordinal' : function (test) {
<del> test.equal(moment([2011, 0, 1]).format('DDDo'), '1º', '1º');
<del> test.equal(moment([2011, 0, 2]).format('DDDo'), '2º', '2º');
<del> test.equal(moment([2011, 0, 3]).format('DDDo'), '3º', '3º');
<del> test.equal(moment([2011, 0, 4]).format('DDDo'), '4º', '4º');
<del> test.equal(moment([2011, 0, 5]).format('DDDo'), '5º', '5º');
<del> test.equal(moment([2011, 0, 6]).format('DDDo'), '6º', '6º');
<del> test.equal(moment([2011, 0, 7]).format('DDDo'), '7º', '7º');
<del> test.equal(moment([2011, 0, 8]).format('DDDo'), '8º', '8º');
<del> test.equal(moment([2011, 0, 9]).format('DDDo'), '9º', '9º');
<del> test.equal(moment([2011, 0, 10]).format('DDDo'), '10º', '10º');
<del>
<del> test.equal(moment([2011, 0, 11]).format('DDDo'), '11º', '11º');
<del> test.equal(moment([2011, 0, 12]).format('DDDo'), '12º', '12º');
<del> test.equal(moment([2011, 0, 13]).format('DDDo'), '13º', '13º');
<del> test.equal(moment([2011, 0, 14]).format('DDDo'), '14º', '14º');
<del> test.equal(moment([2011, 0, 15]).format('DDDo'), '15º', '15º');
<del> test.equal(moment([2011, 0, 16]).format('DDDo'), '16º', '16º');
<del> test.equal(moment([2011, 0, 17]).format('DDDo'), '17º', '17º');
<del> test.equal(moment([2011, 0, 18]).format('DDDo'), '18º', '18º');
<del> test.equal(moment([2011, 0, 19]).format('DDDo'), '19º', '19º');
<del> test.equal(moment([2011, 0, 20]).format('DDDo'), '20º', '20º');
<del>
<del> test.equal(moment([2011, 0, 21]).format('DDDo'), '21º', '21º');
<del> test.equal(moment([2011, 0, 22]).format('DDDo'), '22º', '22º');
<del> test.equal(moment([2011, 0, 23]).format('DDDo'), '23º', '23º');
<del> test.equal(moment([2011, 0, 24]).format('DDDo'), '24º', '24º');
<del> test.equal(moment([2011, 0, 25]).format('DDDo'), '25º', '25º');
<del> test.equal(moment([2011, 0, 26]).format('DDDo'), '26º', '26º');
<del> test.equal(moment([2011, 0, 27]).format('DDDo'), '27º', '27º');
<del> test.equal(moment([2011, 0, 28]).format('DDDo'), '28º', '28º');
<del> test.equal(moment([2011, 0, 29]).format('DDDo'), '29º', '29º');
<del> test.equal(moment([2011, 0, 30]).format('DDDo'), '30º', '30º');
<del>
<del> test.equal(moment([2011, 0, 31]).format('DDDo'), '31º', '31º');
<add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1r', '1r');
<add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2n', '2n');
<add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3r', '3r');
<add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4t', '4t');
<add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5è', '5è');
<add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6è', '6è');
<add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7è', '7è');
<add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8è', '8è');
<add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9è', '9è');
<add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10è', '10è');
<add>
<add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11è', '11è');
<add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12è', '12è');
<add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13è', '13è');
<add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14è', '14è');
<add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15è', '15è');
<add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16è', '16è');
<add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17è', '17è');
<add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18è', '18è');
<add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19è', '19è');
<add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20è', '20è');
<add>
<add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21è', '21è');
<add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22è', '22è');
<add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23è', '23è');
<add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24è', '24è');
<add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25è', '25è');
<add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26è', '26è');
<add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27è', '27è');
<add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28è', '28è');
<add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29è', '29è');
<add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30è', '30è');
<add>
<add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31è', '31è');
<ide> test.done();
<ide> },
<ide>
<ide> exports['locale:ca'] = {
<ide> },
<ide>
<ide> 'weeks year starting sunday formatted' : function (test) {
<del> test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52º', 'Jan 1 2012 should be week 52');
<del> test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1º', 'Jan 2 2012 should be week 1');
<del> test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1º', 'Jan 8 2012 should be week 1');
<del> test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2º', 'Jan 9 2012 should be week 2');
<del> test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2º', 'Jan 15 2012 should be week 2');
<add> test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52è', 'Jan 1 2012 should be week 52');
<add> test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1r', 'Jan 2 2012 should be week 1');
<add> test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1r', 'Jan 8 2012 should be week 1');
<add> test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2n', 'Jan 9 2012 should be week 2');
<add> test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2n', 'Jan 15 2012 should be week 2');
<ide>
<ide> test.done();
<ide> }, | 2 |
PHP | PHP | add backwards compatibility shim for response | c0a50db738290a3f529536a204de8e87b4d82dec | <ide><path>src/Network/Response.php
<add><?php
<add>// @deprecated Backwards compatibility with earler 3.x versions.
<add>class_alias('Cake\Http\Response', 'Cake\Network\Response'); | 1 |
Python | Python | add an autoencoder model and a test to go with it | 12f7f374c38760a265c468f8cb65f8c030a0cddb | <ide><path>keras/models.py
<ide> from . import objectives
<ide> from . import regularizers
<ide> from . import constraints
<add>from .layers.core import Merge
<add>
<ide> import time, copy
<ide> from .utils.generic_utils import Progbar, printv
<ide> from six.moves import range
<ide> def load_weights(self, filepath):
<ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
<ide> self.layers[k].set_weights(weights)
<ide> f.close()
<del>
<ide>\ No newline at end of file
<add>
<add>
<add>class Autoencoder(Sequential):
<add>
<add> def __init__(self, encoder, decoder):
<add> super(Autoencoder,self).__init__()
<add> self.encoder = encoder
<add> self.decoder = decoder
<add>
<add> self.add(Merge([self.encoder]))
<add> self.add(Merge([self.decoder]))
<add>
<add> def train(self, X, **kwargs):
<add> super(Autoencoder,self).train(X,X,**kwargs)
<add>
<add> def test(self, X, **kwargs):
<add> super(Autoencoder,self).test(X,X,**kwargs)
<add>
<add> def fit(self, X, **kwargs):
<add> super(Autoencoder,self).fit(X,X,**kwargs)
<add>
<add> def freeze_encoder(self):
<add> def zero_grad(g, p):
<add> return 0.
<add> self.encoder.regularizers = [zero_grad for r in self.encoder.regularizers]
<ide><path>test/test_autoencoder.py
<add>from __future__ import absolute_import
<add>from __future__ import print_function
<add>from keras.datasets import mnist
<add>from keras.models import Sequential, Autoencoder
<add>from keras.layers.core import Dense, Dropout, Activation, Layer, Merge
<add>from keras.optimizers import RMSprop
<add>import theano.tensor as T
<add>import numpy as np
<add>
<add>from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
<add>srng = RandomStreams()
<add>
<add>
<add>(X_train, y_train), (_, _) = mnist.load_data()
<add>
<add>X_train = X_train.reshape((X_train.shape[0],-1)).astype(float)/255.
<add>
<add>encoder = Sequential()
<add>decoder = Sequential()
<add>
<add>n_hidden = 64
<add>
<add>layer_enc = Dense(X_train.shape[1],n_hidden,W_regularizer=None)
<add>layer_dec = Dense(n_hidden,X_train.shape[1])
<add>
<add># Tie the weights of encoder and decoder
<add>layer_dec.params.remove(layer_dec.W)
<add>layer_dec.W = T.transpose(layer_enc.W)
<add>
<add>encoder.add(layer_enc)
<add>encoder.add(Dropout(p=0.3))
<add>encoder.add(Activation('relu'))
<add>encoder.add(Activation('softmax'))
<add>
<add>decoder.add(layer_dec)
<add>decoder.add(Activation('relu'))
<add>
<add>autoencoder = Autoencoder(encoder,decoder)
<add>
<add>rms = RMSprop()
<add>autoencoder.compile(loss='mean_squared_error', optimizer=rms)
<add>
<add>autoencoder.fit(X_train, verbose=1, nb_epoch=10)
<add>
<add>autoencoder.freeze_encoder()
<add>
<add>testnet = Sequential()
<add>testnet.add(Merge([autoencoder.encoder]))
<add>testnet.add(Dense(n_hidden,10))
<add>testnet.add(Activation('sigmoid'))
<add>
<add>W_pretrain = layer_enc.W.get_value()
<add>
<add>y_train_full = np.zeros((y_train.shape[0],10))
<add>for n in range(len(y_train)):
<add> y_train_full[n,y_train[n]] = 1.
<add>testnet.compile(loss='mean_squared_error', optimizer=rms)
<add>testnet.fit(X_train,y_train_full,nb_epoch=10)
<add>
<add>W_posttrain = layer_enc.W.get_value()
<add>
<add>assert(np.abs(W_posttrain-W_pretrain).max() < 1e-9) | 2 |
Java | Java | update copyright date | 915f1027a571f850c177a0a7da9263ead95599df | <ide><path>spring-core/src/main/java/org/springframework/util/ObjectUtils.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. | 1 |
Python | Python | fix indexerror in fromrecords | 3caf1223b9b8e4747fb7b41b2fbd2122ee175d03 | <ide><path>numpy/core/records.py
<ide> def fromarrays(arrayList, dtype=None, shape=None, formats=None,
<ide>
<ide> return _array
<ide>
<del># shape must be 1-d if you use list of lists...
<ide> def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
<ide> titles=None, aligned=False, byteorder=None):
<ide> """ create a recarray from a list of records in text form
<ide> def fromrecords(recList, dtype=None, shape=None, formats=None, names=None,
<ide> [(456, 'dbe', 1.2) (2, 'de', 1.3)]
<ide> """
<ide>
<del> nfields = len(recList[0])
<ide> if formats is None and dtype is None: # slower
<ide> obj = sb.array(recList, dtype=object)
<del> arrlist = [sb.array(obj[..., i].tolist()) for i in range(nfields)]
<add> arrlist = [sb.array(obj[..., i].tolist()) for i in range(obj.shape[-1])]
<ide> return fromarrays(arrlist, formats=formats, shape=shape, names=names,
<ide> titles=titles, aligned=aligned, byteorder=byteorder)
<ide>
<ide><path>numpy/core/tests/test_records.py
<ide> def test_fromrecords(self):
<ide> assert_equal(r['col2'].dtype.itemsize, 3)
<ide> assert_equal(r['col3'].dtype.kind, 'f')
<ide>
<add> def test_fromrecords_0len(self):
<add> """ Verify fromrecords works with a 0-length input """
<add> dtype = [('a', np.float), ('b', np.float)]
<add> r = np.rec.fromrecords([], dtype=dtype)
<add> assert_equal(r.shape, (0,))
<add>
<add> def test_fromrecords_2d(self):
<add> data = [
<add> [(1, 2), (3, 4), (5, 6)],
<add> [(6, 5), (4, 3), (2, 1)]
<add> ]
<add> expected_a = [[1, 3, 5], [6, 4, 2]]
<add> expected_b = [[2, 4, 6], [5, 3, 1]]
<add>
<add> # try with dtype
<add> r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
<add> assert_equal(r1['a'], expected_a)
<add> assert_equal(r1['b'], expected_b)
<add>
<add> # try with names
<add> r2 = np.rec.fromrecords(data, names=['a', 'b'])
<add> assert_equal(r2['a'], expected_a)
<add> assert_equal(r2['b'], expected_b)
<add>
<add> assert_equal(r1, r2)
<add>
<ide> def test_method_array(self):
<ide> r = np.rec.array(asbytes('abcdefg') * 100, formats='i2,a3,i4', shape=3, byteorder='big')
<ide> assert_equal(r[1].item(), (25444, asbytes('efg'), 1633837924)) | 2 |
Ruby | Ruby | require rack/utils in exception_wrapper | 85842c553d29cf0cd4353cd71f03bd64b013138a | <ide><path>actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
<ide> require 'action_controller/metal/exceptions'
<ide> require 'active_support/core_ext/module/attribute_accessors'
<add>require 'rack/utils'
<ide>
<ide> module ActionDispatch
<ide> class ExceptionWrapper | 1 |
Javascript | Javascript | fix performance regression | ae244a26c1364857752db2aa79ef1a4a80912459 | <ide><path>lib/string_decoder.js
<ide> StringDecoder.prototype.write = function(buffer) {
<ide> var charReceived = this.charReceived;
<ide> var surrogateSize = this.surrogateSize;
<ide> var encoding = this.encoding;
<add> var charCode;
<ide> // if our last write ended with an incomplete multibyte character
<ide> while (charLength) {
<ide> // determine how many remaining bytes this buffer has to offer for this char
<ide> StringDecoder.prototype.write = function(buffer) {
<ide> charStr = charBuffer.toString(encoding, 0, charLength);
<ide>
<ide> // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
<del> const charCode = charStr.charCodeAt(charStr.length - 1);
<add> charCode = charStr.charCodeAt(charStr.length - 1);
<ide> if (charCode >= 0xD800 && charCode <= 0xDBFF) {
<ide> charLength += surrogateSize;
<ide> charStr = '';
<ide> StringDecoder.prototype.write = function(buffer) {
<ide> charStr += buffer.toString(encoding, 0, end);
<ide>
<ide> end = charStr.length - 1;
<del> const charCode = charStr.charCodeAt(end);
<add> charCode = charStr.charCodeAt(end);
<ide> // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
<ide> if (charCode >= 0xD800 && charCode <= 0xDBFF) {
<ide> charLength += surrogateSize; | 1 |
Javascript | Javascript | use const where applicable in loaderoptionsplugin | afc128c663e8b4dc448cac0d6bd584053646dce7 | <ide><path>lib/LoaderOptionsPlugin.js
<ide> class LoaderOptionsPlugin {
<ide> }
<ide>
<ide> apply(compiler) {
<del> let options = this.options;
<add> const options = this.options;
<ide> compiler.plugin("compilation", (compilation) => {
<ide> compilation.plugin("normal-module-loader", (context, module) => {
<del> let resource = module.resource;
<add> const resource = module.resource;
<ide> if(!resource) return;
<del> let i = resource.indexOf("?");
<add> const i = resource.indexOf("?");
<ide> if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) {
<del> let filterSet = new Set(["include", "exclude", "test"]);
<add> const filterSet = new Set(["include", "exclude", "test"]);
<ide> Object.keys(options)
<ide> .filter((key) => !filterSet.has(key))
<ide> .forEach((key) => context[key] = options[key]); | 1 |
Javascript | Javascript | improve inspect performance | ad1d1057f9362558fcc76b603458374f5f5a31c5 | <ide><path>lib/internal/util.js
<ide> function getSystemErrorName(err) {
<ide> return entry ? entry[0] : `Unknown system error ${err}`;
<ide> }
<ide>
<del>// getConstructorOf is wrapped into this to save iterations
<del>function getIdentificationOf(obj) {
<del> const original = obj;
<del> let constructor;
<del> let tag;
<del>
<del> while (obj) {
<del> if (constructor === undefined) {
<del> const desc = Object.getOwnPropertyDescriptor(obj, 'constructor');
<del> if (desc !== undefined &&
<del> typeof desc.value === 'function' &&
<del> desc.value.name !== '')
<del> constructor = desc.value.name;
<del> }
<del>
<del> if (tag === undefined) {
<del> const desc = Object.getOwnPropertyDescriptor(obj, Symbol.toStringTag);
<del> if (desc !== undefined) {
<del> if (typeof desc.value === 'string') {
<del> tag = desc.value;
<del> } else if (desc.get !== undefined) {
<del> tag = desc.get.call(original);
<del> if (typeof tag !== 'string')
<del> tag = undefined;
<del> }
<del> }
<del> }
<del>
<del> if (constructor !== undefined && tag !== undefined)
<del> break;
<del>
<del> obj = Object.getPrototypeOf(obj);
<del> }
<del>
<del> return { constructor, tag };
<del>}
<del>
<ide> const kCustomPromisifiedSymbol = Symbol('util.promisify.custom');
<ide> const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');
<ide>
<ide> module.exports = {
<ide> filterDuplicateStrings,
<ide> getConstructorOf,
<ide> getSystemErrorName,
<del> getIdentificationOf,
<ide> isError,
<ide> isInsideNodeModules,
<ide> join,
<ide><path>lib/util.js
<ide> const {
<ide> customInspectSymbol,
<ide> deprecate,
<ide> getSystemErrorName: internalErrorName,
<del> getIdentificationOf,
<ide> isError,
<ide> promisify,
<ide> join,
<ide> function stylizeNoColor(str, styleType) {
<ide> return str;
<ide> }
<ide>
<add>function getConstructorName(obj) {
<add> while (obj) {
<add> const descriptor = Object.getOwnPropertyDescriptor(obj, 'constructor');
<add> if (descriptor !== undefined &&
<add> typeof descriptor.value === 'function' &&
<add> descriptor.value.name !== '') {
<add> return descriptor.value.name;
<add> }
<add>
<add> obj = Object.getPrototypeOf(obj);
<add> }
<add>
<add> return '';
<add>}
<add>
<add>function getPrefix(constructor, tag) {
<add> if (constructor !== '') {
<add> if (tag !== '' && constructor !== tag) {
<add> return `${constructor} [${tag}] `;
<add> }
<add> return `${constructor} `;
<add> }
<add>
<add> if (tag !== '')
<add> return `[${tag}] `;
<add>
<add> return '';
<add>}
<add>
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> // Primitive types cannot have properties
<ide> if (typeof value !== 'object' && typeof value !== 'function') {
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide>
<ide> const keyLength = keys.length + symbols.length;
<ide>
<del> const { constructor, tag } = getIdentificationOf(value);
<del> let prefix = '';
<del> if (constructor && tag && constructor !== tag)
<del> prefix = `${constructor} [${tag}] `;
<del> else if (constructor)
<del> prefix = `${constructor} `;
<del> else if (tag)
<del> prefix = `[${tag}] `;
<del>
<add> const constructor = getConstructorName(value);
<add> let tag = value[Symbol.toStringTag];
<add> if (typeof tag !== 'string')
<add> tag = '';
<ide> let base = '';
<ide> let formatter = formatObject;
<ide> let braces;
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> noIterator = false;
<ide> if (Array.isArray(value)) {
<ide> // Only set the constructor for non ordinary ("Array [...]") arrays.
<add> const prefix = getPrefix(constructor, tag);
<ide> braces = [`${prefix === 'Array ' ? '' : prefix}[`, ']'];
<ide> if (value.length === 0 && keyLength === 0)
<ide> return `${braces[0]}]`;
<ide> formatter = formatArray;
<ide> } else if (isSet(value)) {
<add> const prefix = getPrefix(constructor, tag);
<ide> if (value.size === 0 && keyLength === 0)
<ide> return `${prefix}{}`;
<ide> braces = [`${prefix}{`, '}'];
<ide> formatter = formatSet;
<ide> } else if (isMap(value)) {
<add> const prefix = getPrefix(constructor, tag);
<ide> if (value.size === 0 && keyLength === 0)
<ide> return `${prefix}{}`;
<ide> braces = [`${prefix}{`, '}'];
<ide> formatter = formatMap;
<ide> } else if (isTypedArray(value)) {
<del> braces = [`${prefix}[`, ']'];
<add> braces = [`${getPrefix(constructor, tag)}[`, ']'];
<ide> formatter = formatTypedArray;
<ide> } else if (isMapIterator(value)) {
<ide> braces = [`[${tag}] {`, '}'];
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> }
<ide> if (noIterator) {
<ide> braces = ['{', '}'];
<del> if (prefix === 'Object ') {
<add> if (constructor === 'Object') {
<ide> if (isArgumentsObject(value)) {
<ide> braces[0] = '[Arguments] {';
<ide> if (keyLength === 0)
<ide> return '[Arguments] {}';
<add> } else if (tag !== '') {
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<add> if (keyLength === 0) {
<add> return `${braces[0]}}`;
<add> }
<ide> } else if (keyLength === 0) {
<ide> return '{}';
<ide> }
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> // Fast path for ArrayBuffer and SharedArrayBuffer.
<ide> // Can't do the same for DataView because it has a non-primitive
<ide> // .buffer property that we need to recurse for.
<add> const prefix = getPrefix(constructor, tag);
<ide> if (keyLength === 0)
<ide> return prefix +
<ide> `{ byteLength: ${formatNumber(ctx.stylize, value.byteLength)} }`;
<ide> braces[0] = `${prefix}{`;
<ide> keys.unshift('byteLength');
<ide> } else if (isDataView(value)) {
<del> braces[0] = `${prefix}{`;
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> // .buffer goes last, it's not a primitive like the others.
<ide> keys.unshift('byteLength', 'byteOffset', 'buffer');
<ide> } else if (isPromise(value)) {
<del> braces[0] = `${prefix}{`;
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> formatter = formatPromise;
<ide> } else if (isWeakSet(value)) {
<del> braces[0] = `${prefix}{`;
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> if (ctx.showHidden) {
<ide> formatter = formatWeakSet;
<ide> } else {
<ide> extra = '[items unknown]';
<ide> }
<ide> } else if (isWeakMap(value)) {
<del> braces[0] = `${prefix}{`;
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> if (ctx.showHidden) {
<ide> formatter = formatWeakMap;
<ide> } else {
<ide> function formatValue(ctx, value, recurseTimes, ln) {
<ide> } else if (keyLength === 0) {
<ide> if (isExternal(value))
<ide> return ctx.stylize('[External]', 'special');
<del> return `${prefix}{}`;
<add> return `${getPrefix(constructor, tag)}{}`;
<ide> } else {
<del> braces[0] = `${prefix}{`;
<add> braces[0] = `${getPrefix(constructor, tag)}{`;
<ide> }
<ide> }
<ide> }
<ide> function formatNumber(fn, value) {
<ide> function formatPrimitive(fn, value, ctx) {
<ide> if (typeof value === 'string') {
<ide> if (ctx.compact === false &&
<del> value.length > MIN_LINE_LENGTH &&
<del> ctx.indentationLvl + value.length > ctx.breakLength) {
<add> ctx.indentationLvl + value.length > ctx.breakLength &&
<add> value.length > MIN_LINE_LENGTH) {
<ide> // eslint-disable-next-line max-len
<ide> const minLineLength = Math.max(ctx.breakLength - ctx.indentationLvl, MIN_LINE_LENGTH);
<ide> // eslint-disable-next-line max-len
<ide> function formatPrimitive(fn, value, ctx) {
<ide> // eslint-disable-next-line max-len, node-core/no-unescaped-regexp-dot
<ide> readableRegExps[divisor] = new RegExp(`(.|\\n){1,${divisor}}(\\s|$)|(\\n|.)+?(\\s|$)`, 'gm');
<ide> }
<del> const indent = ' '.repeat(ctx.indentationLvl);
<ide> const matches = value.match(readableRegExps[divisor]);
<ide> if (matches.length > 1) {
<add> const indent = ' '.repeat(ctx.indentationLvl);
<ide> res += `${fn(strEscape(matches[0]), 'string')} +\n`;
<ide> for (var i = 1; i < matches.length - 1; i++) {
<ide> res += `${indent} ${fn(strEscape(matches[i]), 'string')} +\n`; | 2 |
Javascript | Javascript | improve coverage in test-crypto.dh | fcf3cbed281118598751c7c71c5323963f61c5dc | <ide><path>test/pummel/test-crypto-dh.js
<ide> if (!common.hasCrypto) {
<ide> return;
<ide> }
<ide>
<del>assert.throws(function() {
<del> crypto.getDiffieHellman('unknown-group');
<del>});
<del>assert.throws(function() {
<del> crypto.getDiffieHellman('modp1').setPrivateKey('');
<del>});
<del>assert.throws(function() {
<del> crypto.getDiffieHellman('modp1').setPublicKey('');
<del>});
<add>assert.throws(
<add> function() {
<add> crypto.getDiffieHellman('unknown-group');
<add> },
<add> /^Error: Unknown group$/,
<add> 'crypto.getDiffieHellman(\'unknown-group\') ' +
<add> 'failed to throw the expected error.'
<add>);
<add>assert.throws(
<add> function() {
<add> crypto.getDiffieHellman('modp1').setPrivateKey('');
<add> },
<add> new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' +
<add> 'setPrivateKey is not a function$'),
<add> 'crypto.getDiffieHellman(\'modp1\').setPrivateKey(\'\') ' +
<add> 'failed to throw the expected error.'
<add>);
<add>assert.throws(
<add> function() {
<add> crypto.getDiffieHellman('modp1').setPublicKey('');
<add> },
<add> new RegExp('^TypeError: crypto\\.getDiffieHellman\\(\\.\\.\\.\\)\\.' +
<add> 'setPublicKey is not a function$'),
<add> 'crypto.getDiffieHellman(\'modp1\').setPublicKey(\'\') ' +
<add> 'failed to throw the expected error.'
<add>);
<ide>
<ide> const hashes = {
<ide> modp1: '630e9acd2cc63f7e80d8507624ba60ac0757201a', | 1 |
Javascript | Javascript | add abstract crossorigin method on tech | 245efacb59d1cf95cd429a4324cbcb6377630a98 | <ide><path>src/js/tech/tech.js
<ide> class Tech extends Component {
<ide> */
<ide> reset() {}
<ide>
<add> /**
<add> * Get the value of `crossOrigin` from the tech.
<add> *
<add> * @abstract
<add> *
<add> * @see {Html5#crossOrigin}
<add> */
<add> crossOrigin() {}
<add>
<add> /**
<add> * Set the value of `crossOrigin` on the tech.
<add> *
<add> * @abstract
<add> *
<add> * @param {string} crossOrigin the crossOrigin value
<add> * @see {Html5#setCrossOrigin}
<add> */
<add> setCrossOrigin() {}
<add>
<ide> /**
<ide> * Get or set an error on the Tech.
<ide> * | 1 |
Text | Text | remove the activerecordhelper section | 21ef4e17ec03e408f366a3b3dbbb925835e0ab7f | <ide><path>guides/source/action_view_overview.md
<ide> Overview of all the helpers provided by Action View
<ide>
<ide> The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
<ide>
<del>### ActiveRecordHelper
<del>TODO: Is it me or there's no ActiveRecordHelper? *Agis-*
<del>
<del>The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the [Rails Form helpers guide](http://guides.rubyonrails.org/form_helpers.html).
<del>
<del>#### error_message_on
<del>
<del>Returns a string containing the error message attached to the method on the object if one exists.
<del>
<del>```ruby
<del>error_message_on "post", "title"
<del>```
<del>
<del>#### error_messages_for
<del>
<del>Returns a string with a DIV containing all of the error messages for the objects located as instance variables by the names given.
<del>
<del>```ruby
<del>error_messages_for "post"
<del>```
<del>
<del>#### form
<del>
<del>Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a `@post` with attributes named `title` of type `String` and `body` of type `Text`. Calling `form` would produce a form to creating a new post with inputs for those attributes.
<del>
<del>```ruby
<del>form("post")
<del>```
<del>
<del>```html
<del><form action='/posts/create' method='post'>
<del> <p>
<del> <label for="post_title">Title</label><br />
<del> <input id="post_title" name="post[title]" type="text" value="Hello World" />
<del> </p>
<del> <p>
<del> <label for="post_body">Body</label><br />
<del> <textarea id="post_body" name="post[body]"></textarea>
<del> </p>
<del> <input name="commit" type="submit" value="Create" />
<del></form>
<del>```
<del>
<del>Typically, `form_for` is used instead of `form` because it doesn't automatically include all of the model's attributes.
<del>
<del>#### input
<del>
<del>Returns a default input tag for the type of object returned by the method.
<del>
<del>For example, if `@post` has an attribute `title` mapped to a `String` column that holds "Hello World":
<del>
<del>```ruby
<del>input("post", "title") # =>
<del> <input id="post_title" name="post[title]" type="text" value="Hello World" />
<del>```
<del>
<ide> ### RecordTagHelper
<ide>
<ide> This module provides methods for generating container tags, such as `div`, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use. | 1 |
Javascript | Javascript | use an apostrophe to indicate ownership | 91e4ad0b5b4dc2e78898d36aef5381c951d74a10 | <ide><path>packages/ember-views/lib/views/component.js
<ide> var get = Ember.get, set = Ember.set, isNone = Ember.isNone,
<ide> ```handlebars
<ide> {{#app-profile person=currentUser}}
<ide> <p>Admin mode</p>
<del> {{! Executed in the controllers context. }}
<add> {{! Executed in the controller's context. }}
<ide> {{/app-profile}}
<ide> ```
<ide> | 1 |
Python | Python | add python3.4 to paver file | b3f497571ebb7eb54065c5e801672f667bc185cd | <ide><path>pavement.py
<ide> "2.7": ["/Library/Frameworks/Python.framework/Versions/2.7/bin/python"],
<ide> "3.2": ["/Library/Frameworks/Python.framework/Versions/3.2/bin/python3"],
<ide> "3.3": ["/Library/Frameworks/Python.framework/Versions/3.3/bin/python3"],
<add> "3.4": ["/Library/Frameworks/Python.framework/Versions/3.4/bin/python3"],
<ide> }
<ide>
<ide> SSE3_CFG = {'ATLAS': r'C:\local\lib\atlas\sse3'}
<ide>
<ide> if sys.platform =="darwin":
<ide> WINDOWS_PYTHON = {
<add> "3.4": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python34/python.exe"],
<ide> "3.3": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python33/python.exe"],
<ide> "3.2": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python32/python.exe"],
<ide> "2.7": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python27/python.exe"],
<ide> MAKENSIS = ["wine", "makensis"]
<ide> elif sys.platform == "win32":
<ide> WINDOWS_PYTHON = {
<add> "3.4": ["C:\Python34\python.exe"],
<ide> "3.3": ["C:\Python33\python.exe"],
<ide> "3.2": ["C:\Python32\python.exe"],
<ide> "2.7": ["C:\Python27\python.exe"],
<ide> MAKENSIS = ["makensis"]
<ide> else:
<ide> WINDOWS_PYTHON = {
<add> "3.4": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python34/python.exe"],
<ide> "3.3": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python33/python.exe"],
<ide> "3.2": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python32/python.exe"],
<ide> "2.7": ["wine", os.environ['HOME'] + "/.wine/drive_c/Python27/python.exe"], | 1 |
PHP | PHP | fix blade sequential compilestring calls | 1c8e24deee344668baf0bb40c78e286b361d6862 | <ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> class BladeCompiler extends Compiler implements CompilerInterface {
<ide> */
<ide> public function compile($path = null)
<ide> {
<del> $this->footer = array();
<del>
<ide> if ($path)
<ide> {
<ide> $this->setPath($path);
<ide> public function setPath($path)
<ide> public function compileString($value)
<ide> {
<ide> $result = '';
<add> // reset compiler state before compilation
<add> $this->footer = array();
<ide>
<ide> // Here we will loop through all of the tokens returned by the Zend lexer and
<ide> // parse each one into the corresponding valid PHP. We will then have this
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testRetrieveDefaultEscapedContentTags()
<ide> $this->assertEquals(['{{{', '}}}'], $compiler->getEscapedContentTags());
<ide> }
<ide>
<add> public function testSequentialCompileStringCalls()
<add> {
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add> $string = '@extends(\'foo\')
<add>test';
<add> $expected = "test".PHP_EOL.'<?php echo $__env->make(\'foo\', array_except(get_defined_vars(), array(\'__data\', \'__path\')))->render(); ?>';
<add> $this->assertEquals($expected, $compiler->compileString($string));
<add>
<add> // use the same compiler instance to compile another template with @extends directive
<add> $string = '@extends(name(foo))'.PHP_EOL.'test';
<add> $expected = "test".PHP_EOL.'<?php echo $__env->make(name(foo), array_except(get_defined_vars(), array(\'__data\', \'__path\')))->render(); ?>';
<add> $this->assertEquals($expected, $compiler->compileString($string));
<add> }
<add>
<ide>
<ide> /**
<ide> * @dataProvider testGetTagsProvider() | 2 |
Ruby | Ruby | improve spec helper | a6be0e62affe150a11d5361636505930744318b0 | <ide><path>Library/Homebrew/test/spec_helper.rb
<ide> def find_files
<ide> @__argv = ARGV.dup
<ide> @__env = ENV.to_hash # dup doesn't work on ENV
<ide>
<add> @__stdout = $stdout.clone
<add> @__stderr = $stderr.clone
<add>
<ide> unless example.metadata.key?(:focus) || ENV.key?("VERBOSE_TESTS")
<del> @__stdout = $stdout.clone
<del> @__stderr = $stderr.clone
<ide> $stdout.reopen(File::NULL)
<ide> $stderr.reopen(File::NULL)
<ide> end
<ide>
<ide> example.run
<add> rescue SystemExit => e
<add> raise "Unexpected exit with status #{e.status}."
<ide> ensure
<ide> ARGV.replace(@__argv)
<ide> ENV.replace(@__env)
<ide>
<del> unless example.metadata.key?(:focus) || ENV.key?("VERBOSE_TESTS")
<del> $stdout.reopen(@__stdout)
<del> $stderr.reopen(@__stderr)
<del> @__stdout.close
<del> @__stderr.close
<del> end
<add> $stdout.reopen(@__stdout)
<add> $stderr.reopen(@__stderr)
<add> @__stdout.close
<add> @__stderr.close
<ide>
<ide> Formulary.clear_cache
<ide> Tap.clear_cache | 1 |
Ruby | Ruby | add reason to 'usageerror' exception | d9363a15590ddb8aad3e8e5444a972eaa79fd05e | <ide><path>Library/Homebrew/exceptions.rb
<del>class UsageError < RuntimeError; end
<del>class FormulaUnspecifiedError < UsageError; end
<del>class KegUnspecifiedError < UsageError; end
<add>class UsageError < RuntimeError
<add> attr_reader :reason
<add>
<add> def initialize(reason = nil)
<add> @reason = reason
<add> end
<add>
<add> def to_s
<add> s = "Invalid usage"
<add> s += ": #{reason}" if reason
<add> s
<add> end
<add>end
<add>
<add>class FormulaUnspecifiedError < UsageError
<add> def initialize
<add> super "This command requires a formula argument"
<add> end
<add>end
<add>
<add>class KegUnspecifiedError < UsageError
<add> def initialize
<add> super "This command requires a keg argument"
<add> end
<add>end
<ide>
<ide> class MultipleVersionsInstalledError < RuntimeError
<ide> attr_reader :name
<ide><path>Library/brew.rb
<ide> def require?(path)
<ide> end
<ide> end
<ide>
<del>rescue FormulaUnspecifiedError
<del> abort "This command requires a formula argument"
<del>rescue KegUnspecifiedError
<del> abort "This command requires a keg argument"
<del>rescue UsageError
<add>rescue UsageError => e
<ide> require "cmd/help"
<del> Homebrew.help cmd, :usage_error => "Invalid usage"
<add> Homebrew.help cmd, :usage_error => e.message
<ide> rescue SystemExit => e
<ide> onoe "Kernel.exit" if ARGV.verbose? && !e.success?
<ide> $stderr.puts e.backtrace if ARGV.debug? | 2 |
Javascript | Javascript | avoid turbofan deopt in arrays bench | eefdf452c35fd79d5588d2338989d55ebaf52763 | <ide><path>benchmark/arrays/var-int.js
<ide> function main(conf) {
<ide> bench.start();
<ide> var arr = new clazz(n * 1e6);
<ide> for (var i = 0; i < 10; ++i) {
<add> run();
<add> }
<add> bench.end(n);
<add>
<add> function run() {
<ide> for (var j = 0, k = arr.length; j < k; ++j) {
<ide> arr[j] = (j ^ k) & 127;
<ide> }
<ide> }
<del> bench.end(n);
<ide> }
<ide><path>benchmark/arrays/zero-float.js
<ide> function main(conf) {
<ide> bench.start();
<ide> var arr = new clazz(n * 1e6);
<ide> for (var i = 0; i < 10; ++i) {
<add> run();
<add> }
<add> bench.end(n);
<add>
<add> function run() {
<ide> for (var j = 0, k = arr.length; j < k; ++j) {
<ide> arr[j] = 0.0;
<ide> }
<ide> }
<del> bench.end(n);
<ide> }
<ide><path>benchmark/arrays/zero-int.js
<ide> function main(conf) {
<ide> bench.start();
<ide> var arr = new clazz(n * 1e6);
<ide> for (var i = 0; i < 10; ++i) {
<add> run();
<add> }
<add> bench.end(n);
<add>
<add> function run() {
<ide> for (var j = 0, k = arr.length; j < k; ++j) {
<ide> arr[j] = 0;
<ide> }
<ide> }
<del> bench.end(n);
<ide> } | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.